Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 188 additions & 15 deletions lib/promote_release.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,64 @@ 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 ' +
'following command in another terminal window. Alternatively, ' +
'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);
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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 });
Expand Down
14 changes: 13 additions & 1 deletion lib/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir>/.git when the directory does not exist.
}
return dotGit;
}

get ncuDir() {
Expand Down
Loading