Skip to content

Commit 67be714

Browse files
committed
[Worktree] Offer to repair worktree links after the main repository moves
Moving the main repository's folder leaves every linked worktree pointing at the old place, while `git worktree list` still reports them as healthy (#739). - Check each linked worktree's .git link on every worktree reload, the way `git worktree repair` does, including a worktree nested in the main folder that moved along with it - Offer a sheet once per window: Repair as Absolute Paths, Repair as Relative Paths (git 2.48), or Skip Repair; the default follows the style the links already share, absolute when they differ - After Skip, dim the broken rows, offer Repair Worktree Links in the row menu, and hold Prune back while a moved-along worktree would be forgotten
1 parent 646aabc commit 67be714

13 files changed

Lines changed: 895 additions & 12 deletions

‎Classes/Controllers/PBGitHistoryController.m‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1196,6 +1196,16 @@ - (NSMenuItem *)locateMenuItemForWorktree:(PBGitWorktree *)worktree
11961196
return [self menuItemWithTitle:NSLocalizedString(@"Locate Worktree Folder…", @"Contextual Menu Item to tell git where a worktree's folder was moved to") action:@selector(locateWorktreeFolder:) worktree:worktree disabledBecause:reason];
11971197
}
11981198

1199+
- (NSMenuItem *)repairLinksMenuItemForWorktree:(PBGitWorktree *)worktree
1200+
{
1201+
NSString *version = self.gitVersion;
1202+
NSString *reason = nil;
1203+
if (![PBGitBinary version:version isAtLeast:@PBGitWorktreeRepairVersion])
1204+
reason = [PBGitBinary explanationForVersion:version belowRequired:@PBGitWorktreeRepairVersion];
1205+
1206+
return [self menuItemWithTitle:NSLocalizedString(@"Repair Worktree Links…", @"Contextual Menu Item to reconnect worktrees that can no longer find the moved main repository") action:@selector(repairWorktreeLinks:) worktree:worktree disabledBecause:reason];
1207+
}
1208+
11991209
- (NSMenuItem *)removeMenuItemForWorktree:(PBGitWorktree *)worktree
12001210
{
12011211
NSString *version = self.gitVersion;
@@ -1232,6 +1242,8 @@ - (NSMenuItem *)checkOutInNewWorktreeMenuItemForBranch:(PBGitRef *)branch isHead
12321242
{
12331243
BOOL folderIsThere = [[NSFileManager defaultManager] fileExistsAtPath:worktree.path];
12341244
NSMenuItem *folderItem = folderIsThere ? [self revealMenuItemForWorktree:worktree] : [self locateMenuItemForWorktree:worktree];
1245+
if (worktree.hasBrokenLink)
1246+
folderItem = [self repairLinksMenuItemForWorktree:worktree];
12351247

12361248
return [@[ folderItem ] arrayByAddingObjectsFromArray:[self lockMenuItemsForWorktree:worktree]];
12371249
}
@@ -1253,6 +1265,15 @@ - (BOOL)anyWorktreeCanBePruned
12531265
return NO;
12541266
}
12551267

1268+
- (BOOL)anyWorktreeMovedWithRepository
1269+
{
1270+
for (PBGitWorktree *worktree in self.repository.worktrees)
1271+
if (worktree.movedPath)
1272+
return YES;
1273+
1274+
return NO;
1275+
}
1276+
12561277
- (NSArray<NSMenuItem *> *)menuItemsForWorktreeGroup
12571278
{
12581279
NSString *version = self.gitVersion;
@@ -1261,6 +1282,8 @@ - (BOOL)anyWorktreeCanBePruned
12611282

12621283
if (![PBGitBinary version:version isAtLeast:@PBGitWorktreePruneVersion])
12631284
pruneReason = [PBGitBinary explanationForVersion:version belowRequired:@PBGitWorktreePruneVersion];
1285+
else if ([self anyWorktreeMovedWithRepository])
1286+
pruneReason = NSLocalizedString(@"Repair the worktree links first: git would forget a worktree that moved with this repository", @"Contextual Menu Item tooltip when pruning would drop a worktree that moved along with the main repository");
12641287
else if (![self anyWorktreeCanBePruned])
12651288
pruneReason = NSLocalizedString(@"Every worktree still has its folder", @"Contextual Menu Item tooltip when no worktree can be pruned");
12661289

‎Classes/Controllers/PBGitSidebarController.m‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,9 @@ - (void)doubleClicked:(id)object
350350
id item = [sourceView itemAtRow:rowNumber];
351351
if ([item isKindOfClass:[PBSourceViewGitWorktreeItem class]]) {
352352
PBSourceViewGitWorktreeItem *worktreeItem = item;
353-
if (worktreeItem.isUnavailable)
353+
if (worktreeItem.worktree.hasBrokenLink)
354+
[self.windowController repairWorktreeLinks:self];
355+
else if (worktreeItem.isUnavailable)
354356
[self.windowController showMissingFolderOfWorktree:worktreeItem.worktree];
355357
else
356358
[self openRepositoryAtURL:worktreeItem.URL];

‎Classes/Controllers/PBGitWindowController.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ NS_ASSUME_NONNULL_BEGIN
5959
- (IBAction)unlockWorktree:(id)sender;
6060
- (IBAction)revealWorktreeInFinder:(id)sender;
6161
- (IBAction)locateWorktreeFolder:(id)sender;
62+
- (IBAction)repairWorktreeLinks:(id)sender;
6263
- (IBAction)pruneWorktrees:(id)sender;
6364
- (IBAction)checkOutInNewWorktree:(id)sender;
6465
- (IBAction)addWorktree:(id)sender;

‎Classes/Controllers/PBGitWindowController.m‎

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ @interface PBGitWindowController () <NSMenuItemValidation> {
4747
__weak IBOutlet NSTextField *statusField;
4848
__weak IBOutlet NSProgressIndicator *progressIndicator;
4949
}
50+
51+
@property (nonatomic, assign) BOOL offeredToRepairWorktreeLinks;
52+
5053
@end
5154

5255
@implementation PBGitWindowController
@@ -59,6 +62,8 @@ - (instancetype)init
5962
if (!self)
6063
return nil;
6164

65+
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(offerToRepairWorktreeLinks) name:PBGitBinaryVersionDidChangeNotification object:nil];
66+
6267
return self;
6368
}
6469

@@ -81,6 +86,8 @@ - (void)windowWillClose:(NSNotification *)notification
8186
{
8287
// NSLog(@"Window will close!");
8388

89+
[self.repository removeObserver:self keyPath:@"worktrees"];
90+
8491
[self.sidebarViewController closeView];
8592
[self.historyViewController closeView];
8693
[self.commitViewController closeView];
@@ -147,6 +154,19 @@ - (void)windowDidLoad
147154

148155
[[statusField cell] setBackgroundStyle:NSBackgroundStyleRaised];
149156
[progressIndicator setUsesThreadedAnimation:YES];
157+
158+
[self.repository addObserver:self
159+
keyPath:@"worktrees"
160+
options:0
161+
block:^(MAKVONotification *notification) {
162+
PBGitWindowController *observer = notification.observer;
163+
[observer offerToRepairWorktreeLinks];
164+
}];
165+
}
166+
167+
- (void)windowDidBecomeKey:(NSNotification *)notification
168+
{
169+
[self offerToRepairWorktreeLinks];
150170
}
151171

152172
- (void)removeAllContentSubViews
@@ -777,6 +797,11 @@ - (void)openWorktreeHoldingRef:(PBGitRef *)ref
777797
if (!worktreePath) return;
778798

779799
PBGitWorktree *worktree = [self.repository worktreeHoldingRef:ref];
800+
if (worktree.hasBrokenLink) {
801+
[self repairWorktreeLinks:self];
802+
return;
803+
}
804+
780805
if (worktree && ![[NSFileManager defaultManager] fileExistsAtPath:worktreePath]) {
781806
[self showMissingFolderOfWorktree:worktree];
782807
return;
@@ -849,6 +874,163 @@ - (void)locateFolderOfWorktree:(PBGitWorktree *)worktree
849874
}];
850875
}
851876

877+
- (NSArray<PBGitWorktree *> *)worktreesWithBrokenLinks
878+
{
879+
NSMutableArray<PBGitWorktree *> *broken = [NSMutableArray array];
880+
for (PBGitWorktree *worktree in self.repository.worktrees)
881+
if (worktree.hasBrokenLink)
882+
[broken addObject:worktree];
883+
884+
return broken;
885+
}
886+
887+
+ (NSView *)listOfWorktrees:(NSArray<PBGitWorktree *> *)worktrees
888+
{
889+
NSMutableArray<NSView *> *rows = [NSMutableArray array];
890+
891+
for (PBGitWorktree *worktree in worktrees) {
892+
NSString *branch = [worktree.branchRefName hasPrefix:@"refs/heads/"] ? [worktree.branchRefName substringFromIndex:[@"refs/heads/" length]] : worktree.branchRefName;
893+
NSString *path = worktree.movedPath ?: worktree.path;
894+
NSString *shown = path.stringByAbbreviatingWithTildeInPath;
895+
896+
NSTextField *row = [NSTextField labelWithString:branch ? [NSString stringWithFormat:@"%@ (%@)", shown, branch] : shown];
897+
row.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
898+
row.lineBreakMode = NSLineBreakByTruncatingMiddle;
899+
row.alignment = NSTextAlignmentCenter;
900+
row.toolTip = path;
901+
[row setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
902+
[rows addObject:row];
903+
}
904+
905+
NSStackView *list = [NSStackView stackViewWithViews:rows];
906+
list.orientation = NSUserInterfaceLayoutOrientationVertical;
907+
list.alignment = NSLayoutAttributeCenterX;
908+
list.spacing = 2;
909+
list.frame = NSMakeRect(0, 0, 220, list.fittingSize.height);
910+
for (NSView *row in rows)
911+
[row.widthAnchor constraintLessThanOrEqualToConstant:220].active = YES;
912+
913+
return list;
914+
}
915+
916+
// Repair writes every link in one style, so the button for the style the
917+
// links already share is the default, and absolute when they differ.
918+
- (NSAlert *)alertForBrokenLinksOfWorktrees:(NSArray<PBGitWorktree *> *)worktrees linkStyle:(PBGitWorktreeLinkStyle)style gitVersion:(NSString *)version
919+
{
920+
BOOL canRepair = [PBGitBinary version:version isAtLeast:@PBGitWorktreeRepairVersion];
921+
BOOL canChooseStyle = [PBGitBinary version:version isAtLeast:@PBGitWorktreeLinkStyleVersion];
922+
923+
NSAlert *alert = [[NSAlert alloc] init];
924+
alert.messageText = worktrees.count == 1 ? NSLocalizedString(@"This repository was moved, so one of its worktrees can no longer find it", @"Title of the sheet when one worktree's link to the moved main repository is broken") : [NSString stringWithFormat:NSLocalizedString(@"This repository was moved, so %lu of its worktrees can no longer find it", @"Title of the sheet when several worktrees' links to the moved main repository are broken"), (unsigned long)worktrees.count];
925+
926+
NSString *explanation = nil;
927+
if (!canRepair)
928+
explanation = [NSString stringWithFormat:NSLocalizedString(@"Reconnecting them needs git %@ or later, and GitX found git %@. Install a newer git, or choose one in Git Preferences…, then open this repository again.", @"Explanation on the broken worktree links sheet when git cannot repair them"), @PBGitWorktreeRepairVersion, version ?: @"?"];
929+
else if (!canChooseStyle)
930+
explanation = [NSString stringWithFormat:NSLocalizedString(@"GitX can reconnect them with “git worktree repair”, which writes the link of every worktree of this repository as an absolute path. Relative paths need git %@ or later, and GitX found git %@.", @"Explanation on the broken worktree links sheet when git can repair them only as absolute paths"), @PBGitWorktreeLinkStyleVersion, version];
931+
else
932+
explanation = NSLocalizedString(@"GitX can reconnect them with “git worktree repair”, which writes the link of every worktree of this repository in the style you choose.", @"Explanation on the broken worktree links sheet");
933+
934+
alert.informativeText = explanation;
935+
alert.accessoryView = [PBGitWindowController listOfWorktrees:worktrees];
936+
937+
NSButton *absolute = [alert addButtonWithTitle:NSLocalizedString(@"Repair as Absolute Paths", @"Button that repairs worktree links as absolute paths")];
938+
NSButton *relative = [alert addButtonWithTitle:NSLocalizedString(@"Repair as Relative Paths", @"Button that repairs worktree links as relative paths")];
939+
NSButton *skip = [alert addButtonWithTitle:NSLocalizedString(@"Skip Repair", @"Button that leaves broken worktree links as they are")];
940+
941+
absolute.enabled = canRepair;
942+
absolute.toolTip = canRepair ? nil : [PBGitBinary explanationForVersion:version belowRequired:@PBGitWorktreeRepairVersion];
943+
relative.enabled = canChooseStyle;
944+
relative.toolTip = canChooseStyle ? nil : [PBGitBinary explanationForVersion:version belowRequired:@PBGitWorktreeLinkStyleVersion];
945+
946+
NSButton *defaultButton = skip;
947+
if (relative.enabled && style == PBGitWorktreeLinkStyleRelative)
948+
defaultButton = relative;
949+
else if (absolute.enabled)
950+
defaultButton = absolute;
951+
952+
for (NSButton *button in alert.buttons)
953+
button.keyEquivalent = @"";
954+
defaultButton.keyEquivalent = @"\r";
955+
if (defaultButton != skip)
956+
skip.keyEquivalent = @"\033";
957+
958+
return alert;
959+
}
960+
961+
- (void)offerToRepairWorktreeLinks
962+
{
963+
NSArray<PBGitWorktree *> *broken = [self worktreesWithBrokenLinks];
964+
if (!broken.count) {
965+
self.offeredToRepairWorktreeLinks = NO;
966+
return;
967+
}
968+
969+
if (self.offeredToRepairWorktreeLinks || !self.window.isVisible || self.window.attachedSheet)
970+
return;
971+
972+
if ([PBGitBinary path].length && !self.gitVersion) {
973+
NSLog(@"git at %@ is still being checked, so the offer to repair worktree links waits for its version", [PBGitBinary path]);
974+
return;
975+
}
976+
977+
self.offeredToRepairWorktreeLinks = YES;
978+
[self showBrokenLinksOfWorktrees:broken];
979+
}
980+
981+
- (IBAction)repairWorktreeLinks:(id)sender
982+
{
983+
NSArray<PBGitWorktree *> *broken = [self worktreesWithBrokenLinks];
984+
if (broken.count)
985+
[self showBrokenLinksOfWorktrees:broken];
986+
}
987+
988+
- (nullable NSString *)gitVersion
989+
{
990+
return [PBGitBinary version];
991+
}
992+
993+
- (void)showBrokenLinksOfWorktrees:(NSArray<PBGitWorktree *> *)worktrees
994+
{
995+
NSString *version = self.gitVersion;
996+
NSAlert *alert = [self alertForBrokenLinksOfWorktrees:worktrees linkStyle:[PBGitWorktree linkStyleOfWorktrees:self.repository.worktrees] gitVersion:version];
997+
BOOL canChooseStyle = [PBGitBinary version:version isAtLeast:@PBGitWorktreeLinkStyleVersion];
998+
999+
NSButton *skip = alert.buttons.lastObject;
1000+
id escapeMonitor = nil;
1001+
if ([skip.keyEquivalent isEqualToString:@"\r"]) {
1002+
__weak NSAlert *weakAlert = alert;
1003+
escapeMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown
1004+
handler:^NSEvent *(NSEvent *event) {
1005+
if (event.window != weakAlert.window || ![event.charactersIgnoringModifiers isEqualToString:@"\033"])
1006+
return event;
1007+
1008+
[skip performClick:nil];
1009+
return nil;
1010+
}];
1011+
}
1012+
1013+
[alert beginSheetModalForWindow:self.window
1014+
completionHandler:^(NSModalResponse returnCode) {
1015+
if (escapeMonitor)
1016+
[NSEvent removeMonitor:escapeMonitor];
1017+
1018+
PBGitWorktreeLinkStyle style = PBGitWorktreeLinkStyleUnknown;
1019+
if (returnCode == NSAlertFirstButtonReturn)
1020+
style = canChooseStyle ? PBGitWorktreeLinkStyleAbsolute : PBGitWorktreeLinkStyleUnknown;
1021+
else if (returnCode == NSAlertSecondButtonReturn)
1022+
style = PBGitWorktreeLinkStyleRelative;
1023+
else
1024+
return;
1025+
1026+
dispatch_async(dispatch_get_main_queue(), ^{
1027+
NSError *error = nil;
1028+
if (![self.repository repairWorktreeLinksInStyle:style error:&error])
1029+
[self showErrorSheet:error];
1030+
});
1031+
}];
1032+
}
1033+
8521034
- (IBAction)lockWorktree:(id)sender
8531035
{
8541036
PBGitWorktree *worktree = [sender representedObject];
@@ -892,6 +1074,14 @@ - (IBAction)revealWorktreeInFinder:(id)sender
8921074

8931075
- (IBAction)pruneWorktrees:(id)sender
8941076
{
1077+
for (PBGitWorktree *worktree in self.repository.worktrees) {
1078+
if (!worktree.movedPath)
1079+
continue;
1080+
1081+
[self repairWorktreeLinks:sender];
1082+
return;
1083+
}
1084+
8951085
NSError *error = nil;
8961086
NSString *report = [self.repository worktreePruneReportWithError:&error];
8971087
if (!report) {

‎Classes/git/PBGitBinary.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@
1515
#define PBGitWorktreeRemoveVersion "2.17"
1616
#define PBGitWorktreeRepairVersion "2.29"
1717
#define PBGitWorktreeStateVersion "2.31"
18+
#define PBGitWorktreeLinkStyleVersion "2.48"
19+
20+
// Posted on the main queue once the version of the git in use is known or changes.
21+
extern NSString *const PBGitBinaryVersionDidChangeNotification;
1822

1923
@interface PBGitBinary : NSObject
2024

‎Classes/git/PBGitBinary.m‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ @implementation PBGitBinary
1414
static NSString *gitPath = nil;
1515
static NSString *gitVersion = nil;
1616

17+
NSString *const PBGitBinaryVersionDidChangeNotification = @"PBGitBinaryVersionDidChangeNotification";
18+
1719
+ (NSString *)versionForPath:(NSString *)path
1820
{
1921
if (!path)
@@ -52,6 +54,15 @@ + (NSString *)extractGitVersion:(NSString *)versionString
5254
return nil;
5355
}
5456

57+
+ (void)takeVersion:(NSString *)version
58+
{
59+
gitVersion = version;
60+
61+
dispatch_async(dispatch_get_main_queue(), ^{
62+
[[NSNotificationCenter defaultCenter] postNotificationName:PBGitBinaryVersionDidChangeNotification object:nil];
63+
});
64+
}
65+
5566
+ (BOOL)acceptBinary:(NSString *)path
5667
{
5768
if (!path)
@@ -64,7 +75,7 @@ + (BOOL)acceptBinary:(NSString *)path
6475
NSComparisonResult c = [version compare:@"" MIN_GIT_VERSION options:NSNumericSearch];
6576
if (c == NSOrderedSame || c == NSOrderedDescending) {
6677
gitPath = path;
67-
gitVersion = version;
78+
[self takeVersion:version];
6879
return YES;
6980
}
7081

@@ -125,7 +136,7 @@ + (void)validateConfiguredPath:(NSString *)path
125136

126137
dispatch_async(dispatch_get_main_queue(), ^{
127138
if (accepted) {
128-
gitVersion = version;
139+
[self takeVersion:version];
129140
return;
130141
}
131142

‎Classes/git/PBGitRepository.h‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
//
88

99
#import <Cocoa/Cocoa.h>
10+
#import "PBGitWorktree.h"
1011

1112
@class PBGitHistoryList;
12-
@class PBGitWorktree;
1313
@class PBGitRevSpecifier;
1414
@protocol PBGitRefish;
1515
@class PBGitRef;
@@ -93,6 +93,9 @@ typedef NS_ENUM(NSInteger, PBGitConfigScope) {
9393
- (BOOL)addWorktreeAtPath:(NSString *)path newBranchNamed:(NSString *)name error:(NSError **)error;
9494
- (BOOL)removeWorktree:(PBGitWorktree *)worktree force:(BOOL)force error:(NSError **)error;
9595
- (BOOL)repairWorktree:(PBGitWorktree *)worktree movedTo:(NSString *)path error:(NSError **)error;
96+
// Runs `git worktree repair`, which rewrites the link of every linked worktree
97+
// in the given style; Unknown passes no style and leaves it to git.
98+
- (BOOL)repairWorktreeLinksInStyle:(PBGitWorktreeLinkStyle)style error:(NSError **)error;
9699

97100
- (BOOL)checkoutRefish:(id<PBGitRefish>)ref error:(NSError **)error;
98101
- (BOOL)checkoutFiles:(NSArray *)files fromRefish:(id<PBGitRefish>)ref error:(NSError **)error;

0 commit comments

Comments
 (0)