git-workon-lib 0.2.0

API for managing worktrees
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
//! Worktree descriptor and metadata access.
//!
//! This module provides the core `WorktreeDescriptor` type that wraps git2's `Worktree`
//! and exposes rich metadata about worktree state.
//!
//! ## Completed Metadata Methods
//!
//! The following metadata is fully implemented and working:
//! - **Basic info**: `name()`, `path()`, `branch()`
//! - **State detection**: `is_detached()`, `is_dirty()`, `is_valid()`, `is_locked()`
//! - **Remote tracking**: `remote()`, `remote_branch()`, `remote_url()`, `remote_fetch_url()`, `remote_push_url()`
//! - **Commit info**: `head_commit()`
//! - **Status checks**: `has_unpushed_commits()`, `is_behind_upstream()`, `has_gone_upstream()`, `is_merged_into()`
//!
//! These methods enable status filtering (`--dirty`, `--ahead`, `--behind`, `--gone`) and
//! interactive display with status indicators.
//!
//! ## Branch Types
//!
//! Supports three branch types for worktree creation:
//! - **Normal**: Standard branch, tracks existing or creates from HEAD
//! - **Orphan**: Independent history with initial empty commit (for documentation, gh-pages, etc.)
//! - **Detached**: Detached HEAD state (for exploring specific commits)
//!
//! - **Activity tracking**: `last_activity()`, `is_stale()`
//!
//! ## Future Extensions
//!
//! Planned metadata methods for smart worktree management:
//!
//! TODO: Add worktree notes/descriptions support
//! - Store user-provided notes/context for worktrees
//! - Help remember why a worktree was created
//! - Storage strategy TBD (git notes, config, or metadata file)

use std::{fmt, fs::create_dir_all, path::Path};

use git2::WorktreeAddOptions;
use git2::{Repository, Worktree};
use log::debug;

use crate::error::{Result, WorktreeError};
use crate::workon_root;

/// Type of branch to create for a new worktree
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BranchType {
    /// Normal branch - track existing or create from HEAD
    #[default]
    Normal,
    /// Orphan branch - independent history with initial empty commit
    Orphan,
    /// Detached HEAD
    Detached,
}

/// A handle to a git worktree with rich metadata access.
///
/// Wraps a [`git2::Worktree`] and exposes branch state, remote tracking info,
/// commit history, and status checks used by the CLI commands.
pub struct WorktreeDescriptor {
    worktree: Worktree,
}

impl WorktreeDescriptor {
    /// Open a worktree by name within the given repository.
    pub fn new(repo: &Repository, name: &str) -> Result<Self> {
        Ok(Self {
            worktree: repo.find_worktree(name)?,
        })
    }

    /// Wrap an existing [`git2::Worktree`] without a repository lookup.
    pub fn of(worktree: Worktree) -> Self {
        Self { worktree }
    }

    /// Returns the name of the worktree, or `None` if the name is invalid UTF-8.
    pub fn name(&self) -> Option<&str> {
        self.worktree.name()
    }

    /// Returns the filesystem path to the worktree's working directory.
    pub fn path(&self) -> &Path {
        self.worktree.path()
    }

    /// Returns the branch name if the worktree is on a branch, or None if detached.
    ///
    /// This reads the HEAD file from the worktree's git directory to determine
    /// if HEAD points to a branch reference or directly to a commit SHA.
    pub fn branch(&self) -> Result<Option<String>> {
        use std::fs;

        // Get the path to the worktree's HEAD file
        let git_dir = self.worktree.path().join(".git");
        let head_path = if git_dir.is_file() {
            // Linked worktree - read .git file to find actual git directory
            let git_file_content = fs::read_to_string(&git_dir)?;
            let git_dir_path = git_file_content
                .strip_prefix("gitdir: ")
                .and_then(|s| s.trim().strip_suffix('\n').or(Some(s.trim())))
                .ok_or(WorktreeError::InvalidGitFile)?;
            Path::new(git_dir_path).join("HEAD")
        } else {
            // Main worktree
            git_dir.join("HEAD")
        };

        let head_content = fs::read_to_string(&head_path)?;

        // HEAD file contains either:
        // - "ref: refs/heads/branch-name" for a branch
        // - A direct SHA for detached HEAD
        if let Some(ref_line) = head_content.strip_prefix("ref: ") {
            let ref_name = ref_line.trim();
            Ok(ref_name.strip_prefix("refs/heads/").map(|s| s.to_string()))
        } else {
            // Direct SHA - detached HEAD
            Ok(None)
        }
    }

    /// Returns true if the worktree has a detached HEAD (not on a branch).
    pub fn is_detached(&self) -> Result<bool> {
        Ok(self.branch()?.is_none())
    }

    /// Returns true if the worktree has uncommitted changes (dirty working tree).
    ///
    /// This includes:
    /// - Modified files (staged or unstaged)
    /// - New untracked files
    /// - Deleted files
    pub fn is_dirty(&self) -> Result<bool> {
        let repo = Repository::open(self.path())?;
        let statuses = repo.statuses(None)?;
        Ok(!statuses.is_empty())
    }

    /// Returns true if the worktree has a lock file.
    ///
    /// Locked worktrees are protected from pruning unless `--include-locked`
    /// or `--force` is used.
    pub fn is_locked(&self) -> Result<bool> {
        Ok(!matches!(
            self.worktree.is_locked()?,
            git2::WorktreeLockStatus::Unlocked
        ))
    }

    /// Returns true if the worktree's path and git metadata are intact.
    ///
    /// A worktree is invalid if its directory is missing or its git
    /// metadata is broken.
    pub fn is_valid(&self) -> bool {
        self.worktree.validate().is_ok()
    }

    /// Returns true if the worktree has uncommitted changes to tracked files.
    ///
    /// Unlike `is_dirty()`, this excludes untracked files. Use this when
    /// untracked files should not block an operation (e.g. pruning a worktree
    /// whose remote branch is gone).
    pub fn has_tracked_changes(&self) -> Result<bool> {
        let repo = Repository::open(self.path())?;
        let mut opts = git2::StatusOptions::new();
        opts.include_untracked(false);
        let statuses = repo.statuses(Some(&mut opts))?;
        Ok(!statuses.is_empty())
    }

    /// Returns true if the worktree's branch has unpushed commits (ahead of upstream).
    ///
    /// Returns false if:
    /// - The worktree is detached (no branch)
    /// - The branch has no upstream configured
    /// - The branch is up to date with upstream
    ///
    /// Returns true if:
    /// - The branch has commits ahead of its upstream
    /// - The upstream is configured but the remote reference is gone (conservative)
    pub fn has_unpushed_commits(&self) -> Result<bool> {
        // Get the branch name - return false if detached
        let branch_name = match self.branch()? {
            Some(name) => name,
            None => return Ok(false), // Detached HEAD, no branch to check
        };

        // Open the repository (use the bare repo, not the worktree)
        let repo = Repository::open(self.path())?;

        // Find the local branch
        let branch = match repo.find_branch(&branch_name, git2::BranchType::Local) {
            Ok(b) => b,
            Err(_) => return Ok(false), // Branch doesn't exist
        };

        // Check if upstream is configured via git config
        let config = repo.config()?;
        let remote_key = format!("branch.{}.remote", branch_name);

        // If no upstream is configured, there can't be unpushed commits
        let _remote = match config.get_string(&remote_key) {
            Ok(r) => r,
            Err(_) => return Ok(false), // No remote configured
        };

        // Get the upstream branch
        let upstream = match branch.upstream() {
            Ok(u) => u,
            Err(_) => {
                // Upstream is configured but ref is gone - conservatively assume unpushed
                return Ok(true);
            }
        };

        // Get the local and upstream commit OIDs
        let local_oid = branch
            .get()
            .target()
            .ok_or(WorktreeError::NoLocalBranchTarget)?;
        let upstream_oid = upstream
            .get()
            .target()
            .ok_or(WorktreeError::NoBranchTarget)?;

        // Check if local is ahead of upstream
        let (ahead, _behind) = repo.graph_ahead_behind(local_oid, upstream_oid)?;

        Ok(ahead > 0)
    }

    /// Returns true if the worktree's branch is behind its upstream.
    ///
    /// Returns false if:
    /// - The worktree is detached (no branch)
    /// - The branch has no upstream configured
    /// - The branch is up to date with upstream
    /// - The upstream is configured but the remote reference is gone
    ///
    /// Returns true if:
    /// - The branch has commits behind its upstream
    pub fn is_behind_upstream(&self) -> Result<bool> {
        // Get the branch name - return false if detached
        let branch_name = match self.branch()? {
            Some(name) => name,
            None => return Ok(false), // Detached HEAD, no branch to check
        };

        // Open the repository
        let repo = Repository::open(self.path())?;

        // Find the local branch
        let branch = match repo.find_branch(&branch_name, git2::BranchType::Local) {
            Ok(b) => b,
            Err(_) => return Ok(false), // Branch doesn't exist
        };

        // Check if upstream is configured via git config
        let config = repo.config()?;
        let remote_key = format!("branch.{}.remote", branch_name);

        // If no upstream is configured, can't be behind
        let _remote = match config.get_string(&remote_key) {
            Ok(r) => r,
            Err(_) => return Ok(false), // No remote configured
        };

        // Get the upstream branch
        let upstream = match branch.upstream() {
            Ok(u) => u,
            Err(_) => {
                // Upstream is configured but ref is gone - can't be behind non-existent branch
                return Ok(false);
            }
        };

        // Get the local and upstream commit OIDs
        let local_oid = branch
            .get()
            .target()
            .ok_or(WorktreeError::NoLocalBranchTarget)?;
        let upstream_oid = upstream
            .get()
            .target()
            .ok_or(WorktreeError::NoBranchTarget)?;

        // Check if local is behind upstream
        let (_ahead, behind) = repo.graph_ahead_behind(local_oid, upstream_oid)?;

        Ok(behind > 0)
    }

    /// Returns true if the worktree's upstream branch reference is gone (deleted on remote).
    ///
    /// Returns false if:
    /// - The worktree is detached (no branch)
    /// - The branch has no upstream configured
    /// - The upstream branch reference exists
    ///
    /// Returns true if:
    /// - Upstream is configured (branch.{name}.remote exists in config)
    /// - But the upstream branch reference cannot be found
    pub fn has_gone_upstream(&self) -> Result<bool> {
        // Get the branch name - return false if detached
        let branch_name = match self.branch()? {
            Some(name) => name,
            None => return Ok(false), // Detached HEAD, no branch to check
        };

        // Open the repository
        let repo = Repository::open(self.path())?;

        // Find the local branch
        let branch = match repo.find_branch(&branch_name, git2::BranchType::Local) {
            Ok(b) => b,
            Err(_) => return Ok(false), // Branch doesn't exist
        };

        // Check if upstream is configured via git config
        let config = repo.config()?;
        let remote_key = format!("branch.{}.remote", branch_name);

        // If no upstream is configured, it's not "gone"
        match config.get_string(&remote_key) {
            Ok(_) => {
                // Upstream is configured - check if the reference exists
                match branch.upstream() {
                    Ok(_) => Ok(false), // Upstream exists
                    Err(_) => Ok(true), // Upstream configured but ref is gone
                }
            }
            Err(_) => Ok(false), // No upstream configured
        }
    }

    /// Returns true if the worktree's branch has been merged into the target branch.
    ///
    /// A branch is considered merged if its HEAD commit is reachable from the target branch,
    /// meaning all commits in this branch exist in the target branch's history.
    ///
    /// Returns false if:
    /// - The worktree is detached (no branch)
    /// - The target branch doesn't exist
    /// - The branch has commits not in the target branch
    ///
    /// Returns true if:
    /// - All commits in this branch are reachable from the target branch
    pub fn is_merged_into(&self, target_branch: &str) -> Result<bool> {
        // Get the branch name - return false if detached
        let branch_name = match self.branch()? {
            Some(name) => name,
            None => return Ok(false), // Detached HEAD, no branch to check
        };

        // Don't consider the target branch as merged into itself
        if branch_name == target_branch {
            return Ok(false);
        }

        // Open the bare repository (not the worktree) to check actual branch states
        // The worktree's .git points to the commondir (bare repo)
        let worktree_repo = Repository::open(self.path())?;
        let commondir = worktree_repo.commondir();
        let repo = Repository::open(commondir)?;

        // Find the current branch
        let current_branch = match repo.find_branch(&branch_name, git2::BranchType::Local) {
            Ok(b) => b,
            Err(_) => return Ok(false), // Branch doesn't exist
        };

        // Find the target branch
        let target = match repo.find_branch(target_branch, git2::BranchType::Local) {
            Ok(b) => b,
            Err(_) => return Ok(false), // Target branch doesn't exist
        };

        // Get commit OIDs
        let current_oid = current_branch
            .get()
            .target()
            .ok_or(WorktreeError::NoCurrentBranchTarget)?;
        let target_oid = target.get().target().ok_or(WorktreeError::NoBranchTarget)?;

        // If they point to the same commit, the branch is merged
        if current_oid == target_oid {
            return Ok(true);
        }

        // Check if current branch's commit is reachable from target
        // This means target is a descendant of (or equal to) current
        Ok(repo.graph_descendant_of(target_oid, current_oid)?)
    }

    /// Returns the commit hash (SHA) of the worktree's current HEAD.
    ///
    /// Returns None if HEAD cannot be resolved (e.g., empty repository).
    pub fn head_commit(&self) -> Result<Option<String>> {
        let repo = Repository::open(self.path())?;

        // Try to resolve HEAD to a commit and extract the OID immediately
        let commit_oid = match repo.head() {
            Ok(head) => match head.peel_to_commit() {
                Ok(commit) => Some(commit.id()),
                Err(_) => return Ok(None), // HEAD exists but can't resolve to commit
            },
            Err(_) => return Ok(None), // No HEAD (unborn branch)
        };

        Ok(commit_oid.map(|oid| oid.to_string()))
    }

    /// Returns the timestamp of the HEAD commit as the last activity time.
    ///
    /// Returns None if:
    /// - HEAD cannot be resolved (empty/unborn repository)
    /// - HEAD cannot be peeled to a commit
    pub fn last_activity(&self) -> Result<Option<i64>> {
        let repo = Repository::open(self.path())?;
        let seconds = match repo.head() {
            Ok(head) => match head.peel_to_commit() {
                Ok(commit) => Some(commit.time().seconds()),
                Err(_) => None,
            },
            Err(_) => None,
        };
        Ok(seconds)
    }

    /// Returns true if the worktree's last activity is older than `days` days.
    ///
    /// Returns false if:
    /// - Last activity cannot be determined
    /// - The worktree has recent activity within the threshold
    pub fn is_stale(&self, days: u32) -> Result<bool> {
        let last = match self.last_activity()? {
            Some(ts) => ts,
            None => return Ok(false),
        };
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(std::io::Error::other)?
            .as_secs() as i64;
        let threshold = i64::from(days) * 86400;
        Ok((now - last) > threshold)
    }

    /// Returns the name of the remote that the worktree's branch tracks (e.g., "origin").
    ///
    /// Returns None if:
    /// - The worktree is detached (no branch)
    /// - The branch has no upstream configured
    pub fn remote(&self) -> Result<Option<String>> {
        // Get the branch name - return None if detached
        let branch_name = match self.branch()? {
            Some(name) => name,
            None => return Ok(None), // Detached HEAD, no branch to check
        };

        let repo = Repository::open(self.path())?;
        let config = repo.config()?;

        // Check for branch.<name>.remote in git config
        let remote_key = format!("branch.{}.remote", branch_name);
        match config.get_string(&remote_key) {
            Ok(remote) => Ok(Some(remote)),
            Err(_) => Ok(None), // No remote configured
        }
    }

    /// Returns the full name of the upstream remote branch (e.g., "refs/remotes/origin/main").
    ///
    /// Returns None if:
    /// - The worktree is detached (no branch)
    /// - The branch has no upstream configured
    pub fn remote_branch(&self) -> Result<Option<String>> {
        // Get the branch name - return None if detached
        let branch_name = match self.branch()? {
            Some(name) => name,
            None => return Ok(None), // Detached HEAD, no branch to check
        };

        let repo = Repository::open(self.path())?;

        // Find the local branch and get its upstream, extracting the name immediately
        let branch = match repo.find_branch(&branch_name, git2::BranchType::Local) {
            Ok(b) => b,
            Err(_) => return Ok(None), // Branch doesn't exist
        };

        let upstream_name = match branch.upstream() {
            Ok(upstream) => match upstream.name() {
                Ok(Some(name)) => Some(name.to_string()),
                _ => None,
            },
            Err(_) => return Ok(None), // No upstream configured
        };

        Ok(upstream_name)
    }

    /// Returns the default URL for the remote (usually the fetch URL).
    ///
    /// Returns None if:
    /// - The worktree is detached (no branch)
    /// - The branch has no upstream configured
    /// - The remote has no URL configured
    pub fn remote_url(&self) -> Result<Option<String>> {
        // Get the remote name
        let remote_name = match self.remote()? {
            Some(name) => name,
            None => return Ok(None),
        };

        let repo = Repository::open(self.path())?;

        // Find the remote and extract the URL immediately
        let url = match repo.find_remote(&remote_name) {
            Ok(remote) => remote.url().map(|s| s.to_string()),
            Err(_) => return Ok(None), // Remote doesn't exist
        };

        Ok(url)
    }

    /// Returns the fetch URL for the remote.
    ///
    /// Returns None if:
    /// - The worktree is detached (no branch)
    /// - The branch has no upstream configured
    /// - The remote has no fetch URL configured
    pub fn remote_fetch_url(&self) -> Result<Option<String>> {
        // Get the remote name
        let remote_name = match self.remote()? {
            Some(name) => name,
            None => return Ok(None),
        };

        let repo = Repository::open(self.path())?;

        // Find the remote and extract the fetch URL immediately
        let url = match repo.find_remote(&remote_name) {
            Ok(remote) => remote.url().map(|s| s.to_string()),
            Err(_) => return Ok(None), // Remote doesn't exist
        };

        Ok(url)
    }

    /// Returns the push URL for the remote.
    ///
    /// Returns None if:
    /// - The worktree is detached (no branch)
    /// - The branch has no upstream configured
    /// - The remote has no push URL configured (falls back to fetch URL)
    pub fn remote_push_url(&self) -> Result<Option<String>> {
        // Get the remote name
        let remote_name = match self.remote()? {
            Some(name) => name,
            None => return Ok(None),
        };

        let repo = Repository::open(self.path())?;

        // Find the remote and extract the push URL (or fallback to fetch URL) immediately
        let url = match repo.find_remote(&remote_name) {
            Ok(remote) => remote
                .pushurl()
                .or_else(|| remote.url())
                .map(|s| s.to_string()),
            Err(_) => return Ok(None), // Remote doesn't exist
        };

        Ok(url)
    }
}

impl fmt::Debug for WorktreeDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "WorktreeDescriptor({:?})", self.worktree.path())
    }
}

impl fmt::Display for WorktreeDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.worktree.path().display())
    }
}

/// Return all worktrees registered with the repository.
pub fn get_worktrees(repo: &Repository) -> Result<Vec<WorktreeDescriptor>> {
    repo.worktrees()?
        .into_iter()
        .map(|name| {
            let name = name.ok_or(WorktreeError::InvalidName)?;
            WorktreeDescriptor::new(repo, name)
        })
        .collect()
}

/// Return the worktree that contains the current working directory.
///
/// Returns [`WorktreeError::NotInWorktree`] if the current directory is not
/// inside any registered worktree.
pub fn current_worktree(repo: &Repository) -> Result<WorktreeDescriptor> {
    let current_dir = std::env::current_dir().map_err(std::io::Error::other)?;

    let worktrees = get_worktrees(repo)?;
    worktrees
        .into_iter()
        .find(|wt| current_dir.starts_with(wt.path()))
        .ok_or_else(|| WorktreeError::NotInWorktree.into())
}

/// Find a worktree by its name or by its branch name.
///
/// Returns [`WorktreeError::NotFound`] if no matching worktree exists.
pub fn find_worktree(repo: &Repository, name: &str) -> Result<WorktreeDescriptor> {
    let worktrees = get_worktrees(repo)?;
    worktrees
        .into_iter()
        .find(|wt| {
            // Match by worktree name or branch name
            wt.name() == Some(name) || wt.branch().ok().flatten().as_deref() == Some(name)
        })
        .ok_or_else(|| WorktreeError::NotFound(name.to_string()).into())
}

/// Create a new worktree for the given branch.
///
/// The worktree directory is placed under the workon root (see [`workon_root`]).
/// Branch names containing `/` are supported; parent directories are created
/// automatically and the worktree is named after the final path component.
///
/// # Branch types
///
/// - [`BranchType::Normal`] — uses an existing local/remote branch, or creates one from
///   `base_branch` (or HEAD if `base_branch` is `None`).
/// - [`BranchType::Orphan`] — creates an independent branch with no shared history,
///   seeded with an empty initial commit.
/// - [`BranchType::Detached`] — creates a worktree with a detached HEAD pointing to
///   the current HEAD commit.
pub fn add_worktree(
    repo: &Repository,
    branch_name: &str,
    branch_type: BranchType,
    base_branch: Option<&str>,
    lock: bool,
) -> Result<WorktreeDescriptor> {
    // git worktree add <branch>
    debug!(
        "adding worktree for branch {:?} with type: {:?}",
        branch_name, branch_type
    );

    let reference = match branch_type {
        BranchType::Orphan => {
            debug!("creating orphan branch {:?}", branch_name);
            // For orphan branches, we'll create the branch after the worktree
            None
        }
        BranchType::Detached => {
            debug!("creating detached HEAD worktree at {:?}", branch_name);
            // For detached worktrees, we don't create or use a branch reference
            None
        }
        BranchType::Normal => {
            let branch = match repo.find_branch(branch_name, git2::BranchType::Local) {
                Ok(b) => b,
                Err(e) => {
                    debug!("local branch not found: {:?}", e);
                    debug!("looking for remote branch {:?}", branch_name);
                    match repo.find_branch(branch_name, git2::BranchType::Remote) {
                        Ok(b) => b,
                        Err(e) => {
                            debug!("remote branch not found: {:?}", e);
                            debug!("creating new local branch {:?}", branch_name);

                            // Determine which commit to branch from
                            let base_commit = if let Some(base) = base_branch {
                                // Branch from specified base branch
                                debug!("branching from base branch {:?}", base);
                                // Try local branch first, then remote branch
                                let base_branch =
                                    match repo.find_branch(base, git2::BranchType::Local) {
                                        Ok(b) => b,
                                        Err(_) => {
                                            debug!("base branch not found as local, trying remote");
                                            repo.find_branch(base, git2::BranchType::Remote)?
                                        }
                                    };
                                base_branch.into_reference().peel_to_commit()?
                            } else {
                                // Default: branch from HEAD
                                repo.head()?.peel_to_commit()?
                            };

                            repo.branch(branch_name, &base_commit, false)?
                        }
                    }
                }
            };

            Some(branch.into_reference())
        }
    };

    let root = workon_root(repo)?;

    // Git does not support worktree names with slashes in them,
    // so take the base of the branch name as the worktree name.
    let worktree_name = match Path::new(&branch_name).file_name() {
        Some(basename) => basename.to_str().ok_or(WorktreeError::InvalidName)?,
        None => branch_name,
    };

    let worktree_path = root.join(branch_name);

    // Create parent directories if the branch name contains slashes
    if let Some(parent) = worktree_path.parent() {
        create_dir_all(parent)?;
    }

    let mut opts = WorktreeAddOptions::new();
    if let Some(ref r) = reference {
        opts.reference(Some(r));
    }
    if lock {
        opts.lock(true);
    }

    debug!(
        "adding worktree {} at {}",
        worktree_name,
        worktree_path.display()
    );

    let worktree = repo.worktree(worktree_name, worktree_path.as_path(), Some(&opts))?;

    // For detached worktrees, set HEAD to point directly to a commit SHA
    if branch_type == BranchType::Detached {
        debug!("setting up detached HEAD for worktree {:?}", branch_name);

        use std::fs;

        // Get the current HEAD commit SHA
        let head_commit = repo.head()?.peel_to_commit()?;
        let commit_sha = head_commit.id().to_string();

        // Write the commit SHA directly to the worktree's HEAD file
        let git_dir = repo.path().join("worktrees").join(worktree_name);
        let head_path = git_dir.join("HEAD");
        fs::write(&head_path, format!("{}\n", commit_sha).as_bytes())?;

        debug!(
            "detached HEAD setup complete for worktree {:?} at {}",
            branch_name, commit_sha
        );
    }

    // For orphan branches, create an initial empty commit with no parent
    if branch_type == BranchType::Orphan {
        debug!(
            "setting up orphan branch {:?} with initial empty commit",
            branch_name
        );

        use std::fs;

        // Get the common directory (bare repo path) - important when running from a worktree
        let common_dir = repo.commondir();

        // First, manually set HEAD to point to the new branch as a symbolic reference
        // This ensures we're not trying to update an existing branch
        let git_dir = common_dir.join("worktrees").join(worktree_name);
        let head_path = git_dir.join("HEAD");
        let branch_ref = format!("ref: refs/heads/{}\n", branch_name);
        fs::write(&head_path, branch_ref.as_bytes())?;

        // Remove any existing branch ref that libgit2 may have created
        let branch_ref_path = common_dir.join("refs/heads").join(branch_name);
        let _ = fs::remove_file(&branch_ref_path);

        // Open the worktree repository
        let worktree_repo = Repository::open(&worktree_path)?;

        // Remove all files from the working directory (but keep .git)
        for entry in fs::read_dir(&worktree_path)? {
            let entry = entry?;
            let path = entry.path();
            if path.file_name() != Some(std::ffi::OsStr::new(".git")) {
                if path.is_dir() {
                    fs::remove_dir_all(&path)?;
                } else {
                    fs::remove_file(&path)?;
                }
            }
        }

        // Clear the index to start fresh
        let mut index = worktree_repo.index()?;
        index.clear()?;
        index.write()?;

        // Create an empty tree for the initial commit
        let tree_id = index.write_tree()?;
        let tree = worktree_repo.find_tree(tree_id)?;

        // Create signature for the commit
        let config = worktree_repo.config()?;
        let sig = worktree_repo.signature().or_else(|_| {
            // Fallback if no git config is set
            git2::Signature::now(
                config
                    .get_string("user.name")
                    .unwrap_or_else(|_| "git-workon".to_string())
                    .as_str(),
                config
                    .get_string("user.email")
                    .unwrap_or_else(|_| "git-workon@localhost".to_string())
                    .as_str(),
            )
        })?;

        // Create initial commit with no parents (orphan)
        worktree_repo.commit(
            Some("HEAD"),
            &sig,
            &sig,
            "Initial commit",
            &tree,
            &[], // No parents - this makes it an orphan
        )?;

        debug!("orphan branch setup complete for {:?}", branch_name);
    }

    Ok(WorktreeDescriptor::of(worktree))
}

/// Set upstream tracking for a worktree branch
///
/// Configures the branch in the worktree to track a remote branch by setting
/// `branch.*.remote` and `branch.*.merge` configuration entries.
///
/// This is particularly important for PR worktrees to ensure they properly track
/// the PR's remote branch.
pub fn set_upstream_tracking(
    worktree: &WorktreeDescriptor,
    remote: &str,
    remote_ref: &str,
) -> Result<()> {
    let repo = Repository::open(worktree.path())?;
    let mut config = repo.config()?;

    let head = repo.head()?;
    let branch_name = head
        .shorthand()
        .ok_or(WorktreeError::NoCurrentBranchTarget)?;

    // Set branch.*.remote
    let remote_key = format!("branch.{}.remote", branch_name);
    config.set_str(&remote_key, remote)?;

    // Set branch.*.merge
    let merge_key = format!("branch.{}.merge", branch_name);
    config.set_str(&merge_key, remote_ref)?;

    debug!(
        "Set upstream tracking: {} -> {}/{}",
        branch_name, remote, remote_ref
    );
    Ok(())
}