ofsht 0.6.0

Git worktree management tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Add command - Create new worktrees with GitHub integration and tmux support

use anyhow::{Context, Result};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use std::process::Command;
use std::time::Duration;

use crate::color;
use crate::commands::common::get_main_repo_root;
use crate::config;
use crate::domain::worktree::normalize_absolute_path;
use crate::hooks;
use crate::integrations;
use crate::integrations::tmux::TmuxLauncher;

/// Process a PR and return branch name and start point
fn process_pr(
    pr: &integrations::gh::PrInfo,
    number: u32,
    repo_root: &std::path::Path,
    color_mode: color::ColorMode,
) -> Result<(String, Option<String>)> {
    // Check if it's from a fork (cross-repository PR)
    let is_fork = pr.is_cross_repository;

    if is_fork {
        // Fork PR - fetch PR ref from GitHub without checking out
        let fetch_output = Command::new("git")
            .args(["fetch", "origin", &format!("refs/pull/{number}/head")])
            .current_dir(repo_root)
            .output()
            .context("Failed to execute git fetch")?;

        if !fetch_output.status.success() {
            let stderr = String::from_utf8_lossy(&fetch_output.stderr);
            anyhow::bail!("git fetch PR ref failed: {stderr}");
        }

        // Check if local branch with PR's name already exists
        let branch_exists = Command::new("git")
            .args(["rev-parse", "--verify", &pr.head_ref_name])
            .current_dir(repo_root)
            .output()
            .is_ok_and(|o| o.status.success());

        eprintln!(
            "{}",
            color::success(
                color_mode,
                &format!("Fetched PR #{}: {} (fork)", pr.number, pr.title)
            )
        );

        if branch_exists {
            // Conflict: local branch already exists, use unique name
            let sanitized_ref = pr.head_ref_name.replace('/', "-");
            let unique_branch = format!("pr-{number}-{sanitized_ref}");

            eprintln!(
                "{}",
                color::warn(
                    color_mode,
                    &format!(
                        "Local branch '{}' already exists. Using '{}' instead.",
                        pr.head_ref_name, unique_branch
                    )
                )
            );

            Ok((unique_branch, Some("FETCH_HEAD".to_string())))
        } else {
            // Use PR's original branch name
            Ok((pr.head_ref_name.clone(), Some("FETCH_HEAD".to_string())))
        }
    } else {
        // Same repository - fetch the branch
        let fetch_output = Command::new("git")
            .args(["fetch", "origin", &pr.head_ref_name])
            .current_dir(repo_root)
            .output()
            .context("Failed to execute git fetch")?;

        if !fetch_output.status.success() {
            let stderr = String::from_utf8_lossy(&fetch_output.stderr);
            anyhow::bail!("git fetch failed: {stderr}");
        }

        eprintln!(
            "{}",
            color::success(
                color_mode,
                &format!("Fetched PR #{}: {}", pr.number, pr.title)
            )
        );

        // Check if local branch already exists
        let branch_exists = Command::new("git")
            .args(["rev-parse", "--verify", &pr.head_ref_name])
            .current_dir(repo_root)
            .output()
            .is_ok_and(|o| o.status.success());

        if branch_exists {
            // Existing local branch - use it directly
            Ok((pr.head_ref_name.clone(), None))
        } else {
            // Create new branch tracking remote
            Ok((
                pr.head_ref_name.clone(),
                Some(format!("origin/{}", pr.head_ref_name)),
            ))
        }
    }
}

/// Resolve branch name and start point from GitHub issue/PR
#[allow(clippy::type_complexity)]
fn resolve_github_ref(
    gh_client: &impl integrations::gh::GhClient,
    number: u32,
    start_point: Option<&str>,
    repo_root: &std::path::Path,
    color_mode: color::ColorMode,
) -> Result<(String, Option<String>)> {
    if !gh_client.is_available() {
        anyhow::bail!(
            "GitHub CLI (gh) is not installed or not available.\n\
             Please install gh from https://cli.github.com/ to use GitHub integration.\n\
             Alternatively, use a regular branch name instead of #{number}."
        );
    }

    // Try PR first, then issue if PR fails
    match gh_client.pr_info(number) {
        Ok(pr) => process_pr(&pr, number, repo_root, color_mode),
        Err(_pr_err) => match gh_client.issue_info(number) {
            Ok(issue) => {
                let branch_name = integrations::gh::build_issue_branch(number);
                eprintln!(
                    "{}",
                    color::success(
                        color_mode,
                        &format!("Fetched issue #{}: {}", issue.number, issue.title)
                    )
                );
                Ok((branch_name, start_point.map(String::from)))
            }
            Err(_issue_err) => {
                anyhow::bail!(
                    "#{number} is not a valid issue or pull request.\n\
                     Please check the number and try again."
                );
            }
        },
    }
}

/// Determine if tmux integration should be used based on flags and config
const fn should_use_tmux(
    behavior: config::TmuxBehavior,
    tmux_flag: bool,
    no_tmux_flag: bool,
) -> bool {
    // Priority: --no-tmux > --tmux > behavior setting
    if no_tmux_flag {
        return false;
    }
    if tmux_flag {
        return true;
    }
    // behavior: Auto (default), Always, Never
    matches!(behavior, config::TmuxBehavior::Always)
}

/// Add command - Create new worktree with optional GitHub integration and tmux support
///
/// # Errors
/// Returns an error if:
/// - Not in a git repository
/// - Git worktree creation fails
/// - Zoxide registration fails
#[allow(clippy::too_many_lines, clippy::missing_panics_doc)]
pub fn cmd_new(
    branch: &str,
    start_point: Option<&str>,
    tmux: bool,
    no_tmux: bool,
    color_mode: color::ColorMode,
) -> Result<()> {
    // Get main repository root
    let repo_root = get_main_repo_root()?;

    // Load configuration from repo root
    let config = config::Config::load_from_repo_root(&repo_root)?;

    // Parse branch input to detect GitHub issue/PR references
    let branch_input = integrations::gh::BranchInput::parse(branch);

    // Resolve actual branch name and optional start point from GitHub if needed
    let (actual_branch, actual_start_point) = match branch_input {
        integrations::gh::BranchInput::Github(number) if config.integrations.gh.enabled => {
            let gh_client = integrations::gh::RealGhClient;
            resolve_github_ref(&gh_client, number, start_point, &repo_root, color_mode)?
        }
        integrations::gh::BranchInput::Github(number) => {
            // GitHub integration is disabled
            eprintln!(
                "{}",
                color::warn(
                    color_mode,
                    &format!(
                        "GitHub integration is disabled. Treating '#{number}' as a literal branch name.\n\
                         To enable GitHub integration, set enabled = true in [integration.gh] in your global config."
                    )
                )
            );
            (branch.to_string(), start_point.map(String::from))
        }
        integrations::gh::BranchInput::Plain(name) => (name, start_point.map(String::from)),
    };

    let branch = &actual_branch;
    let start_point = actual_start_point.as_deref();

    // Determine if tmux should be used based on flags and config
    let use_tmux = should_use_tmux(config.integrations.tmux.behavior, tmux, no_tmux);

    // Early detection if tmux integration is requested
    if use_tmux {
        let launcher = integrations::tmux::RealTmuxLauncher;
        launcher.detect()?;
    }
    let repo_name = repo_root
        .file_name()
        .and_then(|n| n.to_str())
        .context("Failed to get repository name")?;

    // Expand path template
    #[allow(clippy::literal_string_with_formatting_args)]
    let path_template = config
        .worktree
        .dir
        .replace("{repo}", repo_name)
        .replace("{branch}", branch);

    // Create worktree path (relative paths are resolved from repo root)
    let worktree_path = if path_template.starts_with('/') {
        std::path::PathBuf::from(&path_template)
    } else {
        repo_root.join(&path_template)
    };

    let mp = MultiProgress::new();
    let is_tty = color_mode.should_colorize();

    // Header spinner (TTY) — after GH fetch, before git worktree add
    let header_pb = if is_tty {
        let pb = mp.add(ProgressBar::new_spinner());
        pb.set_style(
            ProgressStyle::default_spinner()
                .template("{spinner:.cyan} {msg}")
                .unwrap(),
        );
        pb.set_message(format!("Adding {branch}"));
        pb.enable_steady_tick(Duration::from_millis(100));
        Some(pb)
    } else {
        None
    };

    // Create worktree using git worktree add
    let mut cmd = Command::new("git");

    if let Some(sp) = start_point {
        // Create new branch with start point
        cmd.args(["worktree", "add", "-b", branch])
            .arg(&worktree_path)
            .arg(sp);
    } else {
        // No start_point: try to checkout existing branch, or create from HEAD
        // Check if branch exists
        let branch_exists = Command::new("git")
            .args(["rev-parse", "--verify", branch])
            .current_dir(&repo_root)
            .output()
            .is_ok_and(|o| o.status.success());

        if branch_exists {
            // Checkout existing branch (no -b flag)
            cmd.args(["worktree", "add"])
                .arg(&worktree_path)
                .arg(branch);
        } else {
            // Create new branch from HEAD
            cmd.args(["worktree", "add", "-b", branch])
                .arg(&worktree_path);
        }
    }

    let output = cmd.output().context("Failed to execute git worktree add")?;

    if !output.status.success() {
        if let Some(pb) = header_pb {
            pb.finish_and_clear();
        }
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git worktree add failed: {stderr}");
    }

    // non-TTY: print header before hooks (rm/sync pattern)
    if !is_tty {
        eprintln!("{}", color::success(color_mode, format!("Added {branch}")));
    }

    // Execute create hooks
    if !config.hooks.create.run.is_empty()
        || !config.hooks.create.copy.is_empty()
        || !config.hooks.create.link.is_empty()
    {
        hooks::execute_hooks_lenient_with_mp(
            &config.hooks.create,
            &worktree_path,
            &repo_root,
            color_mode,
            "  ",
            &mp,
        );
    }

    // Finish header: Adding → Added
    if let Some(pb) = header_pb {
        pb.set_style(ProgressStyle::with_template("{msg}").unwrap());
        pb.finish_with_message(format!(
            "{}",
            color::success(color_mode, format!("Added {branch}"))
        ));
    }

    // Add to zoxide if enabled
    integrations::zoxide::add_to_zoxide_if_enabled(
        &worktree_path,
        config.integrations.zoxide.enabled,
    )?;

    // Create tmux window or pane if enabled
    if use_tmux {
        let launcher = integrations::tmux::RealTmuxLauncher;
        let result = match config.integrations.tmux.create.as_str() {
            "pane" => launcher.create_pane(&worktree_path),
            _ => launcher.create_window(&worktree_path, branch),
        };
        if let Err(e) = result {
            eprintln!("Warning: tmux creation failed: {e}");
        }
        // Don't print path to stdout when using tmux
        // (prevents shell integration from cd'ing in the calling shell)
    } else {
        // Print normalized absolute path to STDOUT for shell wrapper integration
        println!("{}", normalize_absolute_path(&worktree_path));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_should_use_tmux_no_tmux_flag_priority() {
        use config::TmuxBehavior;
        // --no-tmux has highest priority
        assert!(!should_use_tmux(TmuxBehavior::Always, true, true));
        assert!(!should_use_tmux(TmuxBehavior::Always, false, true));
        assert!(!should_use_tmux(TmuxBehavior::Auto, true, true));
        assert!(!should_use_tmux(TmuxBehavior::Auto, false, true));
    }

    #[test]
    fn test_should_use_tmux_tmux_flag_priority() {
        use config::TmuxBehavior;
        // --tmux has second priority
        assert!(should_use_tmux(TmuxBehavior::Never, true, false));
        assert!(should_use_tmux(TmuxBehavior::Auto, true, false));
        assert!(should_use_tmux(TmuxBehavior::Always, true, false));
    }

    #[test]
    fn test_should_use_tmux_behavior_auto() {
        use config::TmuxBehavior;
        // behavior=Auto defaults to false
        assert!(!should_use_tmux(TmuxBehavior::Auto, false, false));
    }

    #[test]
    fn test_should_use_tmux_behavior_always() {
        use config::TmuxBehavior;
        // behavior=Always enables tmux
        assert!(should_use_tmux(TmuxBehavior::Always, false, false));
    }

    #[test]
    fn test_should_use_tmux_behavior_never() {
        use config::TmuxBehavior;
        // behavior=Never disables tmux (unless --tmux is specified)
        assert!(!should_use_tmux(TmuxBehavior::Never, false, false));
    }

    #[test]
    fn test_resolve_github_ref_issue_path() {
        let mock = integrations::gh::MockGhClient::new()
            .with_pr_error("not found")
            .with_issue(integrations::gh::IssueInfo {
                number: 33,
                title: "Test issue".to_string(),
                url: "https://github.com/owner/repo/issues/33".to_string(),
            });

        let result = resolve_github_ref(
            &mock,
            33,
            None,
            std::path::Path::new("/tmp"),
            color::ColorMode::Never,
        );

        let (branch, start_point) = result.unwrap();
        assert_eq!(branch, "issue-33");
        assert!(start_point.is_none());
    }

    #[test]
    fn test_resolve_github_ref_issue_path_with_start_point() {
        let mock = integrations::gh::MockGhClient::new()
            .with_pr_error("not found")
            .with_issue(integrations::gh::IssueInfo {
                number: 33,
                title: "Test issue".to_string(),
                url: "https://github.com/owner/repo/issues/33".to_string(),
            });

        let result = resolve_github_ref(
            &mock,
            33,
            Some("develop"),
            std::path::Path::new("/tmp"),
            color::ColorMode::Never,
        );

        let (branch, start_point) = result.unwrap();
        assert_eq!(branch, "issue-33");
        assert_eq!(start_point.as_deref(), Some("develop"));
    }

    #[test]
    fn test_resolve_github_ref_both_fail() {
        let mock = integrations::gh::MockGhClient::new()
            .with_pr_error("no pr")
            .with_issue_error("no issue");

        let result = resolve_github_ref(
            &mock,
            999,
            None,
            std::path::Path::new("/tmp"),
            color::ColorMode::Never,
        );

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("not a valid issue or pull request"),
            "unexpected error: {err}"
        );
    }
}