Skip to content

Commit a921dbd

Browse files
authored
Merge pull request #656 from goneng/worktree-lookup-off-the-draw-path
Stop the worktree lookup stalling the history while it draws
2 parents 50803f9 + 2b3f451 commit a921dbd

2 files changed

Lines changed: 207 additions & 7 deletions

File tree

‎Classes/git/PBGitRepository.m‎

Lines changed: 83 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,13 @@ @interface PBGitRepository () {
4242

4343
@property (nonatomic, strong) NSNumber *hasSVNRepoConfig;
4444
@property (nonatomic, strong) NSDictionary<NSString *, NSString *> *worktreePathsByRefName;
45+
@property (nonatomic, assign) BOOL worktreeLookupInFlight;
46+
@property (nonatomic, assign) BOOL worktreePathsNeedRefresh;
47+
48+
- (void)reloadWorktreePaths;
49+
- (void)startWorktreeLookupIfIdle;
50+
- (NSDictionary<NSString *, NSString *> *)readWorktreePathsExcluding:(NSString *)ourPath;
51+
- (void)takeWorktreePaths:(NSDictionary<NSString *, NSString *> *)paths;
4552

4653
@end
4754

@@ -223,7 +230,7 @@ - (void)reloadRefs
223230
// clear out ref caches
224231
_headRef = nil;
225232
_headOID = nil;
226-
self.worktreePathsByRefName = nil;
233+
[self reloadWorktreePaths];
227234
self->refs = [NSMutableDictionary dictionary];
228235

229236
NSError *error = nil;
@@ -305,21 +312,90 @@ + (BOOL)worktreeAtPath:(NSString *)path isTheOneAt:(NSString *)ourPath
305312
return paths;
306313
}
307314

315+
// Read by -drawLabelAtIndex: and by the sidebar's cell, so it answers from the
316+
// snapshot alone. Never nil: -refNamesHeldByOtherWorktrees feeds an array
317+
// literal.
308318
- (NSDictionary<NSString *, NSString *> *)worktreePathsByRefName
309319
{
310-
if (_worktreePathsByRefName)
311-
return _worktreePathsByRefName;
320+
return _worktreePathsByRefName ?: @{};
321+
}
312322

313-
if (![PBGitBinary path].length)
314-
return @{};
323+
// -reloadRefs is called from -haveRefsBeenModified, which the history list
324+
// polls, so this only marks the snapshot stale. Starting a git process per call
325+
// would spawn one per poll.
326+
- (void)reloadWorktreePaths
327+
{
328+
// -reloadRefs runs on the history list's operation, so the flags below are
329+
// only ever touched on the main queue.
330+
if (![NSThread isMainThread]) {
331+
__weak typeof(self) weakSelf = self;
332+
dispatch_async(dispatch_get_main_queue(), ^{
333+
[weakSelf reloadWorktreePaths];
334+
});
335+
return;
336+
}
337+
338+
self.worktreePathsNeedRefresh = YES;
339+
340+
[self startWorktreeLookupIfIdle];
341+
}
342+
343+
- (void)startWorktreeLookupIfIdle
344+
{
345+
if (self.worktreeLookupInFlight || !self.worktreePathsNeedRefresh)
346+
return;
347+
348+
if (![PBGitBinary path].length) {
349+
self.worktreePathsNeedRefresh = NO;
350+
[self takeWorktreePaths:@{}];
351+
return;
352+
}
353+
354+
self.worktreeLookupInFlight = YES;
355+
self.worktreePathsNeedRefresh = NO;
315356

357+
NSString *ourPath = self.workingDirectory;
358+
__weak typeof(self) weakSelf = self;
359+
360+
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
361+
PBGitRepository *repository = weakSelf;
362+
if (!repository)
363+
return;
364+
365+
NSDictionary *paths = [repository readWorktreePathsExcluding:ourPath];
366+
367+
dispatch_async(dispatch_get_main_queue(), ^{
368+
PBGitRepository *mainRepository = weakSelf;
369+
if (!mainRepository)
370+
return;
371+
372+
mainRepository.worktreeLookupInFlight = NO;
373+
[mainRepository takeWorktreePaths:paths];
374+
[mainRepository startWorktreeLookupIfIdle];
375+
});
376+
});
377+
}
378+
379+
- (NSDictionary<NSString *, NSString *> *)readWorktreePathsExcluding:(NSString *)ourPath
380+
{
316381
NSString *output = [self outputOfTaskWithArguments:@[ @"worktree", @"list", @"--porcelain" ] error:NULL];
317382
if (!output)
318383
return @{};
319384

320-
_worktreePathsByRefName = [PBGitRepository worktreePathsFromPorcelain:output excludingWorktreeAtPath:self.workingDirectory];
385+
return [PBGitRepository worktreePathsFromPorcelain:output excludingWorktreeAtPath:ourPath];
386+
}
387+
388+
// The refs observers rearrange the history and reload the sidebar, so a reload
389+
// that found the same worktrees as last time says nothing.
390+
- (void)takeWorktreePaths:(NSDictionary<NSString *, NSString *> *)paths
391+
{
392+
if ([self.worktreePathsByRefName isEqualToDictionary:paths])
393+
return;
394+
395+
self.worktreePathsByRefName = paths;
321396

322-
return _worktreePathsByRefName;
397+
[self willChangeValueForKey:@"refs"];
398+
[self didChangeValueForKey:@"refs"];
323399
}
324400

325401
- (NSString *)pathOfWorktreeHoldingRef:(PBGitRef *)ref

‎GitXTests/PBGitRepositoryWorktreeTests.m‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
// test names both rather than launching git for them.
1212
@interface PBGitRepository (WorktreeTesting)
1313
+ (NSDictionary<NSString *, NSString *> *)worktreePathsFromPorcelain:(NSString *)output excludingWorktreeAtPath:(NSString *)ourPath;
14+
- (void)takeWorktreePaths:(NSDictionary<NSString *, NSString *> *)paths;
15+
- (void)reloadWorktreePaths;
16+
- (NSDictionary<NSString *, NSString *> *)readWorktreePathsExcluding:(NSString *)ourPath;
1417
@end
1518

1619
// What `git worktree list --porcelain` prints for a repository whose own
@@ -34,6 +37,52 @@ @interface PBGitRepository (WorktreeTesting)
3437
@"branch refs/heads/locked_work\n"
3538
@"locked\n";
3639

40+
// Counts what the history and sidebar controllers would act on: both observe
41+
// "refs", and answer by rearranging the history or reloading the sidebar.
42+
@interface PBRefsChangeCounter : NSObject
43+
@property (nonatomic, assign) NSUInteger count;
44+
@end
45+
46+
@implementation PBRefsChangeCounter
47+
48+
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
49+
{
50+
self.count++;
51+
}
52+
53+
@end
54+
55+
// Stands in for the git process: counts how many times the lookup actually
56+
// runs, and holds the first one open so a burst of reloads lands while it is
57+
// still in flight.
58+
@interface PBCountingWorktreeRepository : PBGitRepository
59+
@property (nonatomic, assign) NSUInteger reads;
60+
@property (nonatomic, strong) dispatch_semaphore_t held;
61+
@end
62+
63+
@implementation PBCountingWorktreeRepository
64+
65+
- (NSDictionary<NSString *, NSString *> *)readWorktreePathsExcluding:(NSString *)ourPath
66+
{
67+
@synchronized(self) {
68+
self.reads++;
69+
}
70+
71+
if (self.held)
72+
dispatch_semaphore_wait(self.held, DISPATCH_TIME_FOREVER);
73+
74+
return @{};
75+
}
76+
77+
- (NSUInteger)readsSoFar
78+
{
79+
@synchronized(self) {
80+
return _reads;
81+
}
82+
}
83+
84+
@end
85+
3786
@interface PBGitRepositoryWorktreeTests : XCTestCase
3887
@property (nonatomic, strong) PBGitRepository *repository;
3988
@end
@@ -164,4 +213,79 @@ - (void)testRemovingABranchHeldElsewhereIsRefusedBeforeGitRuns
164213
XCTAssertTrue([error.localizedFailureReason containsString:@"/repos/gitx-feature"], @"%@", error.localizedFailureReason);
165214
}
166215

216+
217+
#pragma mark The snapshot is read while drawing and refreshed away from it
218+
219+
// -drawLabelAtIndex: and the sidebar's cell read this while drawing, and
220+
// -refNamesHeldByOtherWorktrees feeds an array literal, where a nil would
221+
// raise rather than draw nothing.
222+
- (void)testARepositoryThatHasReadNoWorktreesYetStillAnswers
223+
{
224+
PBGitRepository *repository = [[PBGitRepository alloc] init];
225+
226+
XCTAssertNotNil([repository valueForKey:@"worktreePathsByRefName"]);
227+
XCTAssertNotNil([repository refNamesHeldByOtherWorktrees]);
228+
XCTAssertFalse([repository isRefHeldByAnotherWorktree:[PBGitRef refFromString:@"refs/heads/feature"]]);
229+
}
230+
231+
- (NSUInteger)refsChangesTaking:(NSDictionary *)paths after:(NSDictionary *)previous
232+
{
233+
[self.repository takeWorktreePaths:previous];
234+
235+
PBRefsChangeCounter *counter = [[PBRefsChangeCounter alloc] init];
236+
[self.repository addObserver:counter forKeyPath:@"refs" options:0 context:NULL];
237+
[self.repository takeWorktreePaths:paths];
238+
[self.repository removeObserver:counter forKeyPath:@"refs"];
239+
240+
return counter.count;
241+
}
242+
243+
// The refs observers rearrange the history and reload the sidebar, so a reload
244+
// that found the same worktrees as last time has to stay quiet: otherwise
245+
// moving the lookup off the drawing path would cost two reloads per refresh
246+
// in place of the 9ms it saves.
247+
- (void)testFindingTheSameWorktreesAgainAnnouncesNothing
248+
{
249+
NSDictionary *paths = @{@"refs/heads/feature" : @"/repos/gitx-feature"};
250+
251+
XCTAssertEqual([self refsChangesTaking:[paths copy] after:paths], 0u,
252+
@"an unchanged snapshot must not trigger a reload");
253+
}
254+
255+
- (void)testFindingDifferentWorktreesAnnouncesTheChange
256+
{
257+
XCTAssertEqual([self refsChangesTaking:@{@"refs/heads/other" : @"/repos/gitx-other"}
258+
after:@{@"refs/heads/feature" : @"/repos/gitx-feature"}],
259+
1u, @"a snapshot that changed has to reach the labels");
260+
}
261+
262+
263+
// -reloadRefs runs on a polling path (-haveRefsBeenModified), so a burst of
264+
// reloads must not each start their own git process. One runs, and at most one
265+
// more is queued behind it however many times the poll fires.
266+
- (void)testABurstOfReloadsRunsTheLookupOnce
267+
{
268+
PBCountingWorktreeRepository *repository = [[PBCountingWorktreeRepository alloc] init];
269+
repository.held = dispatch_semaphore_create(0);
270+
271+
for (NSUInteger reload = 0; reload < 5; reload++)
272+
[repository reloadWorktreePaths];
273+
274+
NSDate *limit = [NSDate dateWithTimeIntervalSinceNow:2];
275+
while ([repository readsSoFar] == 0 && [limit timeIntervalSinceNow] > 0)
276+
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
277+
278+
XCTAssertEqual([repository readsSoFar], 1u, @"five reloads must not start five git processes");
279+
280+
dispatch_semaphore_signal(repository.held);
281+
282+
limit = [NSDate dateWithTimeIntervalSinceNow:2];
283+
while ([repository readsSoFar] < 2 && [limit timeIntervalSinceNow] > 0)
284+
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
285+
286+
XCTAssertEqual([repository readsSoFar], 2u, @"the reloads that arrived mid-flight collapse into one more run");
287+
288+
dispatch_semaphore_signal(repository.held);
289+
}
290+
167291
@end

0 commit comments

Comments
 (0)