@joberthel/worktree 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,255 @@
1
+ import { access, lstat, mkdir, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { configPath, loadConfig } from '../config/load.js';
4
+ import { cloneNamedVolumes, composeFilesForWorktree, discoverComposeSource, overridePath, prepareVolumeCopy, repositoryIdentifier, resolveSourceVolumes, worktreeResourceName, writeVolumeOverride } from '../docker/compose.js';
5
+ import { git, refExists, repositoryInfo, resolveExistingBranch, resolveWorktreeDirectory } from '../git/repository.js';
6
+ import { StateStore } from '../state/store.js';
7
+ import { copyConfiguredPaths } from './copy-paths.js';
8
+ import { startWithHooks, validateSourceHooks, validateWorktreeHooks } from './hooks.js';
9
+ import { checkInterrupted, withoutOperationSignal } from './process.js';
10
+ import { runStep } from './progress.js';
11
+ const namePattern = /^\w[\w.-]*(?:\/\w[\w.-]*)*$/;
12
+ export function validateCreateInput(name, options) {
13
+ if (!namePattern.test(name))
14
+ throw new Error('Name must be a slash-separated path of letters, digits, dots, underscores, or hyphens.');
15
+ if (name.split('/').some(segment => segment.includes('..') || segment.endsWith('.') || segment.endsWith('.lock')))
16
+ throw new Error('Name segments must not contain .. or end with . or .lock.');
17
+ if (options.branch !== undefined && options.from !== undefined)
18
+ throw new Error('--branch and --from cannot be used together.');
19
+ }
20
+ export async function createEnvironment(name, options, cwd, progress) {
21
+ return withCreateContext(name, options, cwd, progress, async (repository, store, loaded) => createEnvironmentLocked(name, options, repository, store, { ...loaded, progress }));
22
+ }
23
+ /**
24
+ * Validates the input, locks the repository that contains `cwd`, loads its
25
+ * configuration, and runs `create` while the lock is held.
26
+ */
27
+ export async function withCreateContext(name, options, cwd, progress, create) {
28
+ validateCreateInput(name, options);
29
+ const repository = await runStep(progress, 'Locating Git repository', async () => repositoryInfo(cwd));
30
+ const store = new StateStore(repository.gitCommonDir);
31
+ const unlock = await store.lock('repository');
32
+ try {
33
+ return await create(repository, store, await loadCreateConfig(repository, progress));
34
+ }
35
+ finally {
36
+ await unlock();
37
+ }
38
+ }
39
+ export async function loadCreateConfig({ root, repositoryRoot }, progress) {
40
+ const configurationPath = (await configPath(root, repositoryRoot)) ?? null;
41
+ const config = await runStep(progress, configurationPath !== null
42
+ ? `Loading ${configurationPath}`
43
+ : 'No .wt.yml found, using defaults', async () => loadConfig(root, configurationPath));
44
+ return { config, configurationPath };
45
+ }
46
+ /**
47
+ * Creates the worktree and its Docker environment while the repository lock
48
+ * is held. A detached environment checks out `options.from` without creating
49
+ * a branch. A nested checkout is added inside it before its hooks run.
50
+ */
51
+ export async function createEnvironmentLocked(name, options, { root, gitCommonDir, repositoryRoot }, store, { config, configurationPath, nested, progress }) {
52
+ const source = await runStep(progress, 'Inspecting running Docker Compose project', async () => discoverComposeSource(root));
53
+ const { directory, target, repoId, projectName } = await planTarget(name, config, gitCommonDir, repositoryRoot);
54
+ await validateTarget(gitCommonDir, target, name, projectName, await store.list());
55
+ for (const path of config.copy)
56
+ await access(resolve(root, path));
57
+ await validateSourceHooks(config.hooks, root);
58
+ const { branch, revision, args: add } = await worktreeAdd(name, options, root, target, progress);
59
+ const attachment = await nested?.planned(target);
60
+ await validateHookRevision(config, root, revision);
61
+ const sources = await resolveSourceVolumes(source.project, root, source.files, source.sourceVolumes);
62
+ const image = Object.keys(sources).length
63
+ ? await prepareVolumeCopy(root)
64
+ : '';
65
+ await mkdir(directory, { recursive: true });
66
+ const state = {
67
+ schemaVersion: 1,
68
+ repositoryId: repoId,
69
+ repositoryRoot,
70
+ name,
71
+ path: target,
72
+ branch,
73
+ sourceWorktreePath: root,
74
+ sourceProject: source.project,
75
+ configurationPath,
76
+ composeFiles: source.files,
77
+ overridePath: overridePath(gitCommonDir, name),
78
+ projectName,
79
+ volumes: {},
80
+ attachment,
81
+ status: 'creating',
82
+ };
83
+ let worktreeMade = false;
84
+ try {
85
+ await runStep(progress, `Creating Git worktree ${name}`, async () => git(add, root));
86
+ worktreeMade = true;
87
+ await store.save(state);
88
+ if (config.copy.length > 0)
89
+ await runStep(progress, 'Copying configured files', async () => copyConfiguredPaths(root, target, config.copy));
90
+ await nested?.checkedOut(target);
91
+ const targetComposeFiles = await composeFilesForWorktree(source.files, source.workingDir, target);
92
+ await validateWorktreeHooks(config.hooks, target);
93
+ state.volumes = await runStep(progress, 'Cloning named Docker volumes (live writes may cause inconsistent data)', async () => cloneNamedVolumes(sources, state, root, image, async (_volume, volumes) => {
94
+ state.volumes = volumes;
95
+ await store.save(state);
96
+ }));
97
+ await writeVolumeOverride(state.overridePath, state.volumes);
98
+ const environment = {
99
+ ...state,
100
+ targetComposeFiles,
101
+ sourceComposeFiles: [
102
+ ...source.files,
103
+ ...(source.sourceOverride !== undefined
104
+ ? [source.sourceOverride]
105
+ : []),
106
+ ],
107
+ };
108
+ await startWithHooks(config.hooks, environment, progress, nested?.layers(environment));
109
+ await store.save({ ...state, status: 'ready' });
110
+ return { path: target, projectName };
111
+ }
112
+ catch (error) {
113
+ if (worktreeMade || await isRegistered(target, root)) {
114
+ await store.save({ ...state, status: 'failed', error: error.message });
115
+ const retry = nested?.retryName ?? name;
116
+ throw new Error(`${error.message}\nRun wt reset ${retry} to retry setup or wt rm ${retry} to discard the worktree.`, { cause: error });
117
+ }
118
+ throw error;
119
+ }
120
+ }
121
+ async function planTarget(name, config, gitCommonDir, repositoryRoot) {
122
+ const resourceName = worktreeResourceName(name);
123
+ if (!resourceName)
124
+ throw new Error('Worktree name must contain a letter, digit, or underscore.');
125
+ const directory = await canonicalDirectory(resolveWorktreeDirectory(config.worktrees.directory, repositoryRoot));
126
+ const repoId = repositoryIdentifier(gitCommonDir, repositoryRoot);
127
+ return {
128
+ directory,
129
+ target: resolve(directory, resourceName),
130
+ repoId,
131
+ projectName: `wt-${repoId}-${resourceName}`,
132
+ };
133
+ }
134
+ async function isRegistered(target, root) {
135
+ const registered = await withoutOperationSignal(async () => git([
136
+ 'worktree',
137
+ 'list',
138
+ '--porcelain',
139
+ '-z',
140
+ ], root)).catch(() => '');
141
+ return registered.split('\0').includes(`worktree ${target}`);
142
+ }
143
+ async function validateTarget(gitCommonDir, target, name, projectName, existingStates) {
144
+ const gitRelative = relative(gitCommonDir, target);
145
+ if ((!isAbsolute(gitRelative) && gitRelative !== '..' && !gitRelative.startsWith(`..${sep}`)) || target.split(sep).some(part => part.toLowerCase() === '.git'))
146
+ throw new Error(`Target is inside a Git directory: ${target}`);
147
+ if (existingStates.some(item => item.name.toLowerCase() === name.toLowerCase()))
148
+ throw new Error(`Worktree ${name} is already managed.`);
149
+ for (const item of existingStates) {
150
+ const path = await realpath(item.path).catch(() => resolve(item.path));
151
+ if (path === target || item.projectName === projectName)
152
+ throw new Error(`Worktree ${name} collides with managed worktree ${item.name}.`);
153
+ if (target.startsWith(`${path}${sep}`))
154
+ throw new Error(`Target is inside managed worktree ${item.name}.`);
155
+ }
156
+ try {
157
+ await lstat(target);
158
+ throw new Error(`Target already exists: ${target}`);
159
+ }
160
+ catch (error) {
161
+ if (error.code !== 'ENOENT')
162
+ throw error;
163
+ }
164
+ }
165
+ async function worktreeAdd(name, options, root, target, progress) {
166
+ const existingWorktrees = await git([
167
+ 'worktree',
168
+ 'list',
169
+ '--porcelain',
170
+ '-z',
171
+ ], root);
172
+ if (existingWorktrees.split('\0').includes(`worktree ${target}`))
173
+ throw new Error(`A Git worktree already exists at ${target}.`);
174
+ const plan = await planCheckout(name, options, root, progress);
175
+ return {
176
+ ...plan,
177
+ args: plan.args(target),
178
+ };
179
+ }
180
+ /**
181
+ * Resolves the branch and start point of a new worktree and checks that the
182
+ * branch can be created. Returns the `git worktree add` arguments for a target
183
+ * directory. A detached checkout uses `--from` or HEAD and creates no branch.
184
+ */
185
+ export async function planCheckout(name, options, root, progress) {
186
+ if (options.detach === true) {
187
+ const commit = await git([
188
+ 'rev-parse',
189
+ '--verify',
190
+ '--end-of-options',
191
+ `${options.from ?? 'HEAD'}^{commit}`,
192
+ ], root);
193
+ return {
194
+ branch: '',
195
+ revision: commit,
196
+ args: (target) => [
197
+ 'worktree',
198
+ 'add',
199
+ '--detach',
200
+ '--',
201
+ target,
202
+ commit,
203
+ ],
204
+ };
205
+ }
206
+ const existing = options.branch === undefined
207
+ ? undefined
208
+ : await runStep(progress, `Resolving branch ${options.branch}`, async () => resolveExistingBranch(options.branch, root));
209
+ const branch = existing?.branch ?? name;
210
+ if (existing === undefined && await refExists(`refs/heads/${branch}`, root))
211
+ throw new Error(`Branch ${branch} already exists; use --branch ${branch}.`);
212
+ const startPoint = existing === undefined
213
+ ? await git([
214
+ 'rev-parse',
215
+ '--verify',
216
+ '--end-of-options',
217
+ `${options.from ?? 'HEAD'}^{commit}`,
218
+ ], root)
219
+ : existing.track;
220
+ const args = (target) => {
221
+ const add = ['worktree', 'add'];
222
+ if (startPoint !== undefined) {
223
+ if (existing !== undefined)
224
+ add.push('--track');
225
+ add.push('-b', branch);
226
+ }
227
+ add.push('--', target, startPoint ?? branch);
228
+ return add;
229
+ };
230
+ return { branch, revision: startPoint ?? `refs/heads/${branch}`, args };
231
+ }
232
+ export async function validateHookRevision(config, root, revision) {
233
+ for (const phase of ['before_create', 'after_create']) {
234
+ const hook = config.hooks.worktree?.[phase];
235
+ if (typeof hook === 'string' && !config.copy.some(path => hook === path || hook.startsWith(`${path}/`))) {
236
+ try {
237
+ await git(['cat-file', '-e', `${revision}:${hook}`], root);
238
+ }
239
+ catch (error) {
240
+ checkInterrupted();
241
+ throw new Error(`hooks.worktree.${phase}: ${hook} is missing in the selected Git revision. Commit the executable script or include it in copy.`, { cause: error });
242
+ }
243
+ }
244
+ }
245
+ }
246
+ async function canonicalDirectory(path) {
247
+ try {
248
+ return await realpath(path);
249
+ }
250
+ catch (error) {
251
+ if (error.code !== 'ENOENT')
252
+ throw error;
253
+ return resolve(await canonicalDirectory(resolve(path, '..')), relative(resolve(path, '..'), path));
254
+ }
255
+ }
@@ -0,0 +1,113 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, stat } from 'node:fs/promises';
3
+ import { delimiter, resolve } from 'node:path';
4
+ import process from 'node:process';
5
+ import { runCompose, worktreeResourceName } from '../docker/compose.js';
6
+ import { gitEnvironment } from '../git/repository.js';
7
+ import { run } from './process.js';
8
+ import { hookLabel, outputReporter, runStep } from './progress.js';
9
+ export async function validateHook(hook, root, setting = 'Hook script') {
10
+ if (typeof hook !== 'string')
11
+ return;
12
+ try {
13
+ const file = resolve(root, hook);
14
+ if (!(await stat(file)).isFile())
15
+ throw new Error('Expected an executable file.');
16
+ await access(file, constants.X_OK);
17
+ }
18
+ catch (error) {
19
+ throw new Error(`${setting}: ${hook} is missing or not executable in ${root}. Commit the executable script or include it in copy.`, { cause: error });
20
+ }
21
+ }
22
+ export async function validateSourceHooks(hooks, sourcePath) {
23
+ for (const phase of ['before_create', 'after_create']) {
24
+ const hook = hooks.source?.[phase];
25
+ if (hook !== undefined)
26
+ await validateHook(hook, sourcePath, `hooks.source.${phase}`);
27
+ }
28
+ }
29
+ export async function validateWorktreeHooks(hooks, root, directoryForPath = (_path) => root) {
30
+ for (const phase of ['before_create', 'after_create']) {
31
+ const hook = hooks.worktree?.[phase];
32
+ if (typeof hook === 'string')
33
+ await validateHook(hook, directoryForPath(hook), `hooks.worktree.${phase}`);
34
+ }
35
+ }
36
+ export async function runHook(hook, cwd, env, onOutput) {
37
+ const command = typeof hook === 'string'
38
+ ? resolve(cwd, hook)
39
+ : '/bin/sh';
40
+ const args = typeof hook === 'string'
41
+ ? []
42
+ : ['-c', hook.script];
43
+ return run(command, args, cwd, { env, onOutput });
44
+ }
45
+ /**
46
+ * Runs the hooks configured for one phase of creating or resetting an
47
+ * environment. Source hooks wrap worktree hooks: they run first before
48
+ * Compose startup and last after it. `COMPOSE_PROJECT_NAME` follows the
49
+ * directory a hook runs in, so plain `docker compose` commands address the
50
+ * Compose project that lives there.
51
+ */
52
+ export async function runCreateHooks(phase, hooks, environment, progress, scope) {
53
+ const separator = process.env.COMPOSE_PATH_SEPARATOR ?? delimiter;
54
+ const targetFiles = [...environment.targetComposeFiles, environment.overridePath].join(separator);
55
+ const sourceFiles = environment.sourceComposeFiles.join(separator);
56
+ const shared = {
57
+ ...gitEnvironment(),
58
+ WORKTREE_NAME: worktreeResourceName(environment.name),
59
+ WORKTREE_ORIGINAL_NAME: environment.name,
60
+ WORKTREE_BRANCH: environment.branch,
61
+ WORKTREE_COMPOSE_FILE: targetFiles,
62
+ SOURCE_COMPOSE_FILE: sourceFiles,
63
+ WORKTREE_PATH: environment.path,
64
+ WORKTREE_COMPOSE_PROJECT_NAME: environment.projectName,
65
+ SOURCE_WORKTREE_PATH: environment.sourceWorktreePath,
66
+ SOURCE_COMPOSE_PROJECT_NAME: environment.sourceProject,
67
+ ...environment.variables,
68
+ };
69
+ const steps = [
70
+ {
71
+ name: `source.${phase}`,
72
+ hook: hooks.source?.[phase],
73
+ cwd: environment.sourceWorktreePath,
74
+ project: environment.sourceProject,
75
+ files: sourceFiles,
76
+ },
77
+ {
78
+ name: `worktree.${phase}`,
79
+ hook: hooks.worktree?.[phase],
80
+ cwd: environment.path,
81
+ project: environment.projectName,
82
+ files: targetFiles,
83
+ },
84
+ ];
85
+ for (const { name, hook, cwd, project, files } of phase === 'before_create'
86
+ ? steps
87
+ : [...steps].reverse()) {
88
+ if (hook === undefined)
89
+ continue;
90
+ const label = hookLabel(name, hook, scope);
91
+ const env = { ...shared, COMPOSE_PROJECT_NAME: project, COMPOSE_FILE: files };
92
+ await runStep(progress, label, async () => runHook(hook, cwd, env, outputReporter(progress, label)));
93
+ }
94
+ }
95
+ /**
96
+ * Runs the before hooks, starts the environment, and runs the after hooks.
97
+ * Nested layers run after the environment's own hooks in both phases, so
98
+ * their after hooks see a fully prepared environment.
99
+ */
100
+ export async function startWithHooks(hooks, environment, progress, nested = []) {
101
+ const layers = [
102
+ { hooks, environment },
103
+ ...nested,
104
+ ];
105
+ for (const layer of layers)
106
+ await runCreateHooks('before_create', layer.hooks, layer.environment, progress, layer.scope);
107
+ const label = 'Starting Docker Compose services';
108
+ await runStep(progress, label, async () => runCompose(environment, environment.targetComposeFiles, ['up', '-d'], {
109
+ onOutput: outputReporter(progress, label),
110
+ }));
111
+ for (const layer of layers)
112
+ await runCreateHooks('after_create', layer.hooks, layer.environment, progress, layer.scope);
113
+ }