@joberthel/worktree 1.5.0 → 1.6.0

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/README.md CHANGED
@@ -64,8 +64,8 @@ wt rm feature/login
64
64
  | Command | What it does |
65
65
  | --- | --- |
66
66
  | `wt create <name> [--branch <branch> \| --from <ref>]` | Create a worktree, branch, and isolated Compose environment. |
67
- | `wt ls [--filter <key=value>...]` | List managed worktrees, their Docker status and, with OrbStack, their main URL. Filter by `name`, `branch` or `state`. |
68
- | `wt info [name]` | Show a worktree's branch, path, status, services, published ports, OrbStack domains and volumes. |
67
+ | `wt ls [--filter <key=value>...]` | List managed worktrees, their Docker status and, with OrbStack, their [main URL](docs/json-output.md#orbstack-domains). Filter by `name`, `branch` or `state`. |
68
+ | `wt info [name]` | Show a worktree's branch, path, status, services in the [order of its Compose files](docs/json-output.md#container-order), published ports, OrbStack domains and volumes. |
69
69
  | `wt path [name]` | Print the absolute path of a worktree. |
70
70
  | `wt cd [name]` | Change to a worktree's directory. Needs the [shell function](#changing-to-a-worktree). |
71
71
  | `wt start [name]` | Start its Compose services. |
@@ -134,6 +134,10 @@ npx skills add joberthel/worktree
134
134
 
135
135
  Agents work with the [JSON output](docs/json-output.md): results, published ports, dry runs of `rm` and `reset`, and errors with stable codes.
136
136
 
137
+ ### VS Code extension
138
+
139
+ The [VS Code extension](vscode/README.md) shows your environments in the Source Control view, with their state, branch, and URL. It is not on the Marketplace yet. Download the `.vsix` file of the latest `vscode-v…` [release](https://github.com/joberthel/worktree/releases) and install it with `code --install-extension <file>.vsix`.
140
+
137
141
  ## Configuration
138
142
 
139
143
  `wt` works without a configuration file. Put `.wt.yml` at the root of your checkout to copy files into new worktrees, run setup hooks, or change the worktree directory:
@@ -0,0 +1,67 @@
1
+ import { docker } from './compose.js';
2
+ import { domainsLabel, parseDomains } from './orbstack.js';
3
+ import { parsePorts } from './ports.js';
4
+ import { composeFilesFormat, parseComposeFiles, serviceOrderReader, servicePosition } from './service-order.js';
5
+ /** The `docker ps --format` columns that parseContainers reads. */
6
+ const containerFormat = [
7
+ '{{.Names}}',
8
+ '{{.Label "com.docker.compose.service"}}',
9
+ '{{.Label "com.docker.compose.container-number"}}',
10
+ '{{.Label "com.docker.compose.oneoff"}}',
11
+ composeFilesFormat,
12
+ `{{.Label "${domainsLabel}"}}`,
13
+ '{{.Ports}}',
14
+ '{{.State}}',
15
+ '{{.Status}}',
16
+ ].join('\t');
17
+ export function parseContainers(output) {
18
+ return output.split('\n').filter(Boolean).map((line) => {
19
+ const [name, service, number = '', oneOff = '', workingDir, configFiles, domains = '', ports = '', state, ...status] = line.split('\t');
20
+ return {
21
+ container: {
22
+ name,
23
+ service: service || name,
24
+ number: /^\d+$/.test(number)
25
+ ? Number(number)
26
+ : undefined,
27
+ oneOff: oneOff.toLowerCase() === 'true',
28
+ state: state ?? '',
29
+ status: status.join('\t'),
30
+ domains: parseDomains(domains),
31
+ ports: parsePorts(ports),
32
+ },
33
+ files: parseComposeFiles(workingDir, configFiles),
34
+ };
35
+ });
36
+ }
37
+ /**
38
+ * Orders containers by the position of their service in `services`, the
39
+ * order of the Compose files. Services that `services` does not name come
40
+ * last, alphabetically. The containers of a service come in container number
41
+ * order, then the one-off containers of `docker compose run`.
42
+ */
43
+ function sortContainers(rows, services) {
44
+ const position = servicePosition(services);
45
+ const number = ({ container }) => container.number ?? Number.MAX_SAFE_INTEGER;
46
+ return [...rows].sort((a, b) => position(a.container.service) - position(b.container.service)
47
+ || a.container.service.localeCompare(b.container.service)
48
+ || Number(a.container.oneOff) - Number(b.container.oneOff)
49
+ || number(a) - number(b)
50
+ || a.container.name.localeCompare(b.container.name)).map(({ container }) => container);
51
+ }
52
+ /**
53
+ * The containers of a Compose project in the order of its services in the
54
+ * Compose files that its containers were created from.
55
+ */
56
+ export async function projectContainers(project, cwd) {
57
+ const rows = parseContainers(await docker([
58
+ 'ps',
59
+ '-a',
60
+ '--filter',
61
+ `label=com.docker.compose.project=${project}`,
62
+ '--format',
63
+ containerFormat,
64
+ ], cwd));
65
+ const readServiceOrder = serviceOrderReader();
66
+ return sortContainers(rows, await readServiceOrder(rows.map(({ files }) => files)));
67
+ }
@@ -1,5 +1,6 @@
1
1
  import { run } from '../operations/process.js';
2
2
  import { docker } from './compose.js';
3
+ import { composeFilesFormat, parseComposeFiles, serviceOrderReader, servicePosition } from './service-order.js';
3
4
  /** Container label that gives a container custom OrbStack domains. */
4
5
  export const domainsLabel = 'dev.orbstack.domains';
5
6
  /**
@@ -43,33 +44,43 @@ export function containerAddresses(containers, project, { scheme }) {
43
44
  /**
44
45
  * The main URL of each Compose project: its custom domain closest to the
45
46
  * root, so `shop.orb.local` wins over `admin.shop.orb.local`. Among domains
46
- * of equal depth, the one listed first in its label wins.
47
+ * of equal depth, the one of the service that comes first in the Compose
48
+ * files wins, then the one listed first in its label. Services the files do
49
+ * not name come after the others. The files are read only when domains of
50
+ * several services tie.
47
51
  */
48
52
  export async function projectUrls(cwd) {
49
53
  const network = await orbstackNetwork(cwd);
50
54
  if (network === undefined)
51
- return () => undefined;
55
+ return async () => undefined;
52
56
  const output = await docker([
53
57
  'ps',
54
58
  '-a',
55
59
  '--filter',
56
60
  `label=${domainsLabel}`,
57
61
  '--format',
58
- `{{.Label "com.docker.compose.project"}}\t{{.Label "${domainsLabel}"}}`,
62
+ `{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}\t${composeFilesFormat}\t{{.Label "${domainsLabel}"}}`,
59
63
  ], cwd);
60
64
  const domains = new Map();
61
65
  for (const line of output.split('\n').filter(Boolean)) {
62
- const [project, label = ''] = line.split('\t');
66
+ const [project, service = '', workingDir, configFiles, label = ''] = line.split('\t');
67
+ const files = parseComposeFiles(workingDir, configFiles);
63
68
  domains.set(project, [
64
69
  ...domains.get(project) ?? [],
65
- ...parseDomains(label).map((domain, position) => ({ domain, position })),
70
+ ...parseDomains(label).map((domain, position) => ({ domain, position, service, files })),
66
71
  ]);
67
72
  }
73
+ const readServiceOrder = serviceOrderReader();
68
74
  const depth = (domain) => domain.split('.').length;
69
- return (project) => {
70
- const [main] = [
71
- ...domains.get(project) ?? [],
72
- ].sort((a, b) => depth(a.domain) - depth(b.domain) || a.position - b.position || a.domain.localeCompare(b.domain));
75
+ return async (project) => {
76
+ const candidates = domains.get(project) ?? [];
77
+ const closest = Math.min(...candidates.map(({ domain }) => depth(domain)));
78
+ const tied = candidates.filter(({ domain }) => depth(domain) === closest);
79
+ const order = new Set(tied.map(({ service }) => service)).size > 1
80
+ ? await readServiceOrder(candidates.map(({ files }) => files))
81
+ : [];
82
+ const position = servicePosition(order);
83
+ const [main] = tied.sort((a, b) => position(a.service) - position(b.service) || a.position - b.position || a.domain.localeCompare(b.domain));
73
84
  return main === undefined
74
85
  ? undefined
75
86
  : `${network.scheme}://${main.domain}`;
@@ -0,0 +1,242 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import { constants, open, stat } from 'node:fs/promises';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { isAlias, isMap, isScalar, isSeq, parseAllDocuments, visit } from 'yaml';
5
+ /** The two `docker ps --format` columns that parseComposeFiles reads. */
6
+ export const composeFilesFormat = [
7
+ '{{.Label "com.docker.compose.project.working_dir"}}',
8
+ '{{.Label "com.docker.compose.project.config_files"}}',
9
+ ].join('\t');
10
+ /** The Compose files of a container, from its `working_dir` and comma-separated `config_files` labels. */
11
+ export function parseComposeFiles(workingDir = '', configFiles = '') {
12
+ return {
13
+ workingDir,
14
+ configFiles: configFiles.split(',').filter(Boolean),
15
+ };
16
+ }
17
+ /**
18
+ * Compose files larger than this are not read, and their services count as
19
+ * not named. Real ones are much smaller, and parsing a large file takes long.
20
+ */
21
+ const maxFileSize = 1024 * 1024;
22
+ /**
23
+ * The resolver of a document's aliases. An alias refers to the last node
24
+ * with its anchor before it. One pass over the document finds them all,
25
+ * where Alias.resolve would search the whole document for every alias.
26
+ */
27
+ function aliasResolver(document) {
28
+ const anchors = new Map();
29
+ const targets = new Map();
30
+ visit(document, {
31
+ Node: (_key, node) => {
32
+ if (isAlias(node))
33
+ targets.set(node, anchors.get(node.source));
34
+ else if (node.anchor !== undefined)
35
+ anchors.set(node.anchor, node);
36
+ },
37
+ });
38
+ return node => isAlias(node)
39
+ ? targets.get(node)
40
+ : node;
41
+ }
42
+ /** The text of a scalar, also behind an alias. */
43
+ function text(node, resolved) {
44
+ const value = resolved(node);
45
+ return isScalar(value) && typeof value.value === 'string'
46
+ ? value.value
47
+ : undefined;
48
+ }
49
+ /** The texts of a scalar or of a sequence of scalars. */
50
+ function texts(node, resolved) {
51
+ const value = resolved(node);
52
+ const items = isSeq(value)
53
+ ? value.items
54
+ : [value];
55
+ return items.map(item => text(item, resolved)).filter(item => item !== undefined);
56
+ }
57
+ /**
58
+ * The keys of a mapping in document order. The keys of the mappings that it
59
+ * merges with `<<` take the place of the merge key. Each mapping counts
60
+ * once, so aliases cannot make this grow beyond the size of the file.
61
+ */
62
+ function mappingKeys(node, resolved, seen = new Set()) {
63
+ const mapping = resolved(node);
64
+ if (!isMap(mapping) || seen.has(mapping))
65
+ return [];
66
+ seen.add(mapping);
67
+ return mapping.items.flatMap(({ key, value }) => {
68
+ // With `merge: true`, the parser gives a plain `<<` key a symbol as its value.
69
+ if (isScalar(key) && typeof key.value === 'symbol') {
70
+ const merged = resolved(value);
71
+ const sources = isSeq(merged)
72
+ ? merged.items
73
+ : [merged];
74
+ return sources.flatMap(source => mappingKeys(source, resolved, seen));
75
+ }
76
+ const name = text(key, resolved);
77
+ return name === undefined
78
+ ? []
79
+ : [name];
80
+ });
81
+ }
82
+ /** An entry of `include`: a path, or a mapping with `path` and `project_directory`. */
83
+ function includeEntry(node, resolved) {
84
+ const entry = resolved(node);
85
+ const mapping = isMap(entry);
86
+ const path = mapping
87
+ ? entry.get('path', true)
88
+ : entry;
89
+ const paths = texts(path, resolved);
90
+ if (paths.length === 0)
91
+ return undefined;
92
+ return {
93
+ paths,
94
+ projectDirectory: mapping
95
+ ? text(entry.get('project_directory', true), resolved)
96
+ : undefined,
97
+ };
98
+ }
99
+ /** The entries of `include`, which is a sequence. */
100
+ function includeEntries(node, resolved) {
101
+ const entries = resolved(node);
102
+ if (!isSeq(entries))
103
+ return [];
104
+ return entries.items.map(entry => includeEntry(entry, resolved)).filter(entry => entry !== undefined);
105
+ }
106
+ /** The services and includes of a Compose document, in the order of its keys. */
107
+ function documentParts(document) {
108
+ const parts = [];
109
+ if (!isMap(document.contents))
110
+ return parts;
111
+ const resolved = aliasResolver(document);
112
+ for (const { key, value } of document.contents.items) {
113
+ const name = text(key, resolved);
114
+ if (name === 'services') {
115
+ parts.push({
116
+ services: mappingKeys(value, resolved),
117
+ });
118
+ }
119
+ if (name === 'include') {
120
+ parts.push({
121
+ includes: includeEntries(value, resolved),
122
+ });
123
+ }
124
+ }
125
+ return parts;
126
+ }
127
+ /**
128
+ * The text of a Compose file, or undefined when it is not a regular file or
129
+ * larger than maxFileSize. Only regular files are opened, because opening a
130
+ * pipe or a device can have effects, such as releasing a writer that waits
131
+ * on the pipe or resetting a board on a serial port. The opened file is
132
+ * checked again, in case it was replaced in between, and the flags keep
133
+ * such a replacement from blocking or becoming the controlling terminal. At
134
+ * most one byte more than the limit is read, also from a file that reports
135
+ * a wrong size, as those in /proc do.
136
+ */
137
+ async function readComposeFile(file) {
138
+ if (!(await stat(file)).isFile())
139
+ return undefined;
140
+ const handle = await open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOCTTY);
141
+ try {
142
+ if (!(await handle.stat()).isFile())
143
+ return undefined;
144
+ // Only the bytes read are used, so the buffer need not be zeroed.
145
+ const buffer = Buffer.allocUnsafe(maxFileSize + 1);
146
+ let length = 0;
147
+ while (length < buffer.length) {
148
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
149
+ if (bytesRead === 0)
150
+ break;
151
+ length += bytesRead;
152
+ }
153
+ return length > maxFileSize
154
+ ? undefined
155
+ : buffer.toString('utf8', 0, length);
156
+ }
157
+ finally {
158
+ await handle.close();
159
+ }
160
+ }
161
+ /**
162
+ * The parts of a Compose file and of each YAML document in it. A file that
163
+ * is missing, unreadable, not a regular file, larger than maxFileSize, or
164
+ * not valid YAML contributes nothing. Only keys are read, so the service
165
+ * definitions and their aliases are never expanded.
166
+ */
167
+ async function readParts(file) {
168
+ try {
169
+ const source = await readComposeFile(file);
170
+ if (source === undefined)
171
+ return [];
172
+ // The failsafe schema keeps keys as written, so a service named 1.0 stays
173
+ // `1.0`. Duplicate keys are not looked for: Compose rejects them itself,
174
+ // and the check takes quadratic time.
175
+ const documents = parseAllDocuments(source, { schema: 'failsafe', merge: true, uniqueKeys: false });
176
+ if (documents.some(document => document.errors.length > 0))
177
+ return [];
178
+ return documents.flatMap(documentParts);
179
+ }
180
+ catch {
181
+ return [];
182
+ }
183
+ }
184
+ /**
185
+ * Returns a function that lists the services of Compose projects in the
186
+ * order they first appear in the projects' files. It follows `include` as
187
+ * Compose does, except for paths with variables and remote includes, whose
188
+ * services it cannot know. Files it cannot read add no services. It reads
189
+ * each file at most once, so one reader serves a whole command.
190
+ */
191
+ export function serviceOrderReader() {
192
+ const files = new Map();
193
+ const parts = async (file) => {
194
+ const known = files.get(file);
195
+ if (known !== undefined)
196
+ return known;
197
+ const read = readParts(file);
198
+ files.set(file, read);
199
+ return read;
200
+ };
201
+ return async (projects) => {
202
+ const services = new Set();
203
+ const visited = new Set();
204
+ // Compose resolves `include` paths from the directory of the including
205
+ // project: the project directory for the files given with `-f`, and for
206
+ // an included file its entry's `project_directory`, by default the
207
+ // directory of the first included file.
208
+ const addFile = async (file, directory) => {
209
+ if (visited.has(file))
210
+ return;
211
+ visited.add(file);
212
+ for (const part of await parts(file)) {
213
+ if ('services' in part) {
214
+ for (const service of part.services)
215
+ services.add(service);
216
+ continue;
217
+ }
218
+ for (const { paths, projectDirectory } of part.includes) {
219
+ const included = paths.map(path => resolve(directory, path));
220
+ const context = projectDirectory === undefined
221
+ ? dirname(included[0])
222
+ : resolve(directory, projectDirectory);
223
+ for (const path of included)
224
+ await addFile(path, context);
225
+ }
226
+ }
227
+ };
228
+ for (const { workingDir, configFiles } of projects) {
229
+ for (const file of configFiles)
230
+ await addFile(resolve(workingDir, file), workingDir);
231
+ }
232
+ return [...services];
233
+ };
234
+ }
235
+ /**
236
+ * The position of a service in `order`. Services that `order` does not name
237
+ * share the position after the last one.
238
+ */
239
+ export function servicePosition(order) {
240
+ const positions = new Map(order.map((service, index) => [service, index]));
241
+ return (service) => positions.get(service) ?? order.length;
242
+ }
@@ -0,0 +1,25 @@
1
+ /*
2
+ * The state of an environment as `wt ls` shows it. The VS Code extension
3
+ * bundles this file, so both describe environments the same way.
4
+ */
5
+ const setupKinds = {
6
+ creating: 'busy',
7
+ resetting: 'busy',
8
+ removing: 'busy',
9
+ failed: 'failed',
10
+ };
11
+ const dockerKinds = {
12
+ running: 'running',
13
+ stopped: 'stopped',
14
+ finished: 'finished',
15
+ missing: 'missing',
16
+ };
17
+ /**
18
+ * The setup status until the environment is ready, then the summary of its
19
+ * containers. `running (N exited)` counts as running.
20
+ */
21
+ export function environmentState(status, dockerStatus) {
22
+ if (status !== undefined && status !== null && status !== 'ready')
23
+ return { label: status, kind: setupKinds[status] ?? 'unknown' };
24
+ return { label: dockerStatus, kind: dockerKinds[dockerStatus.split(' ')[0]] ?? 'unknown' };
25
+ }
@@ -1,4 +1,5 @@
1
1
  import { UsageError } from './cli-spec.js';
2
+ import { environmentState } from './environment-state.js';
2
3
  /*
3
4
  * Filters for `wt ls --filter key=value`, modeled on `docker ps --filter`.
4
5
  * Values of the same key match if any of them does, and different keys must
@@ -39,10 +40,7 @@ export function parseListFilter(expressions) {
39
40
  }
40
41
  /** The state shown in the STATE column: the setup state until it is ready, then the Docker state without its exited count. */
41
42
  function displayedState(item) {
42
- const status = item.status !== undefined && item.status !== 'ready'
43
- ? item.status
44
- : item.dockerStatus;
45
- return status.split(' ')[0];
43
+ return environmentState(item.status, item.dockerStatus).label.split(' ')[0];
46
44
  }
47
45
  export function matchesListFilter(item, filter) {
48
46
  const tests = {
@@ -44,10 +44,20 @@ export async function listEnvironments(cwd) {
44
44
  listedEnvironments(cwd),
45
45
  projectUrls(cwd),
46
46
  ]);
47
- return rows.map(row => ({
47
+ return Promise.all(rows.map(async (row) => ({
48
48
  ...row,
49
- url: url(row.projectName),
50
- }));
49
+ url: await url(row.projectName),
50
+ })));
51
+ }
52
+ /**
53
+ * The setup status of an attached worktree with the step and start of its
54
+ * running operation: its own until it is ready, then those of its host.
55
+ */
56
+ function setupState(state, host) {
57
+ const { status, step, startedAt } = state.status !== 'ready'
58
+ ? state
59
+ : host ?? {};
60
+ return { status, step, startedAt };
51
61
  }
52
62
  async function listedEnvironments(cwd) {
53
63
  const { gitCommonDir } = await repositoryInfo(cwd);
@@ -63,9 +73,7 @@ async function listedEnvironments(cwd) {
63
73
  name: state.name,
64
74
  branch: state.branch,
65
75
  path: state.path,
66
- status: state.status !== 'ready'
67
- ? state.status
68
- : host?.status,
76
+ ...setupState(state, host),
69
77
  projectName: host?.projectName ?? '-',
70
78
  dockerStatus: host === undefined
71
79
  ? 'missing'
@@ -142,9 +150,7 @@ export async function inspectEnvironment(name, cwd) {
142
150
  name: state.name,
143
151
  branch: state.branch,
144
152
  path: state.path,
145
- status: state.status !== 'ready'
146
- ? state.status
147
- : details.status,
153
+ ...setupState(state, details),
148
154
  error: state.error ?? details.error,
149
155
  host: { name: state.host.name, path: host?.path ?? '-' },
150
156
  };
@@ -6,8 +6,8 @@ import { createInterface } from 'node:readline/promises';
6
6
  import { isDeepStrictEqual } from 'node:util';
7
7
  import { configPath, loadConfig } from '../config/load.js';
8
8
  import { cloneNamedVolumes, composeFilesForWorktree, docker, prepareVolumeCopy, resolveSourceVolumes, runCompose, writeVolumeOverride } from '../docker/compose.js';
9
- import { containerAddresses, domainsLabel, orbstackNetwork, parseDomains } from '../docker/orbstack.js';
10
- import { parsePorts } from '../docker/ports.js';
9
+ import { projectContainers } from '../docker/containers.js';
10
+ import { containerAddresses, orbstackNetwork } from '../docker/orbstack.js';
11
11
  import { WtError } from '../errors.js';
12
12
  import { git, repositoryInfo } from '../git/repository.js';
13
13
  import { AttachedStore, StateStore } from '../state/store.js';
@@ -115,32 +115,11 @@ export async function inspectEnvironment(name, cwd) {
115
115
  const { state } = await managed(name, cwd);
116
116
  return inspectState(state, cwd);
117
117
  }
118
- export function parseContainers(output) {
119
- return output.split('\n').filter(Boolean).map((line) => {
120
- const [name, service, domains = '', ports = '', state, ...status] = line.split('\t');
121
- return {
122
- name,
123
- service: service || name,
124
- state: state ?? '',
125
- status: status.join('\t'),
126
- domains: parseDomains(domains),
127
- ports: parsePorts(ports),
128
- };
129
- }).sort((a, b) => a.service.localeCompare(b.service) || a.name.localeCompare(b.name));
130
- }
131
118
  export async function inspectState(state, cwd) {
132
- const [output, network] = await Promise.all([
133
- docker([
134
- 'ps',
135
- '-a',
136
- '--filter',
137
- `label=com.docker.compose.project=${state.projectName}`,
138
- '--format',
139
- `{{.Names}}\t{{.Label "com.docker.compose.service"}}\t{{.Label "${domainsLabel}"}}\t{{.Ports}}\t{{.State}}\t{{.Status}}`,
140
- ], cwd),
119
+ const [containers, network] = await Promise.all([
120
+ projectContainers(state.projectName, cwd),
141
121
  orbstackNetwork(cwd),
142
122
  ]);
143
- const containers = parseContainers(output);
144
123
  const addresses = network && containerAddresses(containers, state.projectName, network);
145
124
  return {
146
125
  ...state,
@@ -4,7 +4,17 @@ import { checkInterrupted } from './process.js';
4
4
  const operationProgress = new AsyncLocalStorage();
5
5
  /** Runs `operation` with `progress` as the reporter of its notes. */
6
6
  export async function withProgress(progress, operation) {
7
- return operationProgress.run(progress, operation);
7
+ return operationProgress.run({
8
+ progress,
9
+ stepListeners: new Set(),
10
+ }, operation);
11
+ }
12
+ /**
13
+ * Calls `listener` with the label of every step that starts later in the
14
+ * current operation. Outside an operation it does nothing.
15
+ */
16
+ export function onStepStarted(listener) {
17
+ operationProgress.getStore()?.stepListeners.add(listener);
8
18
  }
9
19
  /**
10
20
  * Shows a note as a finished step of the current operation, for code that is
@@ -12,7 +22,7 @@ export async function withProgress(progress, operation) {
12
22
  * note goes to stderr.
13
23
  */
14
24
  export function reportNote(label) {
15
- const progress = operationProgress.getStore();
25
+ const progress = operationProgress.getStore()?.progress;
16
26
  if (progress === undefined) {
17
27
  process.stderr.write(`${label}\n`);
18
28
  return;
@@ -23,6 +33,8 @@ export function reportNote(label) {
23
33
  export async function runStep(progress, label, operation) {
24
34
  checkInterrupted();
25
35
  progress?.({ label, status: 'started' });
36
+ for (const listener of operationProgress.getStore()?.stepListeners ?? [])
37
+ listener(label);
26
38
  try {
27
39
  const result = await operation();
28
40
  checkInterrupted();
@@ -5,6 +5,7 @@ import { setTimeout as sleep } from 'node:timers/promises';
5
5
  import { z } from 'zod';
6
6
  import { WtError } from '../errors.js';
7
7
  import { currentSignal } from '../operations/process.js';
8
+ import { onStepStarted } from '../operations/progress.js';
8
9
  import { writeAtomicFile } from './atomic-file.js';
9
10
  import { acquireLock, inspectLock } from './lock-file.js';
10
11
  const status = z.enum([
@@ -14,6 +15,15 @@ const status = z.enum([
14
15
  'removing',
15
16
  'failed',
16
17
  ]);
18
+ /** The statuses of a create, reset or remove that runs or was interrupted. */
19
+ const busyStatuses = new Set(['creating', 'resetting', 'removing']);
20
+ /** Fields that wt writes while a create, reset or remove runs; see {@link JsonStore.save}. */
21
+ const operationFields = {
22
+ /** Label of the step of the operation that started last, or `null` before its first step. */
23
+ step: z.string().nullable().optional(),
24
+ /** When wt recorded the start of the operation, as an ISO 8601 time. */
25
+ startedAt: z.string().optional(),
26
+ };
17
27
  const stateSchema = z.object({
18
28
  schemaVersion: z.literal(1),
19
29
  repositoryId: z.string(),
@@ -38,6 +48,7 @@ const stateSchema = z.object({
38
48
  }).optional(),
39
49
  status,
40
50
  error: z.string().optional(),
51
+ ...operationFields,
41
52
  });
42
53
  const attachedSchema = z.object({
43
54
  schemaVersion: z.literal(1),
@@ -55,12 +66,56 @@ const attachedSchema = z.object({
55
66
  }),
56
67
  status,
57
68
  error: z.string().optional(),
69
+ ...operationFields,
58
70
  });
59
71
  function isMissing(error) {
60
72
  return error.code === 'ENOENT';
61
73
  }
62
74
  const repositoryLockTimeout = 60_000;
63
75
  const lockPollInterval = 100;
76
+ let pendingWrites = Promise.resolve();
77
+ /**
78
+ * Runs the changes of state files one after another, in the order they are
79
+ * requested, so a step recorded in the background never lands after a later
80
+ * status.
81
+ */
82
+ async function queueWrite(write) {
83
+ const result = pendingWrites.then(write);
84
+ pendingWrites = result.catch(() => undefined);
85
+ await result;
86
+ }
87
+ async function writeState(path, state) {
88
+ const contents = `${JSON.stringify(state, null, 2)}\n`;
89
+ await queueWrite(async () => {
90
+ await mkdir(dirname(path), { recursive: true });
91
+ await writeAtomicFile(path, contents);
92
+ });
93
+ }
94
+ /**
95
+ * The operations this process saw start, by the path of their state file,
96
+ * until any store saves another status there or removes the file.
97
+ */
98
+ const runningOperations = new Map();
99
+ const stepRecorders = new Map();
100
+ function withOperation({ state, step, startedAt }) {
101
+ return { ...state, step, startedAt };
102
+ }
103
+ /** The listener that saves the state at `path` again with each step that starts. */
104
+ function stepRecorder(path) {
105
+ let recorder = stepRecorders.get(path);
106
+ if (recorder === undefined) {
107
+ recorder = (step) => {
108
+ const operation = runningOperations.get(path);
109
+ if (operation === undefined)
110
+ return;
111
+ operation.step = step;
112
+ // The step only informs readers, so a failed write must not fail the operation.
113
+ writeState(path, withOperation(operation)).catch(() => undefined);
114
+ };
115
+ stepRecorders.set(path, recorder);
116
+ }
117
+ return recorder;
118
+ }
64
119
  class JsonStore {
65
120
  directory;
66
121
  schema;
@@ -82,9 +137,30 @@ class JsonStore {
82
137
  throw new Error(`Invalid ${this.kind} state in ${path}`, { cause: error });
83
138
  }
84
139
  }
140
+ /**
141
+ * Saves `state`. While its status is `creating`, `resetting` or `removing`,
142
+ * the saved state also holds when the operation started and the label of
143
+ * its current step, which is saved again each time a step of the current
144
+ * operation starts. Other statuses drop both fields.
145
+ */
85
146
  async save(state) {
86
- await mkdir(this.directory, { recursive: true });
87
- await writeAtomicFile(this.pathFor(state.name, '.json'), `${JSON.stringify(state, null, 2)}\n`);
147
+ const { step: _step, startedAt: _startedAt, ...plain } = state;
148
+ const path = this.pathFor(state.name, '.json');
149
+ if (!busyStatuses.has(state.status)) {
150
+ runningOperations.delete(path);
151
+ return writeState(path, plain);
152
+ }
153
+ const previous = runningOperations.get(path);
154
+ const operation = previous?.state.status === state.status
155
+ ? { ...previous, state: plain }
156
+ : {
157
+ state: plain,
158
+ startedAt: new Date().toISOString(),
159
+ step: null,
160
+ };
161
+ runningOperations.set(path, operation);
162
+ onStepStarted(stepRecorder(path));
163
+ return writeState(path, withOperation(operation));
88
164
  }
89
165
  /** Returns the state saved under `name`, or `undefined` when there is none. */
90
166
  async find(name) {
@@ -104,7 +180,9 @@ class JsonStore {
104
180
  return state;
105
181
  }
106
182
  async remove(name) {
107
- await unlink(this.pathFor(name, '.json'));
183
+ const path = this.pathFor(name, '.json');
184
+ runningOperations.delete(path);
185
+ await queueWrite(async () => unlink(path));
108
186
  }
109
187
  async list() {
110
188
  const files = await readdir(this.directory).catch((error) => {
@@ -1,9 +1,14 @@
1
+ import { environmentState } from '../environment-state.js';
1
2
  import { colorize } from './format-status.js';
2
- const states = {
3
+ const indicators = {
3
4
  running: { icon: '●', variant: 'success' },
4
5
  stopped: { icon: '○', variant: 'warning' },
6
+ finished: { icon: '○', variant: 'plain' },
7
+ missing: { icon: '!', variant: 'error' },
8
+ busy: { icon: '!', variant: 'error' },
9
+ failed: { icon: '!', variant: 'error' },
10
+ unknown: { icon: '!', variant: 'error' },
5
11
  };
6
- const unknownState = { icon: '!', variant: 'error' };
7
12
  /**
8
13
  * Formats managed worktrees as an aligned table. Cells are padded before they
9
14
  * are colored so escape sequences never shift the columns. The URL column only
@@ -12,23 +17,19 @@ const unknownState = { icon: '!', variant: 'error' };
12
17
  export function formatEnvironmentTable(items) {
13
18
  const withUrls = items.some(item => item.url !== undefined);
14
19
  const rows = items.map((item) => {
15
- const status = item.status !== undefined && item.status !== 'ready'
16
- ? item.status
17
- : item.dockerStatus;
18
- const state = status in states
19
- ? states[status]
20
- : unknownState;
20
+ const state = environmentState(item.status, item.dockerStatus);
21
+ const indicator = indicators[state.kind];
21
22
  return {
22
23
  cells: [
23
24
  item.name,
24
25
  item.branch || '(detached)',
25
- `${state.icon} ${status}`,
26
+ `${indicator.icon} ${state.label}`,
26
27
  item.projectName,
27
28
  ...(withUrls
28
29
  ? [item.url ?? '-']
29
30
  : []),
30
31
  ],
31
- variant: state.variant,
32
+ variant: indicator.variant,
32
33
  };
33
34
  });
34
35
  const header = [
@@ -10,6 +10,8 @@ export function environmentListJson(items) {
10
10
  branch: missing(item.branch),
11
11
  path: missing(item.path),
12
12
  status: missing(item.status),
13
+ step: item.step ?? null,
14
+ startedAt: item.startedAt ?? null,
13
15
  dockerStatus: item.dockerStatus,
14
16
  projectName: missing(item.projectName),
15
17
  url: item.url ?? null,
@@ -21,6 +23,8 @@ export function environmentInfoJson(info) {
21
23
  branch: missing(info.branch),
22
24
  path: info.path,
23
25
  status: missing(info.status),
26
+ step: info.step ?? null,
27
+ startedAt: info.startedAt ?? null,
24
28
  projectName: missing(info.projectName),
25
29
  error: missing(info.error),
26
30
  host: info.host === undefined
@@ -29,9 +33,14 @@ export function environmentInfoJson(info) {
29
33
  name: info.host.name,
30
34
  path: missing(info.host.path),
31
35
  },
32
- containers: info.containers.map(({ name, service, state, status, address, ports }) => ({
36
+ containers: info.containers.map(({ name, service, number, oneOff, state, status, address, ports }) => ({
33
37
  name,
34
38
  service,
39
+ // `--index` cannot reach a one-off container, whatever its labels say.
40
+ number: oneOff
41
+ ? null
42
+ : number ?? null,
43
+ oneOff,
35
44
  state,
36
45
  status,
37
46
  hostname: address?.hostname ?? null,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@joberthel/worktree",
3
3
  "type": "module",
4
- "version": "1.5.0",
4
+ "version": "1.6.0",
5
5
  "description": "Isolated development environments from Git worktrees, each with its own Docker Compose project and cloned volumes.",
6
6
  "author": "Johannes Berthel",
7
7
  "license": "MIT",