Skip to content

Commit 1373d3a

Browse files
tamirdalexr00
andauthored
Batch Git config reads for branch operations (#8978)
* Read local PR config once per refresh Local PR enumeration queried all Git config for every branch. Match all requested branches in one helper-owned config read and one pass, keeping the highest finite PR number and the first match on ties. Single-branch lookups use the same helper; each enumeration reads fresh config. * Batch remaining branch config reads First-activation branch association and branch deletion still reread repository config for each branch. Read metadata once for the selected branches, and inspect deletion leftovers after each mutation phase. Only refresh the cleanup snapshot when fallback deletions are needed. Keep association cleanup before that refresh so known metadata is removed even if reading the remaining config fails. Remove the single-branch metadata API and its manager wrapper. Callers use the batch API even when they need only one branch, keeping each operation responsible for the set of branches it requests. * Match the full branch name when cleaning up Git config The config key branch.feature.preview.remote belongs to feature.preview. Matching the prefix branch.feature. when deleting feature can recreate feature unnecessarily and remove the surviving branch's remote. Use the last dot, before the variable name, to identify the complete branch section in both cleanup passes. Scan each config snapshot once for the whole batch. * Attestation commit --------- Co-authored-by: Alex Ross <38270282+alexr00@users.noreply.github.com>
1 parent 923ef8d commit 1373d3a

8 files changed

Lines changed: 165 additions & 108 deletions

‎src/github/createPRViewProvider.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -734,12 +734,17 @@ export class CreatePullRequestViewProvider extends BaseCreatePullRequestViewProv
734734
}
735735

736736
private async existingPRMessage(): Promise<string | undefined> {
737-
const [existingPR, hasUpstream] = await Promise.all([PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(this._folderRepositoryManager.repository, this.model.compareBranch), this.model.getCompareHasUpstream()]);
737+
const branchName = this.model.compareBranch;
738+
const [metadata, hasUpstream] = await Promise.all([
739+
PullRequestGitHelper.getMatchingPullRequestMetadataForBranches(this._folderRepositoryManager.repository, [branchName]),
740+
this.model.getCompareHasUpstream(),
741+
]);
742+
const existingPR = metadata.get(branchName);
738743
if (!existingPR || !hasUpstream) {
739744
return undefined;
740745
}
741746

742-
const [pr, compareBranch] = await Promise.all([this._folderRepositoryManager.resolvePullRequest(existingPR.owner, existingPR.repositoryName, existingPR.prNumber), this._folderRepositoryManager.repository.getBranch(this.model.compareBranch)]);
747+
const [pr, compareBranch] = await Promise.all([this._folderRepositoryManager.resolvePullRequest(existingPR.owner, existingPR.repositoryName, existingPR.prNumber), this._folderRepositoryManager.repository.getBranch(branchName)]);
743748
return (pr?.head?.sha === compareBranch.commit) ? vscode.l10n.t('A pull request already exists for this branch.') : undefined;
744749
}
745750

‎src/github/folderRepositoryManager.ts‎

Lines changed: 39 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1041,6 +1041,7 @@ export class FolderRepositoryManager extends Disposable {
10411041
const localBranches = (await this.repository.getRefs({ pattern: 'refs/heads/' }))
10421042
.filter(r => r.name !== undefined)
10431043
.map(r => r.name!);
1044+
const matchingMetadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranches(this.repository, localBranches);
10441045

10451046
// Chunk localBranches into chunks of 100 to avoid hitting the GitHub API rate limit
10461047
const chunkedLocalBranches: string[][] = [];
@@ -1053,10 +1054,7 @@ export class FolderRepositoryManager extends Disposable {
10531054
const models: (PullRequestModel | undefined)[] = [];
10541055
for (const chunk of chunkedLocalBranches) {
10551056
models.push(...await Promise.all(chunk.map(async localBranchName => {
1056-
const matchingPRMetadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(
1057-
this.repository,
1058-
localBranchName,
1059-
);
1057+
const matchingPRMetadata = matchingMetadata.get(localBranchName);
10601058

10611059
if (matchingPRMetadata) {
10621060
const { owner, prNumber } = matchingPRMetadata;
@@ -1102,7 +1100,7 @@ export class FolderRepositoryManager extends Disposable {
11021100
}
11031101

11041102
try {
1105-
// Only check the 3 most recently used branches to minimize API calls
1103+
// Only check the 10 most recently used branches to minimize API calls
11061104
const localBranches = (await this.repository.getRefs({
11071105
pattern: 'refs/heads/',
11081106
sort: 'committerdate',
@@ -1113,18 +1111,14 @@ export class FolderRepositoryManager extends Disposable {
11131111

11141112
Logger.debug(`Found ${localBranches.length} local branches to check`, this.id);
11151113

1114+
const matchingMetadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranches(this.repository, localBranches);
11161115
const associationResults: boolean[] = [];
11171116

1118-
// Process all branches (max 3) in parallel
1117+
// Process the selected branches in parallel
11191118
const chunkResults = await Promise.all(localBranches.map(async branchName => {
11201119
try {
11211120
// Check if this branch already has PR metadata
1122-
const existingMetadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(
1123-
this.repository,
1124-
branchName,
1125-
);
1126-
1127-
if (existingMetadata) {
1121+
if (matchingMetadata.has(branchName)) {
11281122
// Branch already has PR metadata, skip
11291123
return false;
11301124
}
@@ -2215,29 +2209,10 @@ export class FolderRepositoryManager extends Disposable {
22152209
progress.report({ message: vscode.l10n.t('Deleted {0} of {1} branches', deletedBranches, totalBranches) });
22162210
};
22172211

2218-
const deleteConfig = async (branch: string) => {
2219-
await PullRequestGitHelper.associateBaseBranchWithBranch(this.repository, branch, undefined);
2220-
await PullRequestGitHelper.associateBranchWithPullRequest(this.repository, undefined, branch);
2221-
if (this.repository.unsetConfig) {
2222-
const prefix = `branch.${branch}.`;
2223-
const remaining = (await this.repository.getConfigs()).filter(config => config.key.startsWith(prefix));
2224-
for (const config of remaining) {
2225-
try {
2226-
await this.repository.unsetConfig(config.key);
2227-
} catch (e) {
2228-
Logger.error(`Failed to remove leftover git config ${config.key}: ${e}`, this.id);
2229-
}
2230-
}
2231-
}
2232-
};
2233-
22342212
// batch deleting the branches to avoid consuming all available resources
22352213
await batchPromiseAll(picks, 5, async (pick) => {
22362214
try {
22372215
await this.repository.deleteBranch(pick.label, true);
2238-
if ((await PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(this.repository, pick.label))) {
2239-
console.log(`Branch ${pick.label} was not deleted`);
2240-
}
22412216
reportProgress();
22422217
} catch (e) {
22432218
if (typeof e.stderr === 'string' && e.stderr.includes('not found')) {
@@ -2254,27 +2229,43 @@ export class FolderRepositoryManager extends Disposable {
22542229

22552230
// Git removes the whole config section when deleting a branch, including keys with multiple values.
22562231
// Recreate deleted branches when a provider leaves config behind so Git can perform that cleanup again.
2257-
const configsAfterDeletion = await this.repository.getConfigs();
2258-
const branchesNeedingConfigCleanup = picks.filter(pick => {
2259-
const prefix = `branch.${pick.label}.`;
2260-
return configsAfterDeletion.some(config => config.key.startsWith(prefix));
2261-
});
2232+
// The last dot separates the variable name from the section; a branch name can contain dots.
2233+
const configSection = (key: string) => key.slice(0, key.lastIndexOf('.'));
2234+
const sectionsAfterDeletion = new Set((await this.repository.getConfigs()).map(({ key }) => configSection(key)));
22622235
const branchesNeedingRetry = new Set(needsRetry?.map(pick => pick.label));
2263-
for (const pick of branchesNeedingConfigCleanup) {
2264-
if (!branchesNeedingRetry.has(pick.label)) {
2265-
try {
2266-
await this.repository.createBranch(pick.label, false, 'HEAD');
2267-
await this.repository.deleteBranch(pick.label, true);
2268-
} catch (e) {
2269-
Logger.error(`Failed to remove leftover git config section for ${pick.label}: ${e}`, this.id);
2270-
}
2236+
const branchesToClean = picks.filter(pick => !branchesNeedingRetry.has(pick.label));
2237+
const sectionsNeedingCleanup = new Set<string>();
2238+
for (const { label } of branchesToClean) {
2239+
const section = `branch.${label}`;
2240+
if (!sectionsAfterDeletion.has(section)) {
2241+
continue;
2242+
}
2243+
sectionsNeedingCleanup.add(section);
2244+
try {
2245+
await this.repository.createBranch(label, false, 'HEAD');
2246+
await this.repository.deleteBranch(label, true);
2247+
} catch (e) {
2248+
Logger.error(`Failed to remove leftover git config section for ${label}: ${e}`, this.id);
22712249
}
22722250
}
22732251

2274-
// Config operations can't be parallelized. Clean up any keys left by providers that don't remove sections.
2275-
for (const pick of picks) {
2276-
if (!branchesNeedingRetry.has(pick.label)) {
2277-
await deleteConfig(pick.label);
2252+
// Clear associations serially before refreshing the remaining config.
2253+
for (const { label } of branchesToClean) {
2254+
await PullRequestGitHelper.associateBaseBranchWithBranch(this.repository, label, undefined);
2255+
await PullRequestGitHelper.associateBranchWithPullRequest(this.repository, undefined, label);
2256+
}
2257+
2258+
// Refresh after the fallback deletions, then remove remaining keys serially.
2259+
if (this.repository.unsetConfig && sectionsNeedingCleanup.size) {
2260+
for (const { key } of await this.repository.getConfigs()) {
2261+
if (!sectionsNeedingCleanup.has(configSection(key))) {
2262+
continue;
2263+
}
2264+
try {
2265+
await this.repository.unsetConfig(key);
2266+
} catch (e) {
2267+
Logger.error(`Failed to remove leftover git config ${key}: ${e}`, this.id);
2268+
}
22782269
}
22792270
}
22802271
if (needsRetry && needsRetry.length) {
@@ -2572,18 +2563,6 @@ export class FolderRepositoryManager extends Disposable {
25722563
return githubRepository?.resolveUser(login);
25732564
}
25742565

2575-
async getMatchingPullRequestMetadataForBranch() {
2576-
if (!this.repository || !this.repository.state.HEAD || !this.repository.state.HEAD.name) {
2577-
return null;
2578-
}
2579-
2580-
const matchingPullRequestMetadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(
2581-
this.repository,
2582-
this.repository.state.HEAD.name,
2583-
);
2584-
return matchingPullRequestMetadata;
2585-
}
2586-
25872566
async getMatchingPullRequestMetadataFromGitHub(branch: Branch, remoteName?: string, remoteUrl?: string, upstreamBranchName?: string): Promise<
25882567
(PullRequestMetadata & { model: PullRequestModel }) | null
25892568
> {

‎src/github/pullRequestGitHelper.ts‎

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -375,29 +375,41 @@ export class PullRequestGitHelper {
375375
return `branch.${branchName}.${PullRequestMetadataKey}`;
376376
}
377377

378-
static async getMatchingPullRequestMetadataForBranch(
378+
static async getMatchingPullRequestMetadataForBranches(
379379
repository: Repository,
380-
branchName: string,
381-
): Promise<PullRequestMetadata | undefined> {
380+
branchNames: readonly string[],
381+
): Promise<Map<string, PullRequestMetadata>> {
382+
const matchingMetadata = new Map<string, PullRequestMetadata>();
383+
if (!branchNames.length) {
384+
return matchingMetadata;
385+
}
386+
387+
let configs: { key: string; value: string }[];
382388
try {
383-
const configKey = this.getMetadataKeyForBranch(branchName);
384-
const allConfigs = await repository.getConfigs();
385-
// When the same branch name has been associated with multiple PRs over
386-
// time (resulting in duplicate config entries), prefer the most recent
387-
// association: parse the trailing PR number and sort numerically so the
388-
// highest PR number wins. Entries that fail to parse, or whose PR
389-
// number is not a finite integer (e.g. malformed config values like
390-
// `owner#repo#abc`), are filtered out so they cannot poison the sort.
391-
// Returns `undefined` when no entries parse to valid metadata.
392-
const matchingConfigs = allConfigs
393-
.filter(config => config.key === configKey)
394-
.map(config => ({ config, metadata: PullRequestGitHelper.parsePullRequestMetadata(config.value) }))
395-
.filter((entry): entry is { config: { key: string; value: string }, metadata: PullRequestMetadata } => !!entry.metadata && Number.isFinite(entry.metadata.prNumber))
396-
.sort((a, b) => b.metadata.prNumber - a.metadata.prNumber);
397-
return matchingConfigs[0]?.metadata;
389+
configs = await repository.getConfigs();
398390
} catch (_) {
399-
return;
391+
return matchingMetadata;
392+
}
393+
394+
const requestedBranches = new Map(branchNames.map(branchName => [this.getMetadataKeyForBranch(branchName), branchName]));
395+
for (const config of configs) {
396+
const branchName = requestedBranches.get(config.key);
397+
if (branchName === undefined) {
398+
continue;
399+
}
400+
401+
const metadata = this.parsePullRequestMetadata(config.value);
402+
if (!metadata || !Number.isFinite(metadata.prNumber)) {
403+
continue;
404+
}
405+
406+
// Prefer the highest PR number; retain the first entry for ties.
407+
const previous = matchingMetadata.get(branchName);
408+
if (!previous || metadata.prNumber > previous.prNumber) {
409+
matchingMetadata.set(branchName, metadata);
410+
}
400411
}
412+
return matchingMetadata;
401413
}
402414

403415
static async createRemote(repository: Repository, baseRemote: Remote, cloneUrl: Protocol) {

‎src/test/github/folderRepositoryManager.test.ts‎

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,36 @@ describe('PullRequestManager', function () {
324324
});
325325
});
326326

327+
describe('getLocalPullRequests', function () {
328+
it('reads one fresh config snapshot across branch chunks', async function () {
329+
const url = 'https://github.com/owner/repo.git';
330+
const remote = new GitHubRemote('origin', url, new Protocol(url), GitHubServerType.GitHubDotCom);
331+
const githubRepository = new GitHubRepository(1, remote, repository.rootUri, manager.credentialStore, telemetry, true);
332+
(manager as any)._githubRepositories = [githubRepository];
333+
for (let i = 0; i < 102; i++) {
334+
await repository.createBranch(`branch-${i}`, false);
335+
}
336+
await repository.setConfig('branch.branch-0.github-pr-owner-number', 'owner#repo#5');
337+
await repository.setConfig('branch.branch-101.github-pr-owner-number', 'owner#repo#7');
338+
const first = { localBranchName: undefined } as PullRequestModel;
339+
const last = { localBranchName: undefined } as PullRequestModel;
340+
const updated = { localBranchName: undefined } as PullRequestModel;
341+
const models = new Map([[5, first], [7, last], [11, updated]]);
342+
sinon.stub(githubRepository, 'getPullRequest').callsFake(async (number: number) => models.get(number));
343+
const getConfigs = sinon.spy(repository, 'getConfigs');
344+
345+
assert.deepStrictEqual(await manager.getLocalPullRequests(), [first, last]);
346+
assert.strictEqual(getConfigs.calledOnce, true);
347+
assert.strictEqual(first.localBranchName, 'branch-0');
348+
assert.strictEqual(last.localBranchName, 'branch-101');
349+
350+
await repository.setConfig('branch.branch-101.github-pr-owner-number', 'owner#repo#11');
351+
assert.deepStrictEqual(await manager.getLocalPullRequests(), [first, updated]);
352+
assert.strictEqual(getConfigs.calledTwice, true);
353+
assert.strictEqual(updated.localBranchName, 'branch-101');
354+
});
355+
});
356+
327357
describe('getPullRequestDefaults', function () {
328358
it('uses a GitHub remote when the branch tracks a local sibling branch', async function () {
329359
const url = 'https://github.com/owner/repo.git';
@@ -436,14 +466,41 @@ describe('PullRequestManager', function () {
436466
await repository.setConfig('branch.feature.github-pr-owner-number', 'owner#repo#1');
437467
repository.preserveConfigOnNextBranchDelete = true;
438468

469+
await repository.createBranch('feature.preview', false, 'commit-hash');
470+
await repository.createBranch('feature.preview.local', false, 'commit-hash');
471+
await repository.setConfig('branch.feature.preview.local.remote', 'origin');
472+
const createBranch = sinon.spy(repository, 'createBranch');
473+
const getConfigs = sinon.spy(repository, 'getConfigs');
439474
const nonExistant = new Set<string>();
440-
await (manager as any).deleteBranches([{ label: 'feature' }], nonExistant, noopProgress, 1, 0, []);
475+
await (manager as any).deleteBranches([{ label: 'feature' }, { label: 'feature.preview' }], nonExistant, noopProgress, 2, 0, []);
441476

442-
const configs = await repository.getConfigs();
443-
assert.strictEqual(configs.filter(c => c.key.startsWith('branch.feature.')).length, 0);
477+
assert.strictEqual(getConfigs.callCount, 2);
478+
assert.deepStrictEqual(createBranch.args.map(([name]) => name), ['feature']);
479+
assert.deepStrictEqual(await repository.getConfigs(), [{ key: 'branch.feature.preview.local.remote', value: 'origin' }]);
444480
assert.strictEqual(nonExistant.has('feature'), false);
445481
});
446482

483+
it('clears associations even when refreshing leftover config fails', async function () {
484+
await repository.createBranch('feature', false, 'commit-hash');
485+
await repository.setConfig('branch.feature.github-pr-base-branch', 'owner#repo#main');
486+
await repository.setConfig('branch.feature.vscode-merge-base', 'origin/main');
487+
await repository.setConfig('branch.feature.github-pr-owner-number', 'owner#repo#1');
488+
await repository.setConfig('branch.other.github-pr-owner-number', 'owner#repo#2');
489+
repository.preserveConfigOnNextBranchDelete = true;
490+
sinon.stub(repository, 'createBranch').rejects(new Error('Cannot recreate branch'));
491+
const error = new Error('Cannot read config');
492+
sinon.stub(repository, 'getConfigs').callThrough().onSecondCall().rejects(error);
493+
494+
await assert.rejects(
495+
(manager as any).deleteBranches([{ label: 'feature' }], new Set<string>(), noopProgress, 1, 0, []),
496+
error,
497+
);
498+
499+
assert.deepStrictEqual(await repository.getConfigs(), [
500+
{ key: 'branch.other.github-pr-owner-number', value: 'owner#repo#2' },
501+
]);
502+
});
503+
447504
it('removes leftover branch config for a branch that no longer exists', async function () {
448505
// The branch ref is already gone, but stale [branch "gone"] config remains.
449506
await repository.setConfig('branch.gone.remote', 'origin');

‎src/test/github/pullRequestGitHelper.test.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ describe('PullRequestGitHelper', function () {
374374
});
375375
});
376376

377-
describe('getMatchingPullRequestMetadataForBranch', function () {
377+
describe('getMatchingPullRequestMetadataForBranches', function () {
378378
it('returns the highest-numbered PR when duplicate config entries exist for the branch', async function () {
379379
// Simulate the case where a branch name has been associated with multiple
380380
// PRs over time and `git config --get-all` returns duplicate entries.
@@ -383,13 +383,14 @@ describe('PullRequestGitHelper', function () {
383383
sinon.stub(repository, 'getConfigs').resolves([
384384
{ key: 'branch.feature.github-pr-owner-number', value: 'owner#name#5' },
385385
{ key: 'branch.feature.github-pr-owner-number', value: 'owner#name#42' },
386+
{ key: 'branch.feature.github-pr-owner-number', value: 'other#name#42' },
386387
{ key: 'branch.feature.github-pr-owner-number', value: 'owner#name#17' },
387388
{ key: 'branch.other.github-pr-owner-number', value: 'owner#name#999' },
388389
]);
389390

390-
const metadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(repository, 'feature');
391+
const metadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranches(repository, ['feature']);
391392

392-
assert.deepStrictEqual(metadata, {
393+
assert.deepStrictEqual(metadata.get('feature'), {
393394
owner: 'owner',
394395
repositoryName: 'name',
395396
prNumber: 42,
@@ -406,9 +407,9 @@ describe('PullRequestGitHelper', function () {
406407
{ key: 'branch.feature.github-pr-owner-number', value: 'owner#name#7' },
407408
]);
408409

409-
const metadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(repository, 'feature');
410+
const metadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranches(repository, ['feature']);
410411

411-
assert.deepStrictEqual(metadata, {
412+
assert.deepStrictEqual(metadata.get('feature'), {
412413
owner: 'owner',
413414
repositoryName: 'name',
414415
prNumber: 7,
@@ -421,9 +422,9 @@ describe('PullRequestGitHelper', function () {
421422
{ key: 'branch.feature.github-pr-owner-number', value: 'not-valid' },
422423
]);
423424

424-
const metadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranch(repository, 'feature');
425+
const metadata = await PullRequestGitHelper.getMatchingPullRequestMetadataForBranches(repository, ['feature']);
425426

426-
assert.strictEqual(metadata, undefined);
427+
assert.strictEqual(metadata.get('feature'), undefined);
427428
});
428429
});
429430
});

‎src/test/mocks/mockRepository.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,8 @@ export class MockRepository implements Repository {
206206
if (this.preserveConfigOnNextBranchDelete) {
207207
this.preserveConfigOnNextBranchDelete = false;
208208
} else {
209-
const prefix = `branch.${name}.`;
210-
this._config = this._config.filter(config => !config.key.startsWith(prefix));
209+
const section = `branch.${name}`;
210+
this._config = this._config.filter(({ key }) => key.slice(0, key.lastIndexOf('.')) !== section);
211211
}
212212
}
213213

0 commit comments

Comments
 (0)