diff --git a/lib/promote_release.js b/lib/promote_release.js
index 6dea7735..4eecb0dd 100644
--- a/lib/promote_release.js
+++ b/lib/promote_release.js
@@ -16,7 +16,7 @@ import {
updateNodeVersionForNextMajor,
updateNodeVersionForNextRelease
} from './release/utils.js';
-import { existsSync } from 'node:fs';
+import { realpathSync } from 'node:fs';
const dryRunMessage = 'You are running in dry-run mode, meaning NCU will not run ' +
'the `git push` commands, you would need to copy-paste the ' +
@@ -24,6 +24,56 @@ const dryRunMessage = 'You are running in dry-run mode, meaning NCU will not run
'pass `--run` flag to ask NCU to run the command for you ' +
'(might not work if you need to type a passphrase to push to the remote).';
+export function parseWorktreeList(output) {
+ const worktrees = [];
+ let current = null;
+
+ for (const line of output.split(/\r?\n/)) {
+ if (line === '') {
+ if (current) {
+ worktrees.push(current);
+ current = null;
+ }
+ continue;
+ }
+
+ if (line.startsWith('worktree ')) {
+ if (current) {
+ worktrees.push(current);
+ }
+ current = { path: line.slice('worktree '.length) };
+ } else if (current) {
+ if (line.startsWith('branch ')) {
+ current.branch = line.slice('branch '.length);
+ } else if (line === 'bare') {
+ current.bare = true;
+ } else if (line === 'detached') {
+ current.detached = true;
+ } else if (line === 'prunable' || line.startsWith('prunable ')) {
+ current.prunable = true;
+ } else if (line === 'locked' || line.startsWith('locked ')) {
+ current.locked = true;
+ }
+ }
+ }
+
+ if (current) {
+ worktrees.push(current);
+ }
+
+ return worktrees;
+}
+
+function normalizeWorktreePath(dirPath) {
+ let resolved;
+ try {
+ resolved = realpathSync.native(dirPath);
+ } catch {
+ resolved = path.resolve(dirPath);
+ }
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+}
+
export default class ReleasePromotion extends Session {
constructor(argv, req, cli, dir) {
super(cli, dir, null, argv);
@@ -166,22 +216,26 @@ export default class ReleasePromotion extends Session {
if (!shouldCherryPick) {
throw new Error('Aborted');
}
- const defaultBranch = await this.checkoutDefaultBranch();
+ try {
+ const defaultBranch = await this.checkoutDefaultBranch();
- for (const { releaseCommitSha, version, versionComponents } of releases) {
- await this.cherryPickReleaseCommit(releaseCommitSha, { version, versionComponents });
- }
+ for (const { releaseCommitSha, version, versionComponents } of releases) {
+ await this.cherryPickReleaseCommit(releaseCommitSha, { version, versionComponents });
+ }
- // Push to the remote the release tag(s), and default, release, and staging branches.
- await this.pushToRemote(this.upstream, defaultBranch, ...releases.flatMap(
- ({ version, versionComponents, workingOnNewReleaseCommit, tipOfStagingBranch }) => [
- `v${version}`,
- `${workingOnNewReleaseCommit}:refs/heads/v${versionComponents.major}.x`,
- `+${tipOfStagingBranch}:refs/heads/v${versionComponents.major}.x-staging`,
- ]));
+ // Push to the remote the release tag(s), and default, release, and staging branches.
+ await this.pushToRemote(this.upstream, defaultBranch, ...releases.flatMap(
+ ({ version, versionComponents, workingOnNewReleaseCommit, tipOfStagingBranch }) => [
+ `v${version}`,
+ `${workingOnNewReleaseCommit}:refs/heads/v${versionComponents.major}.x`,
+ `+${tipOfStagingBranch}:refs/heads/v${versionComponents.major}.x-staging`,
+ ]));
- // Promote and sign the release builds.
- await this.promoteAndSignRelease();
+ // Promote and sign the release builds.
+ await this.promoteAndSignRelease();
+ } finally {
+ await this.restoreWorktree();
+ }
cli.separator();
cli.ok('Release promotion(s) complete.\n');
@@ -499,8 +553,127 @@ export default class ReleasePromotion extends Session {
return tipOfStagingBranch.trim();
}
+ async findBranchWorktree(branch) {
+ const output = await forceRunAsync('git', ['worktree', 'list', '--porcelain'], {
+ captureStdout: true,
+ ignoreFailure: false
+ });
+ const ref = `refs/heads/${branch}`;
+ const entry = parseWorktreeList(output).find(
+ (worktree) => !worktree.bare && !worktree.prunable && worktree.branch === ref
+ );
+ return entry?.path ?? null;
+ }
+
+ async getCurrentWorktreeRoot() {
+ const root = await forceRunAsync('git', ['rev-parse', '--show-toplevel'], {
+ captureStdout: true,
+ ignoreFailure: false
+ });
+ return root.trim();
+ }
+
+ async restoreWorktree() {
+ const state = this._worktreeRestore;
+ if (!state) {
+ return;
+ }
+ this._worktreeRestore = null;
+
+ try {
+ if (state.hasStashed) {
+ try {
+ await forceRunAsync('git', ['stash', 'pop'], {
+ ignoreFailure: false,
+ spawnArgs: { cwd: state.worktreePath }
+ });
+ } catch {
+ this.cli.warn(
+ `Failed to pop stashed changes in \`${state.worktreePath}\`. ` +
+ 'Please run `git stash pop` there manually.'
+ );
+ }
+ }
+ } finally {
+ process.chdir(state.previousCwd);
+ this.dir = state.previousDir;
+ }
+ }
+
async checkoutDefaultBranch() {
+ const { cli } = this;
this.defaultBranch ??= await this.getDefaultBranch();
+
+ const [worktreePath, currentRoot] = await Promise.all([
+ this.findBranchWorktree(this.defaultBranch),
+ this.getCurrentWorktreeRoot()
+ ]);
+
+ if (
+ worktreePath &&
+ normalizeWorktreePath(worktreePath) !== normalizeWorktreePath(currentRoot)
+ ) {
+ const shouldSwitch = await cli.prompt(
+ `Branch \`${this.defaultBranch}\` is already checked out in worktree ` +
+ `\`${worktreePath}\`. Switch to that worktree?`,
+ { defaultAnswer: true }
+ );
+ if (!shouldSwitch) {
+ cli.warn(`Aborting release promotion; \`${this.defaultBranch}\` is checked out elsewhere`);
+ throw new Error('Aborted');
+ }
+
+ const status = await forceRunAsync('git', ['status', '--porcelain'], {
+ captureStdout: true,
+ ignoreFailure: false,
+ spawnArgs: { cwd: worktreePath }
+ });
+
+ let hasStashed = false;
+ if (status.trim()) {
+ cli.warn(`Worktree \`${worktreePath}\` has uncommitted changes.`);
+ const shouldStash = await cli.prompt(
+ `Stash uncommitted changes in \`${worktreePath}\` before continuing?`,
+ { defaultAnswer: false }
+ );
+ if (!shouldStash) {
+ cli.warn('Aborting release promotion');
+ throw new Error('Aborted');
+ }
+ const stashTip = await forceRunAsync('git', ['stash', 'list', '-1', '--format=%H'], {
+ ignoreFailure: false,
+ captureStdout: true,
+ spawnArgs: { cwd: worktreePath }
+ });
+ await forceRunAsync('git', ['stash', '--include-untracked'], {
+ ignoreFailure: false,
+ spawnArgs: { cwd: worktreePath }
+ });
+ const newStashTip = await forceRunAsync('git', ['stash', 'list', '-1', '--format=%H'], {
+ ignoreFailure: false,
+ captureStdout: true,
+ spawnArgs: { cwd: worktreePath }
+ });
+ hasStashed = newStashTip !== stashTip && Boolean(newStashTip.trim());
+ }
+
+ const previousCwd = process.cwd();
+ const previousDir = this.dir;
+ this._worktreeRestore = { previousCwd, previousDir, worktreePath, hasStashed };
+
+ try {
+ process.chdir(worktreePath);
+ this.dir = worktreePath;
+ cli.info(`Switched to worktree \`${worktreePath}\` for branch \`${this.defaultBranch}\``);
+ await this.tryResetBranch();
+ } catch (err) {
+ await this.restoreWorktree();
+ throw err;
+ }
+
+ return this.defaultBranch;
+ }
+
await forceRunAsync('git', ['checkout', this.defaultBranch], { ignoreFailure: false });
await this.tryResetBranch();
@@ -557,7 +730,7 @@ export default class ReleasePromotion extends Session {
await cli.prompt('Ready to continue?', { defaultAnswer: true });
}
- if (existsSync('.git/CHERRY_PICK_HEAD')) {
+ if (this.cherryPickInProgress()) {
cli.info('Cherry-pick is still in progress, attempting to continue it.');
await forceRunAsync('git', ['cherry-pick', ...this.gpgSign, '--continue'],
{ ignoreFailure: false });
diff --git a/lib/session.js b/lib/session.js
index cc71ba6b..0cd92815 100644
--- a/lib/session.js
+++ b/lib/session.js
@@ -47,7 +47,19 @@ export default class Session {
}
get gitDir() {
- return path.join(this.dir, '.git');
+ const dir = this.dir ?? process.cwd();
+ const dotGit = path.join(dir, '.git');
+ try {
+ if (fs.statSync(dotGit).isFile()) {
+ const match = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dotGit, 'utf8'));
+ if (match) {
+ return path.resolve(dir, match[1].trim());
+ }
+ }
+ } catch {
+ // Fall back to
/.git when the directory does not exist.
+ }
+ return dotGit;
}
get ncuDir() {
diff --git a/test/unit/promote_release.test.js b/test/unit/promote_release.test.js
index e79da5d5..ae350c32 100644
--- a/test/unit/promote_release.test.js
+++ b/test/unit/promote_release.test.js
@@ -5,7 +5,7 @@ import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
-import ReleasePromotion from '../../lib/promote_release.js';
+import ReleasePromotion, { parseWorktreeList } from '../../lib/promote_release.js';
import { updateNodeVersionForNextRelease } from '../../lib/release/utils.js';
const today = new Date().toISOString().slice(0, 10);
@@ -200,3 +200,316 @@ describe('promote_release: cherryPickReleaseCommit', { concurrency: false }, ()
fs.readFileSync('src/node_version.h', 'utf8'), nodeVersionH(28, 0, [0, 0, 0]));
});
});
+
+describe('promote_release: parseWorktreeList', () => {
+ it('parses standard, bare, detached, locked, and prunable entries', () => {
+ const output = [
+ 'worktree /repo/bare.git',
+ 'bare',
+ '',
+ 'worktree /repo/my main worktree',
+ 'HEAD 1111111111111111111111111111111111111111',
+ 'branch refs/heads/main',
+ 'locked reason here',
+ '',
+ 'worktree /repo/detached',
+ 'HEAD 2222222222222222222222222222222222222222',
+ 'detached',
+ '',
+ 'worktree /repo/gone',
+ 'HEAD 3333333333333333333333333333333333333333',
+ 'branch refs/heads/old',
+ 'prunable gitdir file points to non-existent location',
+ ''
+ ].join('\r\n');
+
+ assert.deepStrictEqual(parseWorktreeList(output), [
+ { path: '/repo/bare.git', bare: true },
+ { path: '/repo/my main worktree', branch: 'refs/heads/main', locked: true },
+ { path: '/repo/detached', detached: true },
+ { path: '/repo/gone', branch: 'refs/heads/old', prunable: true }
+ ]);
+ });
+});
+
+function gitIn(cwd, ...args) {
+ return execFileSync('git', args, {
+ cwd,
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe']
+ }).trim();
+}
+
+function worktreeRepository(t, releaseTitle) {
+ const previous = process.cwd();
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ncu-promote-worktree-'));
+ const mainDir = path.join(root, 'node-main');
+ const releaseDir = path.join(root, 'node-v27.x');
+
+ t.after(() => {
+ process.chdir(previous);
+ fs.rmSync(root, { recursive: true, force: true });
+ });
+
+ fs.mkdirSync(mainDir);
+ gitIn(mainDir, 'init', '-b', 'main');
+ gitIn(mainDir, 'config', 'user.name', 'Test User');
+ gitIn(mainDir, 'config', 'user.email', 'test@example.com');
+ gitIn(mainDir, 'config', 'commit.gpgsign', 'false');
+ gitIn(mainDir, 'config', 'core.autocrlf', 'false');
+ gitIn(mainDir, 'config', 'core.hooksPath', path.join(root, 'no-hooks'));
+ fs.mkdirSync(path.join(mainDir, 'src'));
+ fs.writeFileSync(path.join(mainDir, 'src', 'node_version.h'), nodeVersionH(27, 0, [0, 0, 0]));
+ fs.writeFileSync(path.join(mainDir, 'CHANGELOG.md'), '# Changelog\n');
+ gitIn(mainDir, 'add', '.');
+ gitIn(mainDir, 'commit', '-m', 'Initial commit');
+
+ gitIn(mainDir, 'worktree', 'add', '-b', 'v27.x', releaseDir, 'main');
+ fs.writeFileSync(path.join(releaseDir, 'src', 'node_version.h'), nodeVersionH(27, 1));
+ fs.writeFileSync(path.join(releaseDir, 'CHANGELOG.md'), `# Changelog\n\n${releaseTitle}\n`);
+ gitIn(releaseDir, 'commit', '-am', releaseTitle);
+ const releaseCommitSha = gitIn(releaseDir, 'rev-parse', 'HEAD');
+
+ return {
+ root,
+ mainDir: fs.realpathSync.native(mainDir),
+ releaseDir: fs.realpathSync.native(releaseDir),
+ releaseCommitSha
+ };
+}
+
+describe('promote_release: worktree support', { concurrency: false }, () => {
+ it('switches to default branch worktree during promote and restores cwd', async(t) => {
+ const title = `${today}, Version 27.0.0 (Current)`;
+ const { mainDir, releaseDir, releaseCommitSha } = worktreeRepository(t, title);
+ process.chdir(releaseDir);
+
+ const prompts = [];
+ let resetDir = null;
+ const { release } = releasePromotion();
+ release.defaultBranch = 'main';
+ release.dir = releaseDir;
+ release.config = { upstream: 'upstream' };
+ release.cli.ok = () => {};
+ release.cli.prompt = async(question) => {
+ prompts.push(question);
+ return true;
+ };
+ release.tryResetBranch = async() => {
+ resetDir = fs.realpathSync.native(process.cwd());
+ };
+ release.pushToRemote = async() => {};
+ release.promoteAndSignRelease = async() => {};
+
+ await release.promote([{
+ releaseCommitSha,
+ version: '27.0.0',
+ versionComponents: { major: 27, minor: 0, patch: 0 },
+ workingOnNewReleaseCommit: releaseCommitSha,
+ tipOfStagingBranch: releaseCommitSha,
+ date: today,
+ isAlpha: false,
+ isLTS: false,
+ releaseTitle: `${title}, @tester`
+ }]);
+
+ assert.strictEqual(resetDir, mainDir);
+ assert.strictEqual(fs.realpathSync.native(process.cwd()), releaseDir);
+ assert.strictEqual(release.dir, releaseDir);
+ assert.ok(prompts.some((q) => q.includes('already checked out in worktree')));
+ assert.strictEqual(gitIn(mainDir, 'log', '-1', '--format=%s'), title);
+ assert.strictEqual(
+ fs.readFileSync(path.join(mainDir, 'src', 'node_version.h'), 'utf8'),
+ nodeVersionH(27, 0, [0, 0, 0])
+ );
+ });
+
+ it('aborts without switching when user declines switching worktrees', async(t) => {
+ const title = `${today}, Version 27.0.0 (Current)`;
+ const { mainDir, releaseDir } = worktreeRepository(t, title);
+ process.chdir(releaseDir);
+
+ const { release } = releasePromotion();
+ release.defaultBranch = 'main';
+ release.dir = releaseDir;
+ release.cli.prompt = async() => false;
+ release.tryResetBranch = async() => {
+ assert.fail('tryResetBranch should not be called');
+ };
+
+ await assert.rejects(release.checkoutDefaultBranch(), /Aborted/);
+ assert.strictEqual(fs.realpathSync.native(process.cwd()), releaseDir);
+ assert.strictEqual(gitIn(mainDir, 'log', '-1', '--format=%s'), 'Initial commit');
+ });
+
+ it('aborts when target worktree has uncommitted changes and user declines stashing', async(t) => {
+ const title = `${today}, Version 27.0.0 (Current)`;
+ const { mainDir, releaseDir } = worktreeRepository(t, title);
+ fs.writeFileSync(path.join(mainDir, 'wip.txt'), 'in progress\n');
+ process.chdir(releaseDir);
+
+ const prompts = [];
+ const { release } = releasePromotion();
+ release.defaultBranch = 'main';
+ release.dir = releaseDir;
+ release.cli.prompt = async(question, opts) => {
+ prompts.push({ question, opts });
+ return prompts.length === 1;
+ };
+ release.tryResetBranch = async() => {
+ assert.fail('tryResetBranch should not be called');
+ };
+
+ await assert.rejects(release.checkoutDefaultBranch(), /Aborted/);
+ assert.strictEqual(prompts.length, 2);
+ assert.strictEqual(prompts[1].opts?.defaultAnswer, false);
+ assert.strictEqual(fs.realpathSync.native(process.cwd()), releaseDir);
+ assert.strictEqual(fs.readFileSync(path.join(mainDir, 'wip.txt'), 'utf8'), 'in progress\n');
+ });
+
+ it('stashes and restores dirty target worktree changes even on failure', async(t) => {
+ const title = `${today}, Version 27.0.0 (Current)`;
+ const { mainDir, releaseDir, releaseCommitSha } = worktreeRepository(t, title);
+ fs.writeFileSync(path.join(mainDir, 'wip.txt'), 'untracked work\n');
+ process.chdir(releaseDir);
+
+ const { release } = releasePromotion();
+ release.defaultBranch = 'main';
+ release.dir = releaseDir;
+ release.config = { upstream: 'upstream' };
+ release.cli.prompt = async() => true;
+ release.tryResetBranch = async() => {
+ assert.strictEqual(fs.existsSync(path.join(mainDir, 'wip.txt')), false);
+ };
+ release.pushToRemote = async() => {
+ throw new Error('push aborted');
+ };
+
+ await assert.rejects(release.promote([{
+ releaseCommitSha,
+ version: '27.0.0',
+ versionComponents: { major: 27, minor: 0, patch: 0 },
+ workingOnNewReleaseCommit: releaseCommitSha,
+ tipOfStagingBranch: releaseCommitSha,
+ date: today,
+ isAlpha: false,
+ isLTS: false,
+ releaseTitle: `${title}, @tester`
+ }]), /push aborted/);
+
+ assert.strictEqual(fs.realpathSync.native(process.cwd()), releaseDir);
+ assert.strictEqual(release.dir, releaseDir);
+ assert.strictEqual(fs.readFileSync(path.join(mainDir, 'wip.txt'), 'utf8'), 'untracked work\n');
+ assert.strictEqual(gitIn(mainDir, 'log', '-1', '--format=%s'), title);
+ });
+
+ it('stashes and pops target worktree changes even with a pre-existing stash', async(t) => {
+ const title = `${today}, Version 27.0.0 (Current)`;
+ const { mainDir, releaseDir, releaseCommitSha } = worktreeRepository(t, title);
+
+ // Simulate wrapStash() having already stashed changes in the starting worktree.
+ fs.writeFileSync(path.join(releaseDir, 'starting-wip.txt'), 'starting work\n');
+ gitIn(releaseDir, 'stash', '--include-untracked');
+ const preExistingStashSha = gitIn(releaseDir, 'stash', 'list', '-1', '--format=%H');
+ assert.ok(preExistingStashSha);
+
+ fs.writeFileSync(path.join(mainDir, 'main-wip.txt'), 'main work\n');
+ process.chdir(releaseDir);
+
+ const { release } = releasePromotion();
+ release.defaultBranch = 'main';
+ release.dir = releaseDir;
+ release.config = { upstream: 'upstream' };
+ release.cli.ok = () => {};
+ release.cli.prompt = async() => true;
+ release.tryResetBranch = async() => {
+ assert.strictEqual(fs.existsSync(path.join(mainDir, 'main-wip.txt')), false);
+ };
+ release.pushToRemote = async() => {};
+ release.promoteAndSignRelease = async() => {};
+
+ await release.promote([{
+ releaseCommitSha,
+ version: '27.0.0',
+ versionComponents: { major: 27, minor: 0, patch: 0 },
+ workingOnNewReleaseCommit: releaseCommitSha,
+ tipOfStagingBranch: releaseCommitSha,
+ date: today,
+ isAlpha: false,
+ isLTS: false,
+ releaseTitle: `${title}, @tester`
+ }]);
+
+ assert.strictEqual(fs.realpathSync.native(process.cwd()), releaseDir);
+ assert.strictEqual(fs.readFileSync(path.join(mainDir, 'main-wip.txt'), 'utf8'), 'main work\n');
+ assert.strictEqual(
+ gitIn(releaseDir, 'stash', 'list', '-1', '--format=%H'),
+ preExistingStashSha
+ );
+ assert.strictEqual(gitIn(mainDir, 'log', '-1', '--format=%s'), title);
+ });
+
+ it('uses normal git checkout when default branch is not in another worktree', async(t) => {
+ const title = `${today}, Version 27.0.0 (Current)`;
+ const { mainDir } = worktreeRepository(t, title);
+ // Detach mainDir and switch to another branch so main is free to check out directly.
+ gitIn(mainDir, 'checkout', '-b', 'scratch');
+ process.chdir(mainDir);
+
+ let prompted = false;
+ const { release } = releasePromotion();
+ release.defaultBranch = 'main';
+ release.dir = mainDir;
+ release.cli.prompt = async() => {
+ prompted = true;
+ return true;
+ };
+ release.tryResetBranch = async() => {};
+
+ const branch = await release.checkoutDefaultBranch();
+ assert.strictEqual(branch, 'main');
+ assert.strictEqual(prompted, false);
+ assert.strictEqual(gitIn(mainDir, 'rev-parse', '--abbrev-ref', 'HEAD'), 'main');
+ });
+
+ it('does not prompt when already in the default branch worktree', async(t) => {
+ const title = `${today}, Version 27.0.0 (Current)`;
+ const { mainDir } = worktreeRepository(t, title);
+ process.chdir(mainDir);
+
+ let prompted = false;
+ const { release } = releasePromotion();
+ release.defaultBranch = 'main';
+ release.dir = mainDir;
+ release.cli.prompt = async() => {
+ prompted = true;
+ return true;
+ };
+ release.tryResetBranch = async() => {};
+
+ const branch = await release.checkoutDefaultBranch();
+ assert.strictEqual(branch, 'main');
+ assert.strictEqual(prompted, false);
+ });
+
+ it('resolves gitDir and cherryPickInProgress inside a linked worktree', (t) => {
+ const title = `${today}, Version 27.0.0 (Current)`;
+ const { releaseDir } = worktreeRepository(t, title);
+ process.chdir(releaseDir);
+
+ const { release } = releasePromotion();
+ release.dir = releaseDir;
+
+ const expectedGitDir = fs.realpathSync.native(
+ path.resolve(releaseDir, gitIn(releaseDir, 'rev-parse', '--git-dir'))
+ );
+ assert.strictEqual(fs.realpathSync.native(release.gitDir), expectedGitDir);
+ assert.strictEqual(release.cherryPickInProgress(), false);
+
+ const cpHead = path.join(expectedGitDir, 'CHERRY_PICK_HEAD');
+ fs.writeFileSync(cpHead, `${gitIn(releaseDir, 'rev-parse', 'HEAD')}\n`);
+ assert.strictEqual(release.cherryPickInProgress(), true);
+ fs.rmSync(cpHead);
+ assert.strictEqual(release.cherryPickInProgress(), false);
+ });
+});