Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
13 changes: 11 additions & 2 deletions docs/design/2026-08-29-pnpm-worktree-bootstrap.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,17 @@ registry access only when that cache-only attempt is incomplete.
This avoids waiting for pnpm to prefetch optional binaries for other platforms
on the common warm-store path. The script sets `QWEN_SKIP_PREPARE=1` plus a
bootstrap-private notice-generation guard, keeping dependency install scripts
enabled while skipping repository build, bundle, Husky setup, and npm-layout
notice generation. Script execution does not
enabled while skipping repository build, bundle, and npm-layout notice
generation. Because `QWEN_SKIP_PREPARE=1` also suppresses the Husky step that
`scripts/prepare.js` runs for an npm install, the bootstrap installs Husky
hooks itself once the frozen install succeeds. It preserves an existing
non-default `core.hooksPath` and honours `HUSKY=0`; in a linked worktree whose
`core.hooksPath` is unset it skips Husky and reports that, since husky's
unguarded `git config` write would otherwise set the hooks path in the config
every worktree of the repository shares while creating `.husky/_` only in the
bootstrapped checkout; and it fails closed when a Husky run leaves the hooks
path unconfigured. Tree cleanliness is preserved by the `.gitignore` husky
generates inside `.husky/_`. Script execution does not
implicitly install stale dependencies; the bootstrap command is the explicit
installation boundary. Building from this pnpm layout is deferred to Stage 2.

Expand Down
71 changes: 63 additions & 8 deletions scripts/setup-worktree.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { constants as osConstants } from 'node:os';
import { delimiter, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
Expand All @@ -28,10 +28,14 @@ const env = {
// A spread of process.env is an ordinary object: on Windows the path
// variable canonically arrives as `Path`, so a case-sensitive `env.PATH`
// read misses it and corepack is never found.
function envValue(name) {
if (process.platform !== 'win32') return env[name];
const key = Object.keys(env).find((key) => key.toUpperCase() === name);
return key === undefined ? undefined : env[key];
}

function pathValue() {
if (process.platform !== 'win32') return env.PATH ?? '';
const key = Object.keys(env).find((name) => name.toUpperCase() === 'PATH');
return (key !== undefined ? env[key] : env.PATH) ?? '';
return envValue('PATH') ?? '';
}

function findOnPath(command) {
Expand Down Expand Up @@ -61,8 +65,59 @@ function runPnpm(args) {
});
}

function getHooksPath() {
const result = spawnSync('git', ['config', '--get', 'core.hooksPath'], {
cwd: rootDir,
env,
encoding: 'utf8',
});
return result.status === 0 ? result.stdout.trim() : undefined;
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
}

// Husky runs `git config core.hooksPath .husky/_` with no --worktree, so the
// value always lands in the config of the root that owns `.git` while the
// `.husky/_` wrappers are created in the working directory it was invoked from.
// Those are the same root here unless `.git` is a file, which is how git marks
// a linked worktree pointing at the primary's `.git/worktrees/<name>`.
function ownsRepositoryConfig() {
const gitEntry = statSync(resolve(rootDir, '.git'), {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
throwIfNoEntry: false,
});
return gitEntry === undefined || gitEntry.isDirectory();
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
}

function install(cacheMode) {
return runPnpm(['install', '--frozen-lockfile', cacheMode]);
const result = runPnpm(['install', '--frozen-lockfile', cacheMode]);
if (result.status === 0) {
const hooksPath = getHooksPath();
if (
envValue('HUSKY') === '0' ||
(hooksPath !== undefined && hooksPath !== '.husky/_')
) {
exitWithResult(result);
}
// With the key unset, husky's write would add it to the config shared by
// every worktree of this repository while only this checkout receives
// `.husky/_`, silently repointing hook resolution for roots that never got
// the wrappers. Leave that config alone and say so instead. `prepare.js`'s
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
// `run('husky')` needs no such guard: it installs the checkout that owns
// the config it writes.
if (hooksPath === undefined && !ownsRepositoryConfig()) {
console.log(
'worktree setup: core.hooksPath is unset and this linked worktree does ' +
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
'not own the repository config; skipping Husky so the hooks path is ' +
'not rewritten for every other worktree.',
);
exitWithResult(result);
}
const husky = runPnpm(['exec', 'husky']);
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
if (husky.status === 0 && getHooksPath() !== '.husky/_') {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
console.error('worktree setup failed: Husky did not install hooks');
process.exit(1);
}
exitWithResult(husky);
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
}
return result;
}

function exitWithResult(result) {
Expand All @@ -80,10 +135,10 @@ function exitWithResult(result) {
process.exit(result.status ?? 1);
}

// install() exits the process on every path where the install succeeded, so it
// returns only a failed result and the registry retry below is the only
// decision left for this driver to make.
const cachedInstall = install('--offline');
if (cachedInstall.status === 0) {
process.exit(0);
}

if (
cachedInstall.error ||
Expand Down
202 changes: 186 additions & 16 deletions scripts/tests/package-scripts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ import { getWorkflowJob, getWorkflowStep } from './workflow-helpers.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(__dirname, '../..');
const huskyTestEnv = {
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
HUSKY: '1',
GIT_CONFIG_COUNT: '1',
GIT_CONFIG_KEY_0: 'core.hooksPath',
GIT_CONFIG_VALUE_0: '.husky/_',
};

function readPackageJson() {
return JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
Expand Down Expand Up @@ -210,12 +216,31 @@ describe('package scripts', () => {
expect(new Set(specifiers)).toEqual(new Set(['workspace:*']));
});

it('bootstraps worktrees with frozen pnpm dependencies and skips prepare', () => {
it('bootstraps worktrees and preserves explicit hook settings', () => {
const binDir = mkdtempSync(path.join(tmpdir(), 'qwen-worktree-setup-'));
const commandDir = path.join(binDir, 'runner bin');
const logFile = path.join(binDir, 'corepack.log');
mkdirSync(commandDir);

const runSetup = (envOverride = {}) => {
writeFileSync(logFile, '');
return spawnSync(
process.execPath,
[path.join(root, 'scripts/setup-worktree.js')],
{
cwd: root,
encoding: 'utf8',
env: {
...process.env,
...huskyTestEnv,
...envOverride,
PATH: `${commandDir}${path.delimiter}${process.env.PATH ?? ''}`,
WORKTREE_SETUP_LOG: logFile,
},
},
);
};

try {
if (process.platform === 'win32') {
writeFileSync(
Expand All @@ -230,21 +255,18 @@ describe('package scripts', () => {
chmodSync(path.join(commandDir, 'corepack'), 0o755);
}

const result = spawnSync(
process.execPath,
[path.join(root, 'scripts/setup-worktree.js')],
{
cwd: root,
encoding: 'utf8',
env: {
...process.env,
PATH: `${commandDir}${path.delimiter}${process.env.PATH ?? ''}`,
WORKTREE_SETUP_LOG: logFile,
},
},
);
const result = runSetup();

expect(result.status).toBe(0);
expect(readFileSync(logFile, 'utf8').trim().split(/\r?\n/)).toEqual([
'1 1 pnpm install --frozen-lockfile --offline',
'1 1 pnpm exec husky',
]);
expect(runSetup({ HUSKY: '0' }).status).toBe(0);
expect(readFileSync(logFile, 'utf8').trim()).toBe(
'1 1 pnpm install --frozen-lockfile --offline',
);
expect(runSetup({ GIT_CONFIG_VALUE_0: '/custom/hooks' }).status).toBe(0);
expect(readFileSync(logFile, 'utf8').trim()).toBe(
'1 1 pnpm install --frozen-lockfile --offline',
);
Expand All @@ -253,6 +275,146 @@ describe('package scripts', () => {
}
});

/**
* The hook logic reads `core.hooksPath` from git and decides from `.git`
* whether this checkout owns the config that write would land in. The
* injected `GIT_CONFIG_*` constant above cannot express either: it pins the
* value for the child's whole lifetime, so the unset state — the only one
* where husky is asked to write — is unreachable from it. These cases run the
* real script against a throwaway root instead: a synthetic checkout whose
* `.git` is a file (linked worktree) or a directory (primary), plus a real
* `git init` repo the child reads and writes through `GIT_DIR`, and a stub
* husky whose write the case controls.
*/
it('installs hooks only where the checkout owns the repository config', () => {
const sandbox = mkdtempSync(path.join(tmpdir(), 'qwen-worktree-hooks-'));
const checkout = path.join(sandbox, 'checkout');
const commandDir = path.join(sandbox, 'bin');
const configRepo = path.join(sandbox, 'config-repo');
const configRepoGitDir = path.join(configRepo, '.git');
const logFile = path.join(sandbox, 'corepack.log');
const emptyConfig = path.join(sandbox, 'empty-config');

try {
mkdirSync(path.join(checkout, 'scripts'), { recursive: true });
mkdirSync(commandDir, { recursive: true });
writeFileSync(emptyConfig, '');
writeFileSync(
path.join(checkout, 'package.json'),
`${JSON.stringify({ packageManager: 'pnpm@11.24.0' }, null, 2)}\n`,
);
for (const script of ['setup-worktree.js', 'pnpm-package.js']) {
writeFileSync(
path.join(checkout, 'scripts', script),
readFileSync(path.join(root, 'scripts', script), 'utf8'),
);
}

// Stands in for husky: logs the invocation like the neighbouring stubs,
// then writes the hooks path only when the case asks it to.
const stub =
process.platform === 'win32'
? '@echo %QWEN_SKIP_PREPARE% %QWEN_SKIP_NOTICE_GENERATION% %*>>"%WORKTREE_SETUP_LOG%"\r\n@if not "%2"=="exec" exit /b 0\r\n@if not "%STUB_HUSKY_SETS_HOOKS_PATH%"=="1" exit /b 0\r\n@git config core.hooksPath .husky/_\r\n'
: '#!/bin/sh\necho "$QWEN_SKIP_PREPARE $QWEN_SKIP_NOTICE_GENERATION $*" >> "$WORKTREE_SETUP_LOG"\n[ "$2" = "exec" ] || exit 0\n[ "$STUB_HUSKY_SETS_HOOKS_PATH" = "1" ] || exit 0\ngit config core.hooksPath .husky/_\n';
writeFileSync(
path.join(
commandDir,
process.platform === 'win32' ? 'corepack.cmd' : 'corepack',
),
stub,
);
if (process.platform !== 'win32') {
chmodSync(path.join(commandDir, 'corepack'), 0o755);
}
expect(
spawnSync('git', ['init', '--quiet', configRepo], { encoding: 'utf8' })
.status,
).toBe(0);

const sharedConfigEnv = {
...process.env,
GIT_DIR: configRepoGitDir,
GIT_CONFIG_COUNT: '0',
};
const runSetup = ({ ownsConfig, stubSetsHooksPath }) => {
// `.git` as a file is how git marks a linked worktree, and the script
// only ever looks at it through `statSync`, so a stand-in is enough.
rmSync(path.join(checkout, '.git'), { recursive: true, force: true });
if (ownsConfig) {
mkdirSync(path.join(checkout, '.git'));
} else {
writeFileSync(
path.join(checkout, '.git'),
`gitdir: ${path.join(configRepoGitDir, 'worktrees', 'checkout')}\n`,
);
}
writeFileSync(logFile, '');
return spawnSync(
process.execPath,
[path.join(checkout, 'scripts', 'setup-worktree.js')],
{
cwd: checkout,
encoding: 'utf8',
env: {
...process.env,
HUSKY: '1',
STUB_HUSKY_SETS_HOOKS_PATH: stubSetsHooksPath ? '1' : '0',
PATH: `${commandDir}${path.delimiter}${process.env.PATH ?? ''}`,
WORKTREE_SETUP_LOG: logFile,
// Read the throwaway repo's config rather than the host
// checkout's, which already carries `core.hooksPath`.
GIT_DIR: configRepoGitDir,
GIT_CONFIG_COUNT: '0',
GIT_CONFIG_GLOBAL: emptyConfig,
GIT_CONFIG_SYSTEM: emptyConfig,
},
},
);
};
const sharedHooksPath = () =>
spawnSync('git', ['config', '--get', 'core.hooksPath'], {
cwd: configRepo,
encoding: 'utf8',
env: sharedConfigEnv,
}).status === 0;

// A linked worktree with the key unset must not let husky add it to the
// config every worktree of the repository shares.
const linked = runSetup({ ownsConfig: false, stubSetsHooksPath: true });
expect(linked.status).toBe(0);
expect(linked.stdout).toContain('skipping Husky');
expect(readFileSync(logFile, 'utf8').trim()).toBe(
'1 1 pnpm install --frozen-lockfile --offline',
);
expect(sharedHooksPath()).toBe(false);

// The primary checkout owns the config husky writes, so the same unset
// key installs hooks there.
const primary = runSetup({ ownsConfig: true, stubSetsHooksPath: true });
expect(primary.status).toBe(0);
expect(readFileSync(logFile, 'utf8').trim().split(/\r?\n/)).toEqual([
'1 1 pnpm install --frozen-lockfile --offline',
'1 1 pnpm exec husky',
]);
expect(sharedHooksPath()).toBe(true);

// A husky that exits 0 without configuring the hooks path fails closed
// instead of shipping a checkout with no hooks.
expect(
spawnSync('git', ['config', '--unset', 'core.hooksPath'], {
cwd: configRepo,
encoding: 'utf8',
env: sharedConfigEnv,
}).status,
).toBe(0);
const hookless = runSetup({ ownsConfig: true, stubSetsHooksPath: false });
expect(hookless.status).toBe(1);
expect(hookless.stderr).toContain('Husky did not install hooks');
} finally {
rmSync(sandbox, { recursive: true, force: true });
}
});

it.skipIf(process.platform !== 'win32')(
'resolves the path variable under its native Windows casing',
() => {
Expand All @@ -270,10 +432,16 @@ describe('package scripts', () => {
// Native shells expose the path variable as `Path`; a case-sensitive
// `env.PATH` read on the spread object would miss it and report
// Corepack unavailable.
const env = { ...process.env, WORKTREE_SETUP_LOG: logFile };
const env = {
...process.env,
...huskyTestEnv,
WORKTREE_SETUP_LOG: logFile,
};
delete env.PATH;
delete env.Path;
delete env.HUSKY;
env.Path = `${commandDir}${path.delimiter}${process.env.Path ?? process.env.PATH ?? ''}`;
env.Husky = '0';

const result = spawnSync(
process.execPath,
Expand Down Expand Up @@ -344,7 +512,8 @@ describe('package scripts', () => {
encoding: 'utf8',
env: {
...process.env,
PATH: binDir,
...huskyTestEnv,
PATH: `${binDir}${path.delimiter}${process.env.PATH ?? ''}`,
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
WORKTREE_SETUP_LOG: logFile,
},
},
Expand All @@ -354,6 +523,7 @@ describe('package scripts', () => {
expect(readFileSync(logFile, 'utf8').trim().split(/\r?\n/)).toEqual([
'1 1 pnpm install --frozen-lockfile --offline',
'1 1 pnpm install --frozen-lockfile --prefer-offline',
'1 1 pnpm exec husky',
]);
} finally {
rmSync(binDir, { recursive: true, force: true });
Expand Down
Loading