Skip to content

Commit 923ef8d

Browse files
kinqsradioalexr00
andauthored
Fix orphan stack worktree cleanup through macOS path aliases (#9100)
* Fix orphan stack worktree cleanup through macOS path aliases * Attestation commit * Network paths --------- Co-authored-by: Alex Ross <38270282+alexr00@users.noreply.github.com>
1 parent 5c92651 commit 923ef8d

2 files changed

Lines changed: 85 additions & 8 deletions

File tree

‎src/github/updateStackBranches.ts‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
* Licensed under the MIT License. See License.txt in the project root for license information.
44
*--------------------------------------------------------------------------------------------*/
55

6+
import { realpathSync } from 'fs';
67
import { tmpdir } from 'os';
78
import * as path from 'path';
89
import { Repository } from '../api/api';
@@ -12,14 +13,30 @@ import { generateUuid } from '../common/uuid';
1213
const STACK_WORKTREE_PREFIX = 'vscode-pr-stack-';
1314
// Worktree names record the owning process so another window's in-progress update is never removed.
1415
const STACK_WORKTREE_NAME = /^vscode-pr-stack-(?<pid>\d+)-[0-9a-f-]+$/i;
15-
// Temporary worktrees owned by updates running in this process.
16+
// Names of temporary worktrees owned by updates running in this process.
1617
const activeStackWorktrees = new Set<string>();
1718

1819
function normalizeWorktreePath(worktreePath: string): string {
1920
const resolved = path.resolve(worktreePath);
2021
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
2122
}
2223

24+
/**
25+
* Git records worktree paths with symlinks resolved (on macOS, /private/var rather than /var), so the temporary
26+
* directory is matched in both its reported and canonical forms. Paths read from the repository are never resolved,
27+
* so they cannot cause file system or network access.
28+
*/
29+
function temporaryDirectories(): Set<string> {
30+
const directory = tmpdir();
31+
const forms = [directory];
32+
try {
33+
forms.push(realpathSync.native(directory));
34+
} catch {
35+
// Match the reported form only.
36+
}
37+
return new Set(forms.map(normalizeWorktreePath));
38+
}
39+
2340
function isProcessRunning(pid: number): boolean {
2441
try {
2542
process.kill(pid, 0);
@@ -36,11 +53,12 @@ function isProcessRunning(pid: number): boolean {
3653
*/
3754
export async function removeOrphanedStackWorktrees(repository: StackGitRepository,
3855
isRunning: (pid: number) => boolean = isProcessRunning): Promise<void> {
39-
const temporaryDirectory = normalizeWorktreePath(tmpdir());
56+
const temporaryDirectoryForms = temporaryDirectories();
4057
const orphaned = (repository.state.worktrees ?? []).filter(worktree => {
41-
const pid = STACK_WORKTREE_NAME.exec(path.basename(worktree.path))?.groups?.pid;
42-
if (worktree.main || !pid || normalizeWorktreePath(path.dirname(worktree.path)) !== temporaryDirectory
43-
|| activeStackWorktrees.has(normalizeWorktreePath(worktree.path))) {
58+
const name = path.basename(worktree.path);
59+
const pid = STACK_WORKTREE_NAME.exec(name)?.groups?.pid;
60+
if (worktree.main || !pid || !temporaryDirectoryForms.has(normalizeWorktreePath(path.dirname(worktree.path)))
61+
|| activeStackWorktrees.has(name.toLowerCase())) {
4462
return false;
4563
}
4664
return Number(pid) === process.pid || !isRunning(Number(pid));
@@ -296,8 +314,9 @@ export async function updateStackBranches(
296314
const updated: number[] = [];
297315
let failure: Error | undefined;
298316
// Registered before creation so a concurrent update in this process never treats it as orphaned.
299-
const requestedWorktreePath = path.join(tmpdir(), `${STACK_WORKTREE_PREFIX}${process.pid}-${generateUuid()}`);
300-
activeStackWorktrees.add(normalizeWorktreePath(requestedWorktreePath));
317+
const requestedWorktreeName = `${STACK_WORKTREE_PREFIX}${process.pid}-${generateUuid()}`.toLowerCase();
318+
const requestedWorktreePath = path.join(tmpdir(), requestedWorktreeName);
319+
activeStackWorktrees.add(requestedWorktreeName);
301320
try {
302321
worktreePath = await repository.createWorktree({
303322
path: requestedWorktreePath,
@@ -392,7 +411,7 @@ export async function updateStackBranches(
392411
if (worktreePath) {
393412
await removeTemporaryWorktree(repository, worktreePath);
394413
}
395-
activeStackWorktrees.delete(normalizeWorktreePath(requestedWorktreePath));
414+
activeStackWorktrees.delete(requestedWorktreeName);
396415
}
397416
if (failure) {
398417
throw failure;

‎src/test/github/updateStackBranches.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
*--------------------------------------------------------------------------------------------*/
55

66
import { strict as assert } from 'assert';
7+
import { mkdtempSync, realpathSync, rmdirSync, symlinkSync, unlinkSync } from 'fs';
78
import { tmpdir } from 'os';
89
import * as path from 'path';
910
import { Uri } from 'vscode';
@@ -411,6 +412,36 @@ describe('Update pull request stack branches', function () {
411412
});
412413

413414
describe('orphaned temporary worktrees', function () {
415+
/** Points the temporary directory at an alias of the real one, as macOS does with /var and /private/var. */
416+
async function withTemporaryDirectoryAlias(run: (canonical: string) => Promise<void>): Promise<void> {
417+
const canonical = realpathSync.native(tmpdir());
418+
const directory = mkdtempSync(path.join(canonical, 'stack-path-alias-'));
419+
const alias = path.join(directory, 'temporary');
420+
const variables = ['TMPDIR', 'TMP', 'TEMP'];
421+
const saved = variables.map(name => process.env[name]);
422+
try {
423+
symlinkSync(canonical, alias, 'junction');
424+
try {
425+
for (const name of variables) {
426+
process.env[name] = alias;
427+
}
428+
assert.equal(tmpdir(), alias);
429+
await run(canonical);
430+
} finally {
431+
variables.forEach((name, index) => {
432+
if (saved[index] === undefined) {
433+
delete process.env[name];
434+
} else {
435+
process.env[name] = saved[index];
436+
}
437+
});
438+
unlinkSync(alias);
439+
}
440+
} finally {
441+
rmdirSync(directory);
442+
}
443+
}
444+
414445
const temporaryWorktree = (name: string, directory = tmpdir()) => ({
415446
// Git reports worktree paths with forward slashes on Windows.
416447
name, path: path.join(directory, name).replace(/\\/g, '/'), ref: '', main: false, detached: true,
@@ -439,6 +470,33 @@ describe('Update pull request stack branches', function () {
439470
assert.deepEqual(repository.deletedWorktrees, [exited.path]);
440471
});
441472

473+
it('recognizes an orphan when Git reports the canonical temporary directory', async function () {
474+
await withTemporaryDirectoryAlias(async canonical => {
475+
const exited = temporaryWorktree('vscode-pr-stack-111-0b9f2c4e-1a2b-4c3d-8e9f-0a1b2c3d4e5f', canonical);
476+
repository.state.worktrees!.push(
477+
exited,
478+
temporaryWorktree('vscode-pr-stack-222-5e4d3c2b-1a0f-4e9d-8c7b-6a5f4e3d2c1b', canonical),
479+
{ ...exited, main: true },
480+
temporaryWorktree('vscode-pr-stack-111-0b9f2c4e-1a2b-4c3d-8e9f-0a1b2c3d4e5f', path.join(canonical, 'nested')),
481+
);
482+
await removeOrphanedStackWorktrees(repository, pid => pid === 222);
483+
assert.deepEqual(repository.deletedWorktrees, [exited.path]);
484+
});
485+
});
486+
487+
it('keeps an active worktree when Git reports the canonical temporary directory', async function () {
488+
await withTemporaryDirectoryAlias(async canonical => {
489+
temporary.conflictingStops = 1;
490+
await updateStackBranches(repository, open, 'origin', branches, 2, () => undefined, async worktree => {
491+
repository.state.worktrees!.push(temporaryWorktree(path.basename(repository.createdWorktrees[0]), canonical));
492+
await removeOrphanedStackWorktrees(repository);
493+
assert.deepEqual(repository.deletedWorktrees, []);
494+
await worktree.rebaseContinue!();
495+
return true;
496+
});
497+
});
498+
});
499+
442500
it('keeps the worktree of an update that is waiting for conflicts to be resolved', async function () {
443501
temporary.conflictingStops = 1;
444502
let deletedWhileResolving: string[] | undefined;

0 commit comments

Comments
 (0)