Skip to content

Commit 4a6ba33

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 4a6ba33

12 files changed

Lines changed: 881 additions & 10 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:nil];
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: 192 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
@@ -81,6 +84,8 @@ - (void)windowWillClose:(NSNotification *)notification
8184
{
8285
// NSLog(@"Window will close!");
8386

87+
[self.repository removeObserver:self keyPath:@"worktrees"];
88+
8489
[self.sidebarViewController closeView];
8590
[self.historyViewController closeView];
8691
[self.commitViewController closeView];
@@ -147,6 +152,19 @@ - (void)windowDidLoad
147152

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

152170
- (void)removeAllContentSubViews
@@ -777,6 +795,11 @@ - (void)openWorktreeHoldingRef:(PBGitRef *)ref
777795
if (!worktreePath) return;
778796

779797
PBGitWorktree *worktree = [self.repository worktreeHoldingRef:ref];
798+
if (worktree.hasBrokenLink) {
799+
[self repairWorktreeLinks:nil];
800+
return;
801+
}
802+
780803
if (worktree && ![[NSFileManager defaultManager] fileExistsAtPath:worktreePath]) {
781804
[self showMissingFolderOfWorktree:worktree];
782805
return;
@@ -849,6 +872,167 @@ - (void)locateFolderOfWorktree:(PBGitWorktree *)worktree
849872
}];
850873
}
851874

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

8931077
- (IBAction)pruneWorktrees:(id)sender
8941078
{
1079+
for (PBGitWorktree *worktree in self.repository.worktrees) {
1080+
if (!worktree.movedPath)
1081+
continue;
1082+
1083+
[self repairWorktreeLinks:sender];
1084+
return;
1085+
}
1086+
8951087
NSError *error = nil;
8961088
NSString *report = [self.repository worktreePruneReportWithError:&error];
8971089
if (!report) {

‎Classes/git/PBGitBinary.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#define PBGitWorktreeRemoveVersion "2.17"
1616
#define PBGitWorktreeRepairVersion "2.29"
1717
#define PBGitWorktreeStateVersion "2.31"
18+
#define PBGitWorktreeLinkStyleVersion "2.48"
1819

1920
@interface PBGitBinary : NSObject
2021

‎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)