@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.
- package/LICENSE +21 -0
- package/README.md +315 -2
- package/dist/cli-spec.js +138 -0
- package/dist/cli.js +264 -0
- package/dist/completion.js +178 -0
- package/dist/config/load.js +46 -0
- package/dist/config/schema.js +57 -0
- package/dist/docker/compose.js +253 -0
- package/dist/git/repository.js +196 -0
- package/dist/operations/attached.js +294 -0
- package/dist/operations/commands.js +158 -0
- package/dist/operations/confirmation.js +15 -0
- package/dist/operations/copy-paths.js +109 -0
- package/dist/operations/create.js +255 -0
- package/dist/operations/hooks.js +113 -0
- package/dist/operations/manage.js +446 -0
- package/dist/operations/manage.test/fixture.js +67 -0
- package/dist/operations/process.js +122 -0
- package/dist/operations/progress.js +28 -0
- package/dist/state/atomic-file.js +14 -0
- package/dist/state/store.js +162 -0
- package/dist/ui/confirmation-prompt.js +48 -0
- package/dist/ui/environment-info.js +85 -0
- package/dist/ui/environment-table.js +43 -0
- package/dist/ui/format-status.js +29 -0
- package/dist/ui/hook-log-panel.js +57 -0
- package/dist/ui/json-output.js +41 -0
- package/dist/ui/operation-view.js +33 -0
- package/dist/ui/progress-state.js +111 -0
- package/dist/ui/progress.js +16 -0
- package/dist/ui/show-operation.js +56 -0
- package/dist/ui/use-progress.js +34 -0
- package/package.json +72 -3
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { access, realpath } from 'node:fs/promises';
|
|
3
|
+
import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import process from 'node:process';
|
|
5
|
+
import { repositoryInfo } from '../git/repository.js';
|
|
6
|
+
import { run } from '../operations/process.js';
|
|
7
|
+
import { writeAtomicFile } from '../state/atomic-file.js';
|
|
8
|
+
import { StateStore } from '../state/store.js';
|
|
9
|
+
export async function docker(args, cwd, { project, timeout } = {}) {
|
|
10
|
+
return run('docker', args, cwd, {
|
|
11
|
+
env: project !== undefined
|
|
12
|
+
? { ...process.env, COMPOSE_PROJECT_NAME: project }
|
|
13
|
+
: process.env,
|
|
14
|
+
timeout,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export async function composeFilesForWorktree(files, sourceWorktree, targetWorktree) {
|
|
18
|
+
const sourceRoot = await realpath(sourceWorktree).catch(() => resolve(sourceWorktree));
|
|
19
|
+
return Promise.all(files.map(async (file) => {
|
|
20
|
+
const canonicalFile = await realpath(file).catch(() => resolve(file));
|
|
21
|
+
const relativeFile = relative(sourceRoot, canonicalFile);
|
|
22
|
+
if (relativeFile === '..' || relativeFile.startsWith(`..${sep}`) || isAbsolute(relativeFile))
|
|
23
|
+
return file;
|
|
24
|
+
const targetFile = resolve(targetWorktree, relativeFile);
|
|
25
|
+
try {
|
|
26
|
+
await access(targetFile);
|
|
27
|
+
return targetFile;
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error.code === 'ENOENT')
|
|
31
|
+
return file;
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
export async function discoverComposeSource(worktree) {
|
|
37
|
+
const expectedWorkingDir = await realpath(worktree).catch(() => resolve(worktree));
|
|
38
|
+
const repository = await repositoryInfo(worktree).catch(() => undefined);
|
|
39
|
+
const managedStates = repository
|
|
40
|
+
? await new StateStore(repository.gitCommonDir).list()
|
|
41
|
+
: [];
|
|
42
|
+
const projects = new Map();
|
|
43
|
+
const paths = new Map();
|
|
44
|
+
for (const [project, labeledDirectory, labeledFiles] of await composeContainerLabels(worktree)) {
|
|
45
|
+
if (!project || !labeledDirectory)
|
|
46
|
+
continue;
|
|
47
|
+
const canonicalDirectory = paths.get(labeledDirectory) ?? await realpath(labeledDirectory).catch(() => resolve(labeledDirectory));
|
|
48
|
+
paths.set(labeledDirectory, canonicalDirectory);
|
|
49
|
+
if (canonicalDirectory !== expectedWorkingDir)
|
|
50
|
+
continue;
|
|
51
|
+
const managed = managedStates.find(state => state.projectName === project);
|
|
52
|
+
if (repository !== undefined && managed === undefined && labeledFiles.split(',').some(path => resolve(path).startsWith(`${join(repository.gitCommonDir, 'wt')}${sep}`)))
|
|
53
|
+
throw new Error(`Compose project ${project} uses a wt volume override but its state is unavailable. Restore the source state before cloning.`);
|
|
54
|
+
const files = managed
|
|
55
|
+
? await composeFilesForWorktree(managed.composeFiles, managed.sourceWorktreePath, managed.path)
|
|
56
|
+
: labeledFiles.split(',').filter(Boolean);
|
|
57
|
+
const previous = projects.get(project);
|
|
58
|
+
if (previous && JSON.stringify(previous.files) !== JSON.stringify(files))
|
|
59
|
+
throw new Error(`Compose containers for ${project} disagree about their config files. Recreate the source services with the intended file list.`);
|
|
60
|
+
projects.set(project, {
|
|
61
|
+
project,
|
|
62
|
+
workingDir: expectedWorkingDir,
|
|
63
|
+
files,
|
|
64
|
+
sourceVolumes: managed?.volumes,
|
|
65
|
+
sourceOverride: managed?.overridePath,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return singleComposeSource(projects);
|
|
69
|
+
}
|
|
70
|
+
async function composeContainerLabels(worktree) {
|
|
71
|
+
const label = (key) => `{{json (.Label "com.docker.compose.project${key}")}}`;
|
|
72
|
+
const rows = await docker([
|
|
73
|
+
'ps',
|
|
74
|
+
'-a',
|
|
75
|
+
'--filter',
|
|
76
|
+
'label=com.docker.compose.project.working_dir',
|
|
77
|
+
'--format',
|
|
78
|
+
[
|
|
79
|
+
label(''),
|
|
80
|
+
label('.working_dir'),
|
|
81
|
+
label('.config_files'),
|
|
82
|
+
].join('\t'),
|
|
83
|
+
], worktree);
|
|
84
|
+
return rows.split('\n').filter(Boolean).map(row => row.split('\t').map(field => JSON.parse(field)));
|
|
85
|
+
}
|
|
86
|
+
function singleComposeSource(projects) {
|
|
87
|
+
if (projects.size !== 1)
|
|
88
|
+
throw new Error(projects.size ? 'Multiple Compose projects match this worktree; stop or disambiguate them.' : 'No Compose project found for this worktree. Start it with the Git checkout root as the Compose project directory.');
|
|
89
|
+
const [source] = projects.values();
|
|
90
|
+
if (source.files.length === 0)
|
|
91
|
+
throw new Error(`No Compose config files found for project ${source.project}.`);
|
|
92
|
+
return source;
|
|
93
|
+
}
|
|
94
|
+
export function isExternalComposeVolume(volume) {
|
|
95
|
+
if (typeof volume !== 'object' || volume === null)
|
|
96
|
+
return false;
|
|
97
|
+
return volume.external === true || typeof volume.external === 'object';
|
|
98
|
+
}
|
|
99
|
+
export async function resolveSourceVolumes(project, cwd, files, managedVolumes = {}, required = {}) {
|
|
100
|
+
const config = JSON.parse(await docker(composeArgs(files, undefined, project, cwd, [
|
|
101
|
+
'config',
|
|
102
|
+
'--format',
|
|
103
|
+
'json',
|
|
104
|
+
]), cwd, { project }));
|
|
105
|
+
const listed = await docker([
|
|
106
|
+
'volume',
|
|
107
|
+
'ls',
|
|
108
|
+
'--filter',
|
|
109
|
+
`label=com.docker.compose.project=${project}`,
|
|
110
|
+
'--format',
|
|
111
|
+
'{{.Name}}',
|
|
112
|
+
], cwd);
|
|
113
|
+
const available = new Set(listed.split('\n'));
|
|
114
|
+
const volumes = new Map();
|
|
115
|
+
const missing = new Set(Object.keys(required));
|
|
116
|
+
for (const [logical, definition] of Object.entries(config.volumes ?? {})) {
|
|
117
|
+
if (isExternalComposeVolume(definition))
|
|
118
|
+
continue;
|
|
119
|
+
const managed = Object.hasOwn(managedVolumes, logical)
|
|
120
|
+
? managedVolumes[logical]
|
|
121
|
+
: undefined;
|
|
122
|
+
const candidate = managed ?? definition.name;
|
|
123
|
+
if (candidate !== undefined && (managed !== undefined || available.has(candidate))) {
|
|
124
|
+
try {
|
|
125
|
+
await docker(['volume', 'inspect', candidate], cwd);
|
|
126
|
+
volumes.set(logical, candidate);
|
|
127
|
+
missing.delete(logical);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (!/no such volume/i.test(error.message))
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
missing.add(logical);
|
|
136
|
+
}
|
|
137
|
+
if (missing.size > 0)
|
|
138
|
+
throw new Error(`Source project ${project} is missing volume data for: ${[...missing].join(', ')}. Restore the source volumes before retrying.`);
|
|
139
|
+
return Object.fromEntries(volumes);
|
|
140
|
+
}
|
|
141
|
+
const defaultCopyImage = 'debian:trixie-slim@sha256:8aa5a7bf5a1955bddbe7d74fcdd0b91ab30e74362a8b73af672b0481b35b44a0';
|
|
142
|
+
export async function prepareVolumeCopy(cwd) {
|
|
143
|
+
const image = process.env.WT_VOLUME_COPY_IMAGE ?? defaultCopyImage;
|
|
144
|
+
try {
|
|
145
|
+
await docker(['image', 'inspect', image], cwd);
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
if (!/no such image/i.test(error.message))
|
|
149
|
+
throw error;
|
|
150
|
+
await docker(['pull', image], cwd);
|
|
151
|
+
}
|
|
152
|
+
return image;
|
|
153
|
+
}
|
|
154
|
+
export async function cloneNamedVolumes(sources, owner, cwd, image, onVolume) {
|
|
155
|
+
const { repositoryId: repoId, name } = owner;
|
|
156
|
+
const mapping = new Map();
|
|
157
|
+
for (const [logicalName, source] of Object.entries(sources)) {
|
|
158
|
+
const target = `wt-${repoId}-${worktreeResourceName(name)}-${randomUUID()}`;
|
|
159
|
+
mapping.set(logicalName, target);
|
|
160
|
+
await onVolume(target, Object.fromEntries(mapping));
|
|
161
|
+
const sourceBefore = await docker([
|
|
162
|
+
'volume',
|
|
163
|
+
'inspect',
|
|
164
|
+
'--format',
|
|
165
|
+
'{{json .}}',
|
|
166
|
+
source,
|
|
167
|
+
], cwd);
|
|
168
|
+
await docker([
|
|
169
|
+
'volume',
|
|
170
|
+
'create',
|
|
171
|
+
'--label',
|
|
172
|
+
`com.wt.repository=${repoId}`,
|
|
173
|
+
'--label',
|
|
174
|
+
`com.wt.worktree=${name}`,
|
|
175
|
+
target,
|
|
176
|
+
], cwd);
|
|
177
|
+
const targetLabelsRaw = await docker([
|
|
178
|
+
'volume',
|
|
179
|
+
'inspect',
|
|
180
|
+
'--format',
|
|
181
|
+
'{{json .Labels}}',
|
|
182
|
+
target,
|
|
183
|
+
], cwd);
|
|
184
|
+
const targetLabels = JSON.parse(targetLabelsRaw || 'null');
|
|
185
|
+
if (targetLabels?.['com.wt.repository'] !== repoId || targetLabels['com.wt.worktree'] !== name)
|
|
186
|
+
throw new Error(`Refusing to clone data into volume ${target}: ownership labels do not match this repository and worktree.`);
|
|
187
|
+
await docker([
|
|
188
|
+
'run',
|
|
189
|
+
'--rm',
|
|
190
|
+
'-v',
|
|
191
|
+
`${source}:/src:ro`,
|
|
192
|
+
'-v',
|
|
193
|
+
`${target}:/dst`,
|
|
194
|
+
image,
|
|
195
|
+
'bash',
|
|
196
|
+
'-c',
|
|
197
|
+
'set -o pipefail; tar --sparse --xattrs --acls -C /src -cf - . | tar --xattrs --xattrs-include="*" --acls --numeric-owner -C /dst -xpf -',
|
|
198
|
+
], cwd);
|
|
199
|
+
const sourceAfter = await docker([
|
|
200
|
+
'volume',
|
|
201
|
+
'inspect',
|
|
202
|
+
'--format',
|
|
203
|
+
'{{json .}}',
|
|
204
|
+
source,
|
|
205
|
+
], cwd);
|
|
206
|
+
if (sourceBefore !== sourceAfter)
|
|
207
|
+
throw new Error(`Source volume ${source} changed during the copy. Retry once it is stable.`);
|
|
208
|
+
}
|
|
209
|
+
return Object.fromEntries(mapping);
|
|
210
|
+
}
|
|
211
|
+
export function composeArgs(files, override, project, worktree, args) {
|
|
212
|
+
return [
|
|
213
|
+
'compose',
|
|
214
|
+
'--project-directory',
|
|
215
|
+
worktree,
|
|
216
|
+
...files.flatMap(file => ['-f', file]),
|
|
217
|
+
...(override !== undefined
|
|
218
|
+
? ['-f', override]
|
|
219
|
+
: []),
|
|
220
|
+
'-p',
|
|
221
|
+
project,
|
|
222
|
+
...args,
|
|
223
|
+
];
|
|
224
|
+
}
|
|
225
|
+
export async function runCompose(state, files, args, options = {}) {
|
|
226
|
+
const { cwd = state.path, ...output } = options;
|
|
227
|
+
return run('docker', composeArgs(files, state.overridePath, state.projectName, state.path, args), cwd, {
|
|
228
|
+
...output,
|
|
229
|
+
env: { ...process.env, COMPOSE_PROJECT_NAME: state.projectName },
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
export async function writeVolumeOverride(path, volumes) {
|
|
233
|
+
const entries = Object.entries(volumes).map(([key, name]) => ` ${JSON.stringify(key)}: !override\n external: true\n name: ${JSON.stringify(name)}`).join('\n');
|
|
234
|
+
await writeAtomicFile(path, entries
|
|
235
|
+
? `volumes:\n${entries}\n`
|
|
236
|
+
: 'volumes: {}\n');
|
|
237
|
+
}
|
|
238
|
+
export function repositoryIdentifier(gitCommonDir, repositoryRoot = gitCommonDir) {
|
|
239
|
+
const identity = gitCommonDir === join(repositoryRoot, '.git')
|
|
240
|
+
? repositoryRoot
|
|
241
|
+
: gitCommonDir;
|
|
242
|
+
const slug = basename(identity).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 24);
|
|
243
|
+
return `${slug}-${createHash('sha256').update(identity).digest('hex').slice(0, 8)}`;
|
|
244
|
+
}
|
|
245
|
+
export function worktreeResourceName(name) {
|
|
246
|
+
return name.toLowerCase()
|
|
247
|
+
.replaceAll('/', '--')
|
|
248
|
+
.replace(/[^a-z0-9_-]+/g, '-')
|
|
249
|
+
.replace(/^-+|-+$/g, '');
|
|
250
|
+
}
|
|
251
|
+
export function overridePath(gitCommonDir, name) {
|
|
252
|
+
return join(gitCommonDir, 'wt', `${encodeURIComponent(name)}.compose.yml`);
|
|
253
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { realpath } from 'node:fs/promises';
|
|
2
|
+
import { dirname, isAbsolute, resolve } from 'node:path';
|
|
3
|
+
import process from 'node:process';
|
|
4
|
+
import { checkInterrupted, run } from '../operations/process.js';
|
|
5
|
+
import { StateStore } from '../state/store.js';
|
|
6
|
+
const gitLocalVariables = [
|
|
7
|
+
'GIT_ALTERNATE_OBJECT_DIRECTORIES',
|
|
8
|
+
'GIT_CONFIG',
|
|
9
|
+
'GIT_CONFIG_PARAMETERS',
|
|
10
|
+
'GIT_CONFIG_COUNT',
|
|
11
|
+
'GIT_OBJECT_DIRECTORY',
|
|
12
|
+
'GIT_DIR',
|
|
13
|
+
'GIT_WORK_TREE',
|
|
14
|
+
'GIT_IMPLICIT_WORK_TREE',
|
|
15
|
+
'GIT_GRAFT_FILE',
|
|
16
|
+
'GIT_INDEX_FILE',
|
|
17
|
+
'GIT_NO_REPLACE_OBJECTS',
|
|
18
|
+
'GIT_REPLACE_REF_BASE',
|
|
19
|
+
'GIT_PREFIX',
|
|
20
|
+
'GIT_INTERNAL_SUPER_PREFIX',
|
|
21
|
+
'GIT_SHALLOW_FILE',
|
|
22
|
+
'GIT_COMMON_DIR',
|
|
23
|
+
];
|
|
24
|
+
export function gitEnvironment() {
|
|
25
|
+
const env = { ...process.env };
|
|
26
|
+
for (const variable of gitLocalVariables)
|
|
27
|
+
delete env[variable];
|
|
28
|
+
return env;
|
|
29
|
+
}
|
|
30
|
+
export async function git(args, cwd) {
|
|
31
|
+
return run('git', args, cwd, {
|
|
32
|
+
env: gitEnvironment(),
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/** Local branches and remote-tracking branches, without the `<remote>/HEAD` aliases. */
|
|
36
|
+
export async function listBranches(cwd) {
|
|
37
|
+
const refs = await git([
|
|
38
|
+
'for-each-ref',
|
|
39
|
+
'--format=%(refname)',
|
|
40
|
+
'refs/heads',
|
|
41
|
+
'refs/remotes',
|
|
42
|
+
], cwd);
|
|
43
|
+
return refs.split('\n')
|
|
44
|
+
.filter(ref => ref !== '' && !ref.endsWith('/HEAD'))
|
|
45
|
+
.map(ref => ref.replace(/^refs\/(?:heads|remotes)\//, ''));
|
|
46
|
+
}
|
|
47
|
+
export async function repositoryInfo(cwd) {
|
|
48
|
+
const common = await git(['rev-parse', '--git-common-dir'], cwd).catch((error) => {
|
|
49
|
+
if (error instanceof Error && /not a git repository/i.test(error.message))
|
|
50
|
+
throw new Error('Run wt from a Git checkout or its repository directory.', { cause: error });
|
|
51
|
+
throw error;
|
|
52
|
+
});
|
|
53
|
+
const gitCommonDir = isAbsolute(common)
|
|
54
|
+
? await realpath(common)
|
|
55
|
+
: await realpath(resolve(cwd, common));
|
|
56
|
+
const worktrees = await git([
|
|
57
|
+
'worktree',
|
|
58
|
+
'list',
|
|
59
|
+
'--porcelain',
|
|
60
|
+
'-z',
|
|
61
|
+
], cwd);
|
|
62
|
+
const [main, kind] = worktrees.split('\0');
|
|
63
|
+
const root = await git(['rev-parse', '--show-toplevel'], cwd).then(async (path) => realpath(path), (error) => {
|
|
64
|
+
if (kind === 'bare')
|
|
65
|
+
return gitCommonDir;
|
|
66
|
+
throw error;
|
|
67
|
+
});
|
|
68
|
+
return {
|
|
69
|
+
root,
|
|
70
|
+
gitCommonDir,
|
|
71
|
+
repositoryRoot: kind === 'bare'
|
|
72
|
+
? dirname(gitCommonDir)
|
|
73
|
+
: await mainCheckout(root, gitCommonDir, main.slice('worktree '.length)),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
async function mainCheckout(root, common, listedPath) {
|
|
77
|
+
// Git derives the listed main path from the common directory, which exists.
|
|
78
|
+
const listed = await realpath(listedPath);
|
|
79
|
+
if (listed !== common)
|
|
80
|
+
return listed;
|
|
81
|
+
// Git can list the metadata directory in place of a checkout with a .git file.
|
|
82
|
+
const gitDir = await realpath(await git(['rev-parse', '--absolute-git-dir'], root));
|
|
83
|
+
if (gitDir === common)
|
|
84
|
+
return root;
|
|
85
|
+
const configured = await git([
|
|
86
|
+
'--git-dir',
|
|
87
|
+
common,
|
|
88
|
+
'config',
|
|
89
|
+
'--local',
|
|
90
|
+
'--get',
|
|
91
|
+
'core.worktree',
|
|
92
|
+
], root).catch(() => '');
|
|
93
|
+
if (configured)
|
|
94
|
+
return realpath(resolve(common, configured));
|
|
95
|
+
// A separate Git directory may have no backlink to its original checkout.
|
|
96
|
+
const states = await new StateStore(common).list();
|
|
97
|
+
return states.find(state => state.repositoryRoot !== undefined)?.repositoryRoot ?? root;
|
|
98
|
+
}
|
|
99
|
+
export async function refExists(ref, cwd) {
|
|
100
|
+
return git(['show-ref', '--verify', '--quiet', ref], cwd).then(() => true, () => false);
|
|
101
|
+
}
|
|
102
|
+
function remoteOptions() {
|
|
103
|
+
return {
|
|
104
|
+
timeout: 15000,
|
|
105
|
+
env: {
|
|
106
|
+
...gitEnvironment(),
|
|
107
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
108
|
+
GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? (process.env.GIT_SSH !== undefined
|
|
109
|
+
? undefined
|
|
110
|
+
: 'ssh -oBatchMode=yes'),
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
async function remoteBranchTip({ remote, branch }, cwd) {
|
|
115
|
+
try {
|
|
116
|
+
const output = await run('git', [
|
|
117
|
+
'ls-remote',
|
|
118
|
+
'--exit-code',
|
|
119
|
+
'--heads',
|
|
120
|
+
remote,
|
|
121
|
+
`refs/heads/${branch}`,
|
|
122
|
+
], cwd, remoteOptions());
|
|
123
|
+
return output.split(/\s+/)[0];
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
checkInterrupted();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async function fetchRemoteBranch({ remote, branch }, tip, cwd) {
|
|
130
|
+
const tracked = `refs/remotes/${remote}/${branch}`;
|
|
131
|
+
const refspecs = (await git(['config', '--get-all', `remote.${remote}.fetch`], cwd).catch(() => '')).split('\n');
|
|
132
|
+
const shallow = await git(['rev-parse', '--is-shallow-repository'], cwd) === 'true';
|
|
133
|
+
const tipPresent = await git(['cat-file', '-e', `${tip}^{commit}`], cwd).then(() => true, () => false);
|
|
134
|
+
// Fetch the requested ref without moving shallow boundaries for other refs.
|
|
135
|
+
// An unknown tip may require additional history, which Git negotiates normally.
|
|
136
|
+
if (!shallow || !tipPresent) {
|
|
137
|
+
await run('git', [
|
|
138
|
+
'fetch',
|
|
139
|
+
'--no-tags',
|
|
140
|
+
remote,
|
|
141
|
+
`+refs/heads/${branch}:${tracked}`,
|
|
142
|
+
], cwd, remoteOptions());
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
await git(['update-ref', tracked, tip], cwd);
|
|
146
|
+
}
|
|
147
|
+
if (!refspecs.some(refspec => refspec.endsWith(`refs/heads/*:refs/remotes/${remote}/*`) || refspec.endsWith(`refs/heads/${branch}:${tracked}`))) {
|
|
148
|
+
await git([
|
|
149
|
+
'remote',
|
|
150
|
+
'set-branches',
|
|
151
|
+
'--add',
|
|
152
|
+
remote,
|
|
153
|
+
branch,
|
|
154
|
+
], cwd);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Resolves the value of `--branch` to a local branch. Accepts a local branch,
|
|
159
|
+
* a remote branch such as `origin/feature`, or a bare name that exists on
|
|
160
|
+
* exactly one remote. Branches that are not fetched yet are looked up on the
|
|
161
|
+
* remotes and fetched.
|
|
162
|
+
*/
|
|
163
|
+
export async function resolveExistingBranch(name, cwd) {
|
|
164
|
+
if (await refExists(`refs/heads/${name}`, cwd))
|
|
165
|
+
return { branch: name };
|
|
166
|
+
const remotes = (await git(['remote'], cwd)).split('\n').filter(Boolean);
|
|
167
|
+
const explicit = remotes.filter(remote => name.startsWith(`${remote}/`)).map(remote => ({
|
|
168
|
+
remote,
|
|
169
|
+
branch: name.slice(remote.length + 1),
|
|
170
|
+
}));
|
|
171
|
+
const bare = remotes.map(remote => ({ remote, branch: name }));
|
|
172
|
+
for (const candidates of [explicit, bare]) {
|
|
173
|
+
const matches = await Promise.all(candidates.map(async (candidate) => {
|
|
174
|
+
const tracked = await refExists(`refs/remotes/${candidate.remote}/${candidate.branch}`, cwd);
|
|
175
|
+
const tip = tracked
|
|
176
|
+
? undefined
|
|
177
|
+
: await remoteBranchTip(candidate, cwd);
|
|
178
|
+
return { candidate, tracked, tip };
|
|
179
|
+
}));
|
|
180
|
+
const found = matches.filter(match => match.tracked || match.tip !== undefined);
|
|
181
|
+
if (found.length > 1)
|
|
182
|
+
throw new Error(`Branch ${name} exists on several remotes; use --branch with one of ${found.map(({ candidate }) => `${candidate.remote}/${candidate.branch}`).join(', ')}.`);
|
|
183
|
+
if (found.length === 1) {
|
|
184
|
+
const [{ candidate, tip }] = found;
|
|
185
|
+
if (tip !== undefined)
|
|
186
|
+
await fetchRemoteBranch(candidate, tip, cwd);
|
|
187
|
+
return await refExists(`refs/heads/${candidate.branch}`, cwd)
|
|
188
|
+
? { branch: candidate.branch }
|
|
189
|
+
: { branch: candidate.branch, track: `refs/remotes/${candidate.remote}/${candidate.branch}` };
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
throw new Error(`Branch ${name} was not found locally or on a reachable remote.`);
|
|
193
|
+
}
|
|
194
|
+
export function resolveWorktreeDirectory(directory, repositoryRoot) {
|
|
195
|
+
return resolve(repositoryRoot, directory);
|
|
196
|
+
}
|