grit-lib 0.5.18

Core library for the grit Git implementation
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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
//! Linked worktree registry: discovery, listing, and admin-dir layout.
//!
//! Git stores linked worktrees under `<common-git-dir>/worktrees/<id>/` with
//! `gitdir`, `commondir`, `HEAD`, and optional `locked` / `prunable` files.
//! This module reads that layout and implements linked worktree add/remove.

use std::fs;
use std::path::{Path, PathBuf};

use crate::check_ref_format::validate_branch_short_name;
use crate::config::ConfigSet;
#[cfg(test)]
use crate::environment::RepositoryOptions;
use crate::error::{Error, Result};
use crate::git_path::{absolute_path_for_gitfile_stored_path, path_for_disk_compare};
use crate::objects::{parse_commit, ObjectKind};
use crate::porcelain::checkout::checkout_between_trees;
use crate::porcelain::status::{status, StatusOptions};
use crate::progress::NullProgress;
use crate::refs;
use crate::repo::{common_git_dir_for_config, Repository};
use crate::rev_parse::resolve_revision;
use crate::state::{resolve_head, HeadState};

/// Why Git marks a linked worktree as `prunable` in `worktree list --porcelain`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrunableReason {
    /// Admin path is not a directory (`not a valid directory`).
    AdminNotValidDirectory,
    /// `<admin>/gitdir` is missing (`gitdir file does not exist`).
    GitdirFileMissing,
    /// Resolved gitdir target is missing (`gitdir file points to non-existent location`).
    GitdirPointsElsewhere,
    /// Working tree root directory is missing while the gitdir file still exists.
    WorktreePathMissing,
    /// `<admin>/gitdir` is empty or unreadable (`invalid gitdir file`).
    InvalidGitdirFile,
    /// `<admin>/prunable` exists (grit/Git admin marker forcing prune eligibility).
    ExplicitMarker,
}

impl PrunableReason {
    /// Message text after `prunable` in `git worktree list --porcelain`.
    #[must_use]
    pub fn porcelain_message(self) -> &'static str {
        match self {
            Self::AdminNotValidDirectory => "not a valid directory",
            Self::GitdirFileMissing => "gitdir file does not exist",
            Self::GitdirPointsElsewhere => "gitdir file points to non-existent location",
            Self::WorktreePathMissing => "gitdir file points to non-existent location",
            Self::InvalidGitdirFile => "invalid gitdir file",
            Self::ExplicitMarker => "gitdir file points to non-existent location",
        }
    }
}

/// One row returned by [`list_worktrees`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeEntry {
    /// Absolute path to the working tree (for bare main worktree, the common git dir).
    pub path: PathBuf,
    /// Resolved HEAD for this worktree.
    pub head: HeadState,
    /// Whether this worktree is bare (only the main entry can be bare).
    pub is_bare: bool,
    /// True when `<admin>/locked` exists.
    pub is_locked: bool,
    /// Contents of the `locked` file when non-empty.
    pub lock_reason: Option<String>,
    /// Administrative directory: common git dir for main, else `worktrees/<id>/`.
    pub admin_dir: PathBuf,
    /// True when [`Self::prunable_reason`] is set (Git `prunable` in `worktree list`).
    pub is_prunable: bool,
    /// Typed prune reason when [`Self::is_prunable`] is true.
    pub prunable_reason: Option<PrunableReason>,
    /// True when this row is the worktree [`Repository`] was opened from.
    pub is_current: bool,
}

/// Shared git directory for `git_dir` (follows `commondir` for linked worktrees).
#[must_use]
pub fn common_git_dir(git_dir: &Path) -> PathBuf {
    common_git_dir_for_config(git_dir)
}

/// Resolve HEAD for a linked worktree admin dir (`HEAD` local, branch refs in `common`).
#[must_use]
pub fn resolve_linked_head(admin: &Path, _common: &Path) -> HeadState {
    resolve_head(admin).unwrap_or(HeadState::Invalid)
}

/// Number of registered worktrees (main + linked entries under `worktrees/`).
#[must_use]
pub fn registered_worktree_count(common: &Path) -> usize {
    let worktrees_dir = common.join("worktrees");
    if !worktrees_dir.is_dir() {
        return 1;
    }
    let linked = fs::read_dir(&worktrees_dir)
        .into_iter()
        .flatten()
        .flatten()
        .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
        .count();
    1 + linked
}

/// Whether `common` is configured as a bare repository (`core.bare=true`).
#[must_use]
pub fn is_bare_repository(common: &Path) -> bool {
    ConfigSet::load(
        &crate::environment::Environment::empty(),
        Some(common),
        true,
    )
    .ok()
    .and_then(|cfg| cfg.get_bool("core.bare"))
    .and_then(|r| r.ok())
    .unwrap_or_else(|| {
        // Heuristic when config is missing: bare repos usually are not named `.git`.
        !common.ends_with(".git") && common.join("config").is_file()
    })
}

/// Where a local branch is checked out among registered worktrees.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BranchWorktreeCheckout {
    /// Short branch name (e.g. `feat`).
    pub branch: String,
    /// Working tree path for the checkout.
    pub worktree_path: PathBuf,
    /// Administrative git directory for that worktree.
    pub admin_dir: PathBuf,
}

/// Administrative git directory for the worktree `repo` was opened from.
#[must_use]
pub fn worktree_admin_dir(repo: &Repository) -> PathBuf {
    let common = common_git_dir(repo.git_dir());
    if repo.git_dir().starts_with(common.join("worktrees")) {
        repo.git_dir().to_path_buf()
    } else {
        common
    }
}

fn head_is_branch(head: &HeadState, branch_short_name: &str) -> bool {
    match head {
        HeadState::Branch {
            short_name,
            refname,
            ..
        } => {
            short_name == branch_short_name || refname == &format!("refs/heads/{branch_short_name}")
        }
        _ => false,
    }
}

pub(crate) fn admin_dirs_match(a: &Path, b: &Path) -> bool {
    path_for_disk_compare(a) == path_for_disk_compare(b) || a == b
}

/// Find a worktree that has `branch_short_name` checked out, optionally skipping one admin dir.
///
/// `exclude_admin_dir` is typically the current worktree's admin dir so a switch to the branch
/// already checked out here is allowed.
pub fn find_worktree_with_branch_checked_out(
    repo: &Repository,
    branch_short_name: &str,
    exclude_admin_dir: Option<&Path>,
) -> Result<Option<BranchWorktreeCheckout>> {
    for entry in list_worktrees(repo)? {
        if exclude_admin_dir.is_some_and(|ex| admin_dirs_match(&entry.admin_dir, ex)) {
            continue;
        }
        if head_is_branch(&entry.head, branch_short_name) {
            return Ok(Some(BranchWorktreeCheckout {
                branch: branch_short_name.to_owned(),
                worktree_path: entry.path.clone(),
                admin_dir: entry.admin_dir.clone(),
            }));
        }
    }
    Ok(None)
}

/// Refuse when another worktree already has `branch_short_name` checked out.
///
/// # Errors
///
/// Returns [`Error::BranchCheckedOutInWorktree`] when a different worktree holds the branch.
pub fn ensure_branch_not_checked_out_elsewhere(
    repo: &Repository,
    branch_short_name: &str,
) -> Result<()> {
    let exclude = worktree_admin_dir(repo);
    if let Some(found) =
        find_worktree_with_branch_checked_out(repo, branch_short_name, Some(&exclude))?
    {
        return Err(branch_checked_out_error(
            branch_short_name,
            &found.worktree_path,
        ));
    }
    Ok(())
}

/// Refuse when any worktree (including linked) has `branch_short_name` checked out.
///
/// # Errors
///
/// Returns [`Error::BranchCheckedOutInWorktree`] when any registered worktree holds the branch.
pub fn ensure_branch_not_checked_out_in_any_worktree(
    repo: &Repository,
    branch_short_name: &str,
) -> Result<()> {
    if let Some(found) = find_worktree_with_branch_checked_out(repo, branch_short_name, None)? {
        return Err(branch_checked_out_error(
            branch_short_name,
            &found.worktree_path,
        ));
    }
    Ok(())
}

fn branch_checked_out_error(branch: &str, worktree_path: &Path) -> Error {
    Error::BranchCheckedOutInWorktree {
        branch: branch.to_owned(),
        worktree_path: worktree_path.display().to_string(),
    }
}

/// Enumerate the main and linked worktrees for `repo`.
///
/// Order matches Git: main worktree first, then linked worktrees sorted by admin id.
pub fn list_worktrees(repo: &Repository) -> Result<Vec<WorktreeEntry>> {
    let common = common_git_dir(repo.git_dir());
    let git_dir = repo.git_dir();
    let opened_from_linked = git_dir.starts_with(common.join("worktrees"));
    let mut entries = Vec::new();

    let bare = is_bare_repository(&common);
    let main_path = if bare {
        path_for_disk_compare(&common)
    } else if let Some(wt) = repo.work_tree() {
        // When opened from the main worktree, use the discovered work tree path.
        if repo.git_dir() == common || !repo.git_dir().starts_with(common.join("worktrees")) {
            path_for_disk_compare(wt)
        } else {
            path_for_disk_compare(common.parent().unwrap_or(&common))
        }
    } else {
        path_for_disk_compare(common.parent().unwrap_or(&common))
    };

    let main_head = resolve_head(&common).unwrap_or(HeadState::Invalid);
    entries.push(WorktreeEntry {
        path: main_path,
        head: main_head,
        is_bare: bare,
        is_locked: false,
        lock_reason: None,
        admin_dir: common.clone(),
        is_prunable: false,
        prunable_reason: None,
        is_current: !opened_from_linked && repo_opened_from_admin(git_dir, &common),
    });

    let worktrees_dir = common.join("worktrees");
    if !worktrees_dir.is_dir() {
        return Ok(entries);
    }

    let mut names: Vec<String> = fs::read_dir(&worktrees_dir)
        .map_err(Error::Io)?
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();

    for name in names {
        let admin = worktrees_dir.join(&name);
        let wt_head = resolve_linked_head(&admin, &common);
        let wt_path = read_worktree_path(&admin)?;
        let (is_locked, lock_reason) = read_lock_state(&admin)?;
        let (is_prunable, prunable_reason) =
            linked_worktree_prunable_state(&admin, is_locked, &wt_path);
        let is_current = opened_from_linked && git_dir == admin.as_path();
        entries.push(WorktreeEntry {
            path: wt_path,
            head: wt_head,
            is_bare: false,
            is_locked,
            lock_reason,
            admin_dir: admin,
            is_prunable,
            prunable_reason,
            is_current,
        });
    }

    Ok(entries)
}

#[inline]
fn repo_opened_from_admin(git_dir: &Path, admin: &Path) -> bool {
    git_dir == admin || path_for_disk_compare(git_dir) == path_for_disk_compare(admin)
}

/// Last path component of `path`, without trailing directory separators (Git `worktree_basename`).
#[must_use]
pub fn worktree_path_basename(path: &Path) -> String {
    let s = path.to_string_lossy();
    let trimmed = s.trim_end_matches(['/', '\\']);
    trimmed
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(trimmed)
        .to_owned()
}

/// Sanitize a path basename for use as `worktrees/<id>/` (Git `sanitize_refname_component`).
#[must_use]
pub fn sanitize_worktree_id_component(name: &str) -> String {
    if name == "@" {
        return "-".to_owned();
    }

    let mut out = String::new();
    let mut last = '\0';
    let chars: Vec<char> = name.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        let ch = chars[i];
        if ch.is_ascii_control()
            || matches!(ch, ':' | '?' | '[' | '\\' | '^' | '~' | ' ' | '\t' | '*')
        {
            if (out.is_empty() && last != '-') || !out.is_empty() {
                out.push('-');
            }
            last = '-';
            i += 1;
            continue;
        }
        if ch == '.' && i + 1 < chars.len() && chars[i + 1] == '.' {
            if last == '.' {
                out.pop();
            } else {
                out.push('.');
                last = '.';
            }
            i += 2;
            continue;
        }
        if ch == '@' && i + 1 < chars.len() && chars[i + 1] == '{' {
            if let Some(last_ch) = out.pop() {
                if last_ch != '-' {
                    out.push('-');
                }
            }
            last = '-';
            i += 2;
            continue;
        }
        if ch == '.' && out.is_empty() {
            out.push('-');
            last = '-';
            i += 1;
            continue;
        }
        out.push(ch);
        last = ch;
        i += 1;
    }

    const LOCK_SUFFIX: &str = ".lock";
    while out.ends_with(LOCK_SUFFIX) {
        out.truncate(out.len() - LOCK_SUFFIX.len());
    }
    while out.ends_with('.') {
        out.pop();
    }
    out
}

/// Pick a unique `<common>/worktrees/<id>/` directory for a new linked worktree at `wt_path`.
///
/// Git uses the sanitized basename and appends `1`, `2`, … when the admin dir already exists.
#[must_use]
pub fn allocate_worktree_admin_dir(common: &Path, wt_path: &Path) -> PathBuf {
    let worktrees_dir = common.join("worktrees");
    let base = sanitize_worktree_id_component(&worktree_path_basename(wt_path));
    let base = if base.is_empty() {
        "worktree".to_owned()
    } else {
        base
    };

    let mut counter = 0u32;
    loop {
        let id = if counter == 0 {
            base.clone()
        } else {
            format!("{base}{counter}")
        };
        let admin = worktrees_dir.join(&id);
        if !admin.exists() {
            return admin;
        }
        counter = counter.saturating_add(1);
        if counter == 0 {
            break;
        }
    }
    worktrees_dir.join(format!("{base}{}", std::process::id()))
}

/// Copy `config.worktree` into a linked worktree admin dir, stripping keys Git omits
/// when `extensions.worktreeConfig` is enabled (`core.bare`, `core.worktree`).
pub fn copy_filtered_worktree_config(source_git_dir: &Path, admin_dir: &Path) -> Result<()> {
    let src = source_git_dir.join("config.worktree");
    if !src.is_file() {
        return Ok(());
    }
    let dst = admin_dir.join("config.worktree");
    fs::copy(&src, &dst).map_err(Error::Io)?;
    strip_worktree_config_keys(&dst, &["core.bare", "core.worktree"])?;
    Ok(())
}

fn strip_worktree_config_keys(path: &Path, keys: &[&str]) -> Result<()> {
    let content = fs::read_to_string(path).map_err(Error::Io)?;
    let mut kept = Vec::new();
    let mut section: Option<String> = None;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
            kept.push(line);
            continue;
        }
        if trimmed.starts_with('[') {
            let end = trimmed.find(']').unwrap_or(trimmed.len());
            let name = trimmed[1..end].trim().to_ascii_lowercase();
            section = Some(name);
            kept.push(line);
            continue;
        }
        if let Some((key, _)) = trimmed.split_once('=') {
            let key = key.trim().to_ascii_lowercase();
            let full = match section.as_deref() {
                Some(sec) => format!("{sec}.{key}"),
                None => key.clone(),
            };
            if keys.iter().any(|k| full.eq_ignore_ascii_case(k)) {
                continue;
            }
        } else if keys.iter().any(|k| trimmed.eq_ignore_ascii_case(k)) {
            continue;
        }
        kept.push(line);
    }
    let mut out = kept.join("\n");
    if !out.is_empty() {
        out.push('\n');
    }
    fs::write(path, out).map_err(Error::Io)
}

/// Options for [`add_linked_worktree`].
#[derive(Debug, Clone)]
pub struct AddLinkedWorktreeOptions {
    /// Directory for the new working tree (created when missing).
    pub path: PathBuf,
    /// Branch to check out. With [`Self::new_branch`], create this branch at the start commit.
    pub branch: Option<String>,
    /// Create [`Self::branch`] before checkout.
    pub new_branch: bool,
    /// Detached HEAD at the resolved start commit.
    pub detach: bool,
    /// Start commit (revision spec). Defaults to the current `HEAD` commit.
    pub start_point: Option<String>,
    /// Replace a stale registration when the working tree directory is missing.
    pub force: bool,
}

/// Register and populate a linked worktree (Git `worktree add` layout).
///
/// # Errors
///
/// Fails when the repository is bare, the path is occupied, the branch is already
/// checked out elsewhere, or checkout cannot complete.
pub fn add_linked_worktree(
    repo: &Repository,
    opts: &AddLinkedWorktreeOptions,
) -> Result<WorktreeEntry> {
    let common = common_git_dir(repo.git_dir());
    if is_bare_repository(&common) {
        return Err(Error::Message(
            "cannot add a worktree to a bare repository".into(),
        ));
    }

    let wt_path = if opts.path.exists() {
        path_for_disk_compare(&opts.path)
    } else {
        opts.path.clone()
    };
    let admin_plan = plan_admin_dir_for_add(&common, &wt_path, opts.force)?;
    ensure_empty_or_missing(&wt_path)?;

    let start_spec = opts.start_point.as_deref().unwrap_or("HEAD");
    let start_oid = resolve_revision(repo, start_spec)?;
    let start_obj = repo.odb().read(&start_oid)?;
    if start_obj.kind != ObjectKind::Commit {
        return Err(Error::Message(format!(
            "revision '{start_spec}' does not resolve to a commit"
        )));
    }
    let tree_oid = parse_commit(&start_obj.data)?.tree;

    let head_ref = if opts.detach {
        None
    } else if let Some(branch) = opts.branch.as_deref() {
        validate_branch_short_name(branch).map_err(|e| Error::Message(e.to_string()))?;
        let branch_ref = format!("refs/heads/{branch}");
        if opts.new_branch {
            if refs::resolve_ref(repo.git_dir(), &branch_ref).is_ok() {
                return Err(Error::Message(format!("branch '{branch}' already exists")));
            }
            refs::write_ref(repo.git_dir(), &branch_ref, &start_oid)?;
        } else if refs::resolve_ref(repo.git_dir(), &branch_ref).is_err() {
            return Err(Error::Message(format!("no branch named '{branch}'")));
        } else {
            let tip = refs::resolve_ref(repo.git_dir(), &branch_ref)?;
            if tip != start_oid {
                return Err(Error::Message(format!(
                    "branch '{branch}' does not match start commit"
                )));
            }
        }
        branch_checked_out_elsewhere(repo, &branch_ref)?;
        Some(branch_ref)
    } else if let Some(start) = opts.start_point.as_deref() {
        if let Some(branch_ref) = resolve_existing_branch(repo, start) {
            branch_checked_out_elsewhere(repo, &branch_ref)?;
            Some(branch_ref)
        } else {
            None
        }
    } else {
        let branch = worktree_path_basename(&wt_path);
        validate_branch_short_name(&branch).map_err(|e| Error::Message(e.to_string()))?;
        let branch_ref = format!("refs/heads/{branch}");
        if refs::resolve_ref(repo.git_dir(), &branch_ref).is_ok() {
            return Err(Error::Message(format!("branch '{branch}' already exists")));
        }
        refs::write_ref(repo.git_dir(), &branch_ref, &start_oid)?;
        branch_checked_out_elsewhere(repo, &branch_ref)?;
        Some(branch_ref)
    };

    let admin = admin_plan.admin_dir;
    let worktree_absent_before = !wt_path.exists();
    let mut stale_guard = admin_plan
        .stale_admins
        .map(StaleWorktreeAdminBackup::remove_and_backup)
        .transpose()?;

    let finish = (|| -> Result<WorktreeEntry> {
        fs::create_dir_all(&admin).map_err(Error::Io)?;
        if let Some(guard) = stale_guard.as_mut() {
            guard.set_new_admin(&admin);
        }
        fs::create_dir_all(&wt_path).map_err(Error::Io)?;
        if let Some(guard) = stale_guard.as_mut() {
            guard.track_replacement_worktree(&wt_path, worktree_absent_before);
        }

        let wt_git = wt_path.join(".git");
        fs::write(
            &wt_git,
            format!(
                "gitdir: {}\n",
                absolute_path_for_gitfile_stored_path(&admin)
            ),
        )
        .map_err(Error::Io)?;
        let wt_git_abs = absolute_path_for_gitfile_stored_path(&wt_git);
        fs::write(admin.join("commondir"), "../..\n").map_err(Error::Io)?;
        fs::write(admin.join("gitdir"), format!("{wt_git_abs}\n")).map_err(Error::Io)?;

        if let Some(ref branch_ref) = head_ref {
            fs::write(admin.join("HEAD"), format!("ref: {branch_ref}\n")).map_err(Error::Io)?;
        } else {
            fs::write(admin.join("HEAD"), format!("{start_oid}\n")).map_err(Error::Io)?;
        }

        copy_filtered_worktree_config(&common, &admin)?;

        let linked = Repository::discover(
            Some(wt_path.as_path()),
            &repo.linked_worktree_discover_options(),
        )?;
        checkout_between_trees(&linked, None, &tree_oid)?;

        linked_worktree_entry(&admin, &common, &worktree_admin_dir(repo))
    })();

    match finish {
        Ok(entry) => {
            if let Some(guard) = stale_guard.take() {
                guard.commit();
            }
            Ok(entry)
        }
        Err(err) => Err(err),
    }
}

/// Remove admin directories for linked worktrees whose working tree is gone.
///
/// Skips locked worktrees. Returns paths to pruned working trees (for reporting).
///
/// # Errors
///
/// Propagates I/O failures while reading or removing admin directories.
pub fn prune_linked_worktrees(repo: &Repository) -> Result<Vec<PathBuf>> {
    let common = common_git_dir(repo.git_dir());
    let worktrees_dir = common.join("worktrees");
    if !worktrees_dir.is_dir() {
        return Ok(Vec::new());
    }

    let mut pruned = Vec::new();
    for entry in list_worktrees(repo)? {
        if entry.admin_dir == common || entry.is_locked || !entry.is_prunable {
            continue;
        }
        let wt_path = entry.path.clone();
        fs::remove_dir_all(&entry.admin_dir).map_err(Error::Io)?;
        pruned.push(wt_path);
    }
    Ok(pruned)
}

fn linked_worktree_entry(
    admin: &Path,
    common: &Path,
    current_admin: &Path,
) -> Result<WorktreeEntry> {
    let wt_path = read_worktree_path(admin)?;
    let wt_head = resolve_linked_head(admin, common);
    let (is_locked, lock_reason) = read_lock_state(admin)?;
    let (is_prunable, prunable_reason) = linked_worktree_prunable_state(admin, is_locked, &wt_path);
    Ok(WorktreeEntry {
        path: wt_path,
        head: wt_head,
        is_bare: false,
        is_locked,
        lock_reason,
        admin_dir: admin.to_path_buf(),
        is_prunable,
        prunable_reason,
        is_current: admin_dirs_match(admin, current_admin),
    })
}

/// Match [`worktree_entry_is_prunable`] syscall order; attach a reason only when prunable.
fn linked_worktree_prunable_state(
    admin: &Path,
    is_locked: bool,
    wt_path: &Path,
) -> (bool, Option<PrunableReason>) {
    if is_locked {
        return (false, None);
    }
    if admin.join("prunable").is_file() {
        return (true, Some(PrunableReason::ExplicitMarker));
    }
    if wt_path.exists() {
        return (false, None);
    }
    (
        true,
        Some(linked_worktree_prunable_reason_when_missing(admin)),
    )
}

fn linked_worktree_prunable_reason_when_missing(admin: &Path) -> PrunableReason {
    if !admin.is_dir() {
        return PrunableReason::AdminNotValidDirectory;
    }
    let gitdir_file = admin.join("gitdir");
    if !gitdir_file.is_file() {
        return PrunableReason::GitdirFileMissing;
    }
    let raw = fs::read_to_string(&gitdir_file).unwrap_or_default();
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return PrunableReason::InvalidGitdirFile;
    }
    let mut dotgit = PathBuf::from(trimmed);
    if dotgit.is_relative() {
        dotgit = admin.join(dotgit);
    }
    let dotgit = path_for_disk_compare(&dotgit);
    if !dotgit.is_file() {
        return PrunableReason::GitdirPointsElsewhere;
    }
    PrunableReason::WorktreePathMissing
}

/// Resolve `path` for [`add_linked_worktree`].
///
/// Relative paths are interpreted from `relative_to` (typically the process working
/// directory at the CLI boundary). The result is absolute and stable for registry
/// comparison even when the leaf directory does not exist yet.
///
/// # Errors
///
/// Returns [`Error::Message`] when `path` has no final component.
pub fn resolve_linked_worktree_add_path(path: &Path, relative_to: &Path) -> Result<PathBuf> {
    if path.exists() {
        return Ok(path_for_disk_compare(path));
    }
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        relative_to.join(path)
    };
    if let Some(parent) = absolute.parent().filter(|p| p.exists()) {
        let Some(name) = absolute.file_name() else {
            return Err(Error::Message("invalid worktree path".into()));
        };
        let mut resolved = path_for_disk_compare(parent);
        resolved.push(name);
        return Ok(resolved);
    }
    Ok(absolute)
}

struct WorktreeAdminAddPlan {
    admin_dir: PathBuf,
    stale_admins: Option<Vec<PathBuf>>,
}

/// On failure after stale admin dirs were moved aside, restore them.
struct StaleWorktreeAdminBackup {
    moved_aside: Vec<(PathBuf, PathBuf)>,
    new_admin: Option<PathBuf>,
    replacement_worktree: Option<(PathBuf, bool)>,
}

impl StaleWorktreeAdminBackup {
    fn remove_and_backup(stale_admins: Vec<PathBuf>) -> Result<Self> {
        let mut moved_aside = Vec::new();
        for (i, admin) in stale_admins.into_iter().enumerate() {
            let id = admin
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| "wt".to_owned());
            let aside = admin
                .parent()
                .ok_or_else(|| Error::Message("invalid worktree admin path".into()))?
                .join(format!(".{id}-stale-backup-{i}"));
            if aside.exists() {
                fs::remove_dir_all(&aside).map_err(Error::Io)?;
            }
            fs::rename(&admin, &aside).map_err(Error::Io)?;
            moved_aside.push((admin, aside));
        }
        Ok(Self {
            moved_aside,
            new_admin: None,
            replacement_worktree: None,
        })
    }

    fn set_new_admin(&mut self, admin: &Path) {
        self.new_admin = Some(admin.to_path_buf());
    }

    fn track_replacement_worktree(&mut self, path: &Path, absent_before_replacement: bool) {
        self.replacement_worktree = Some((path.to_path_buf(), absent_before_replacement));
    }

    fn commit(mut self) {
        for (_, aside) in self.moved_aside.drain(..) {
            let _ = fs::remove_dir_all(aside);
        }
    }
}

impl Drop for StaleWorktreeAdminBackup {
    fn drop(&mut self) {
        if self.moved_aside.is_empty() {
            return;
        }
        if let Some((wt_path, absent_before)) = self.replacement_worktree.take() {
            if absent_before {
                let _ = fs::remove_dir_all(&wt_path);
            } else if wt_path.join(".git").is_file() {
                let _ = fs::remove_file(wt_path.join(".git"));
            }
        }
        if let Some(new_admin) = self.new_admin.take() {
            let _ = fs::remove_dir_all(new_admin);
        }
        for (admin, aside) in &self.moved_aside {
            let _ = fs::remove_dir_all(admin);
            let _ = fs::rename(aside, admin);
        }
    }
}

fn linked_admins_for_worktree_path(common: &Path, wt_path: &Path) -> Result<Vec<PathBuf>> {
    let target = path_for_disk_compare(wt_path);
    let worktrees_dir = common.join("worktrees");
    if !worktrees_dir.is_dir() {
        return Ok(Vec::new());
    }
    let mut admins = Vec::new();
    for entry in fs::read_dir(&worktrees_dir).map_err(Error::Io)? {
        let entry = entry.map_err(Error::Io)?;
        if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
            continue;
        }
        let admin = entry.path();
        let registered = read_worktree_path(&admin)?;
        if path_for_disk_compare(&registered) == target {
            admins.push(admin);
        }
    }
    Ok(admins)
}

fn plan_admin_dir_for_add(
    common: &Path,
    wt_path: &Path,
    force: bool,
) -> Result<WorktreeAdminAddPlan> {
    let existing = linked_admins_for_worktree_path(common, wt_path)?;
    if existing.is_empty() {
        return Ok(WorktreeAdminAddPlan {
            admin_dir: allocate_worktree_admin_dir(common, wt_path),
            stale_admins: None,
        });
    }

    let display = wt_path.display().to_string();
    if wt_path.exists() {
        return Err(Error::WorktreePathRegistered { path: display });
    }
    if !force {
        return Err(Error::WorktreePathRegisteredMissing { path: display });
    }

    let worktrees_dir = common.join("worktrees");
    let base = sanitize_worktree_id_component(&worktree_path_basename(wt_path));
    let base = if base.is_empty() {
        "worktree".to_owned()
    } else {
        base
    };
    let preferred = worktrees_dir.join(&base);
    let admin_dir = existing
        .iter()
        .find(|admin| {
            admin
                .file_name()
                .is_some_and(|name| name.to_string_lossy() == base)
        })
        .cloned()
        .unwrap_or_else(|| {
            if preferred.exists() {
                allocate_worktree_admin_dir(common, wt_path)
            } else {
                preferred
            }
        });
    Ok(WorktreeAdminAddPlan {
        admin_dir,
        stale_admins: Some(existing),
    })
}

/// Remove a linked worktree and its admin directory.
///
/// # Errors
///
/// Refuses to remove the main worktree, locked worktrees (unless `force`), or dirty
/// trees (unless `force`).
pub fn remove_linked_worktree(repo: &Repository, path: &Path, force: bool) -> Result<()> {
    let common = common_git_dir(repo.git_dir());
    let target = path_for_disk_compare(path);
    let entry = list_worktrees(repo)?
        .into_iter()
        .find(|e| e.path == target)
        .ok_or_else(|| {
            Error::Message(format!(
                "'{}' is not a registered worktree",
                target.display()
            ))
        })?;
    if entry.admin_dir == common {
        return Err(Error::Message("cannot remove the main working tree".into()));
    }
    if entry.is_locked && !force {
        return Err(Error::Message(
            entry
                .lock_reason
                .map(|r| format!("worktree is locked: {r}"))
                .unwrap_or_else(|| "worktree is locked".into()),
        ));
    }

    let linked = Repository::discover(
        Some(entry.path.as_path()),
        &repo.linked_worktree_discover_options(),
    )?;
    if !force && worktree_has_local_changes(&linked)? {
        return Err(Error::Message(
            "worktree contains modified or untracked files; use -f or --force to remove".into(),
        ));
    }

    fs::remove_dir_all(&entry.admin_dir).map_err(Error::Io)?;
    if entry.path.exists() {
        fs::remove_dir_all(&entry.path).map_err(Error::Io)?;
    }
    Ok(())
}

fn resolve_existing_branch(repo: &Repository, spec: &str) -> Option<String> {
    let full = if spec.starts_with("refs/heads/") {
        spec.to_owned()
    } else {
        format!("refs/heads/{spec}")
    };
    refs::resolve_ref(repo.git_dir(), &full).ok()?;
    Some(full)
}

fn branch_checked_out_elsewhere(repo: &Repository, branch_ref: &str) -> Result<()> {
    let resolved = branch_ref.to_owned();
    for wt in list_worktrees(repo)? {
        if let HeadState::Branch { refname, .. } = &wt.head {
            if refname == &resolved {
                return Err(Error::Message(format!(
                    "branch '{}' is already checked out at '{}'",
                    resolved.strip_prefix("refs/heads/").unwrap_or(&resolved),
                    wt.path.display()
                )));
            }
        }
    }
    Ok(())
}

fn ensure_empty_or_missing(path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    if !path.is_dir() {
        return Err(Error::Message(format!(
            "'{}' already exists and is not a directory",
            path.display()
        )));
    }
    let mut entries = fs::read_dir(path).map_err(Error::Io)?;
    if entries.next().is_some() {
        return Err(Error::Message(format!(
            "'{}' already exists",
            path.display()
        )));
    }
    Ok(())
}

fn worktree_has_local_changes(repo: &Repository) -> Result<bool> {
    let model = status(repo, &StatusOptions::default(), &mut NullProgress)?;
    Ok(!model.staged.is_empty()
        || !model.unstaged.is_empty()
        || !model.conflicts.is_empty()
        || !model.untracked.is_empty())
}

/// Read the working tree path from `<admin>/gitdir` (parent of the worktree `.git` file).
pub fn read_worktree_path(admin: &Path) -> Result<PathBuf> {
    let gitdir_path = admin.join("gitdir");
    if !gitdir_path.is_file() {
        return Ok(admin.to_path_buf());
    }
    let raw = fs::read_to_string(&gitdir_path).map_err(Error::Io)?;
    let mut p = PathBuf::from(raw.trim());
    if p.is_relative() {
        p = admin.join(p);
    }
    let parent = p.parent().unwrap_or(&p).to_path_buf();
    Ok(path_for_disk_compare(&parent))
}

fn read_lock_state(admin: &Path) -> Result<(bool, Option<String>)> {
    let locked_file = admin.join("locked");
    if !locked_file.is_file() {
        return Ok((false, None));
    }
    let content = fs::read_to_string(&locked_file).map_err(Error::Io)?;
    let reason = content.trim();
    if reason.is_empty() {
        Ok((true, None))
    } else {
        Ok((true, Some(reason.to_owned())))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::repo::Repository;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn list_main_worktree_only() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join("repo");
        fs::create_dir_all(root.join(".git")).unwrap();
        fs::write(root.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
        fs::create_dir_all(root.join(".git/objects")).unwrap();
        fs::write(
            root.join(".git/config"),
            "[core]\n\trepositoryformatversion = 0\n",
        )
        .unwrap();

        let repo = Repository::open(
            &root.join(".git"),
            &RepositoryOptions::empty().with_work_tree(&root),
        )
        .unwrap();
        let list = list_worktrees(&repo).unwrap();
        assert_eq!(list.len(), 1);
        assert_eq!(list[0].path, path_for_disk_compare(&root));
        assert!(!list[0].is_bare);
    }

    #[test]
    fn allocate_unique_worktree_id() {
        let tmp = TempDir::new().unwrap();
        let common = tmp.path().join("git");
        fs::create_dir_all(common.join("worktrees/here")).unwrap();
        let admin = allocate_worktree_admin_dir(&common, Path::new("/tmp/sub/here"));
        assert_eq!(admin, common.join("worktrees/here1"));
    }

    #[test]
    fn strip_worktree_config_removes_core_bare_and_worktree() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("config.worktree");
        fs::write(
            &path,
            "[core]\n\tbare = true\n\tworktree = /wt\n[bogus]\n\tkey = value\n",
        )
        .unwrap();
        strip_worktree_config_keys(&path, &["core.bare", "core.worktree"]).unwrap();
        let out = fs::read_to_string(&path).unwrap();
        assert!(out.contains("bogus"));
        assert!(!out.contains("bare"));
        assert!(!out.contains("worktree"));
    }

    #[test]
    fn sanitize_funny_worktree_name() {
        assert_eq!(
            sanitize_worktree_id_component(".  weird*..?.lock.lock"),
            "---weird-.-"
        );
    }

    #[test]
    fn read_worktree_path_from_gitdir_file() {
        let tmp = TempDir::new().unwrap();
        let admin = tmp.path().join("wt-admin");
        fs::create_dir_all(&admin).unwrap();
        let wt = tmp.path().join("linked");
        fs::create_dir_all(wt.join(".git")).unwrap();
        fs::write(
            admin.join("gitdir"),
            format!("{}\n", wt.join(".git").display()),
        )
        .unwrap();
        let path = read_worktree_path(&admin).unwrap();
        assert_eq!(path, path_for_disk_compare(&wt));
    }

    #[test]
    fn add_and_remove_linked_worktree_via_library() {
        use std::process::Command;
        let tmp = TempDir::new().unwrap();
        let main = tmp.path().join("main");
        fs::create_dir_all(&main).unwrap();
        let git = |args: &[&str]| {
            let out = Command::new("git")
                .env("GIT_AUTHOR_NAME", "Test")
                .env("GIT_AUTHOR_EMAIL", "test@example.com")
                .env("GIT_COMMITTER_NAME", "Test")
                .env("GIT_COMMITTER_EMAIL", "test@example.com")
                .current_dir(&main)
                .args(args)
                .output()
                .unwrap();
            assert!(out.status.success(), "git {args:?}");
        };
        git(&["init", "-q", "-b", "main"]);
        fs::write(main.join("t"), b"1\n").unwrap();
        git(&["add", "t"]);
        git(&["commit", "-qm", "init"]);

        let repo = Repository::discover(Some(main.as_path()), &RepositoryOptions::empty()).unwrap();
        let linked = tmp.path().join("linked");
        add_linked_worktree(
            &repo,
            &AddLinkedWorktreeOptions {
                path: linked.clone(),
                branch: Some("wt".into()),
                new_branch: true,
                detach: false,
                start_point: Some("HEAD".into()),
                force: false,
            },
        )
        .unwrap();
        assert_eq!(list_worktrees(&repo).unwrap().len(), 2);
        remove_linked_worktree(&repo, &linked, false).unwrap();
        assert_eq!(list_worktrees(&repo).unwrap().len(), 1);
    }

    #[test]
    fn registered_worktree_count_and_basename() {
        let tmp = TempDir::new().unwrap();
        let common = tmp.path().join("git");
        fs::create_dir_all(common.join("worktrees/a")).unwrap();
        fs::create_dir_all(common.join("worktrees/b")).unwrap();
        assert_eq!(registered_worktree_count(&common), 3);
        assert_eq!(
            worktree_path_basename(Path::new("/tmp/my/project/")),
            "project"
        );
    }

    #[test]
    fn registered_worktree_count_without_worktrees_dir() {
        let tmp = TempDir::new().unwrap();
        let common = tmp.path().join("only-main");
        fs::create_dir_all(&common).unwrap();
        assert_eq!(registered_worktree_count(&common), 1);
    }

    #[test]
    fn common_git_dir_and_bare_detection() {
        let tmp = TempDir::new().unwrap();
        let git_dir = tmp.path().join("bare.git");
        fs::create_dir_all(&git_dir).unwrap();
        fs::write(
            git_dir.join("config"),
            "[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
        )
        .unwrap();
        assert!(is_bare_repository(&git_dir));
        assert_eq!(common_git_dir(&git_dir), git_dir);
    }

    #[test]
    fn sanitize_worktree_id_special_cases() {
        assert_eq!(sanitize_worktree_id_component("@"), "-");
        assert!(!sanitize_worktree_id_component("@{upstream}").contains('@'));
        assert_eq!(sanitize_worktree_id_component("..name"), ".name");
        assert_eq!(sanitize_worktree_id_component(".lock.lock"), "-lock");
        let tmp = TempDir::new().unwrap();
        let common = tmp.path().join("git");
        fs::create_dir_all(&common).unwrap();
        assert_eq!(
            allocate_worktree_admin_dir(&common, Path::new("/")),
            common.join("worktrees/worktree")
        );
    }

    #[test]
    fn copy_filtered_worktree_config_no_source_is_ok() {
        let tmp = TempDir::new().unwrap();
        let admin = tmp.path().join("admin");
        fs::create_dir_all(&admin).unwrap();
        copy_filtered_worktree_config(tmp.path(), &admin).unwrap();
        assert!(!admin.join("config.worktree").exists());
    }

    #[test]
    fn copy_filtered_worktree_config_copies_file() {
        let tmp = TempDir::new().unwrap();
        let common = tmp.path().join("common");
        let admin = tmp.path().join("admin");
        fs::create_dir_all(&common).unwrap();
        fs::create_dir_all(&admin).unwrap();
        fs::write(
            common.join("config.worktree"),
            "[core]\n\tbare = false\n\tworktree = /x\n[ext]\n\tk = v\n",
        )
        .unwrap();
        copy_filtered_worktree_config(&common, &admin).unwrap();
        let out = fs::read_to_string(admin.join("config.worktree")).unwrap();
        assert!(out.contains("[ext]"));
        assert!(!out.contains("worktree"));
    }

    #[test]
    fn read_lock_state_and_missing_gitdir_path() {
        let tmp = TempDir::new().unwrap();
        let admin = tmp.path().join("admin");
        fs::create_dir_all(&admin).unwrap();
        assert_eq!(read_worktree_path(&admin).unwrap(), admin);
        fs::write(admin.join("locked"), "maintenance\n").unwrap();
        let (locked, reason) = read_lock_state(&admin).unwrap();
        assert!(locked);
        assert_eq!(reason.as_deref(), Some("maintenance"));
    }

    #[test]
    fn ensure_empty_or_missing_rejects_nonempty_dir() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("occupied");
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("file"), b"x").unwrap();
        assert!(ensure_empty_or_missing(&dir).is_err());
        let missing = tmp.path().join("missing");
        assert!(ensure_empty_or_missing(&missing).is_ok());
    }

    #[test]
    fn add_linked_worktree_rejects_bare_repository() {
        let tmp = TempDir::new().unwrap();
        let bare = tmp.path().join("bare.git");
        fs::create_dir_all(bare.join("objects")).unwrap();
        fs::write(bare.join("HEAD"), "ref: refs/heads/main\n").unwrap();
        fs::write(
            bare.join("config"),
            "[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
        )
        .unwrap();
        let repo = Repository::open(&bare, &RepositoryOptions::empty()).unwrap();
        let err = add_linked_worktree(
            &repo,
            &AddLinkedWorktreeOptions {
                path: tmp.path().join("wt"),
                branch: Some("wt".into()),
                new_branch: true,
                detach: false,
                start_point: None,
                force: false,
            },
        )
        .unwrap_err();
        assert!(matches!(err, Error::Message(_)));
    }

    #[test]
    fn list_worktrees_from_linked_checkout_normalizes_main_path() {
        use std::process::Command;
        let tmp = TempDir::new().unwrap();
        let main = tmp.path().join("main");
        fs::create_dir_all(&main).unwrap();
        let git = |args: &[&str]| {
            assert!(Command::new("git")
                .env("GIT_AUTHOR_NAME", "Test")
                .env("GIT_AUTHOR_EMAIL", "test@example.com")
                .env("GIT_COMMITTER_NAME", "Test")
                .env("GIT_COMMITTER_EMAIL", "test@example.com")
                .current_dir(&main)
                .args(args)
                .output()
                .unwrap()
                .status
                .success());
        };
        git(&["init", "-q", "-b", "main"]);
        fs::write(main.join("t"), b"1\n").unwrap();
        git(&["add", "t"]);
        git(&["commit", "-qm", "init"]);

        let repo = Repository::discover(Some(main.as_path()), &RepositoryOptions::empty()).unwrap();
        let linked = tmp.path().join("linked");
        add_linked_worktree(
            &repo,
            &AddLinkedWorktreeOptions {
                path: linked.clone(),
                branch: Some("wt".into()),
                new_branch: true,
                detach: false,
                start_point: Some("HEAD".into()),
                force: false,
            },
        )
        .unwrap();

        let linked_repo =
            Repository::discover(Some(linked.as_path()), &RepositoryOptions::empty()).unwrap();
        let list = list_worktrees(&linked_repo).unwrap();
        assert_eq!(list.len(), 2);
        let expected_main = path_for_disk_compare(&main);
        assert_eq!(list[0].path, expected_main);
        #[cfg(windows)]
        {
            let displayed = list[0].path.display().to_string();
            assert!(
                !displayed.starts_with(r"\\?\"),
                "main worktree path must not use the verbatim prefix: {displayed}"
            );
        }
    }

    #[test]
    fn branch_checkout_exclusivity_helpers() {
        use std::process::Command;
        let tmp = TempDir::new().unwrap();
        let main = tmp.path().join("main");
        fs::create_dir_all(&main).unwrap();
        let git = |args: &[&str]| {
            assert!(Command::new("git")
                .env("GIT_AUTHOR_NAME", "Test")
                .env("GIT_AUTHOR_EMAIL", "test@example.com")
                .env("GIT_COMMITTER_NAME", "Test")
                .env("GIT_COMMITTER_EMAIL", "test@example.com")
                .current_dir(&main)
                .args(args)
                .output()
                .unwrap()
                .status
                .success());
        };
        git(&["init", "-q", "-b", "main"]);
        fs::write(main.join("t"), b"1\n").unwrap();
        git(&["add", "t"]);
        git(&["commit", "-qm", "init"]);

        let repo = Repository::discover(Some(main.as_path()), &RepositoryOptions::empty()).unwrap();
        let linked = tmp.path().join("linked");
        add_linked_worktree(
            &repo,
            &AddLinkedWorktreeOptions {
                path: linked.clone(),
                branch: Some("feature".into()),
                new_branch: true,
                detach: false,
                start_point: Some("HEAD".into()),
                force: false,
            },
        )
        .unwrap();

        let linked_repo =
            Repository::discover(Some(linked.as_path()), &RepositoryOptions::empty()).unwrap();
        let linked_admin = linked_repo
            .git_dir()
            .canonicalize()
            .unwrap_or_else(|_| linked_repo.git_dir().to_path_buf());
        assert_eq!(worktree_admin_dir(&linked_repo), linked_admin);

        let found = find_worktree_with_branch_checked_out(&repo, "feature", None)
            .unwrap()
            .expect("linked checkout");
        assert_eq!(found.branch, "feature");

        assert!(ensure_branch_not_checked_out_in_any_worktree(&repo, "feature").is_err());
        assert!(ensure_branch_not_checked_out_elsewhere(&linked_repo, "feature").is_ok());
        assert!(ensure_branch_not_checked_out_elsewhere(&repo, "feature").is_err());
    }

    #[test]
    fn missing_registered_path_rejects_add_without_force() {
        use std::process::Command;
        let tmp = TempDir::new().unwrap();
        let main = tmp.path().join("main");
        fs::create_dir_all(&main).unwrap();
        let git = |args: &[&str]| {
            assert!(Command::new("git")
                .current_dir(&main)
                .args(args)
                .output()
                .unwrap()
                .status
                .success());
        };
        git(&["init", "-q", "-b", "main"]);
        fs::write(main.join("t"), b"1\n").unwrap();
        git(&["add", "t"]);
        git(&["commit", "-qm", "init"]);

        let repo =
            Repository::discover(Some(&main), &crate::environment::RepositoryOptions::empty())
                .unwrap();
        let linked = tmp.path().join("linked");
        add_linked_worktree(
            &repo,
            &AddLinkedWorktreeOptions {
                path: linked.clone(),
                branch: Some("a".into()),
                new_branch: true,
                detach: false,
                start_point: Some("HEAD".into()),
                force: false,
            },
        )
        .unwrap();
        fs::remove_dir_all(&linked).unwrap();
        assert!(matches!(
            add_linked_worktree(
                &repo,
                &AddLinkedWorktreeOptions {
                    path: linked.clone(),
                    branch: Some("b".into()),
                    new_branch: true,
                    detach: false,
                    start_point: Some("HEAD".into()),
                    force: false,
                },
            )
            .unwrap_err(),
            Error::WorktreePathRegisteredMissing { .. }
        ));
    }

    #[test]
    fn remove_linked_worktree_refuses_main_and_locked() {
        use std::process::Command;
        let tmp = TempDir::new().unwrap();
        let main = tmp.path().join("main");
        fs::create_dir_all(&main).unwrap();
        let git = |args: &[&str]| {
            assert!(Command::new("git")
                .env("GIT_AUTHOR_NAME", "Test")
                .env("GIT_AUTHOR_EMAIL", "test@example.com")
                .env("GIT_COMMITTER_NAME", "Test")
                .env("GIT_COMMITTER_EMAIL", "test@example.com")
                .current_dir(&main)
                .args(args)
                .output()
                .unwrap()
                .status
                .success());
        };
        git(&["init", "-q", "-b", "main"]);
        fs::write(main.join("t"), b"1\n").unwrap();
        git(&["add", "t"]);
        git(&["commit", "-qm", "init"]);

        let repo = Repository::discover(Some(main.as_path()), &RepositoryOptions::empty()).unwrap();
        assert!(remove_linked_worktree(&repo, &main, false).is_err());

        let linked = tmp.path().join("linked");
        add_linked_worktree(
            &repo,
            &AddLinkedWorktreeOptions {
                path: linked.clone(),
                branch: Some("wt".into()),
                new_branch: true,
                detach: false,
                start_point: Some("HEAD".into()),
                force: false,
            },
        )
        .unwrap();
        let common = common_git_dir(repo.git_dir());
        let admin = fs::read_dir(common.join("worktrees"))
            .unwrap()
            .find_map(|e| e.ok())
            .map(|e| e.path())
            .expect("admin");
        fs::write(admin.join("locked"), "hold\n").unwrap();
        assert!(remove_linked_worktree(&repo, &linked, false).is_err());
        assert!(remove_linked_worktree(&repo, &linked, true).is_ok());
    }
}