@joberthel/worktree 1.4.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.
@@ -0,0 +1,245 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { link, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
+ import { hostname } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import process from 'node:process';
6
+ import { z } from 'zod';
7
+ import { WtError } from '../errors.js';
8
+ import { reportNote } from '../operations/progress.js';
9
+ import { processStart } from './process-start.js';
10
+ const ownerSchema = z.object({
11
+ pid: z.number().int().positive(),
12
+ /** Host the command runs on. wt 1.4.0 and older did not record it. */
13
+ host: z.string().optional(),
14
+ /** When the command started, as an ISO date. */
15
+ started: z.string().optional(),
16
+ /** When its process started, as `processStart` reports it, to tell it from a later process with the same PID. */
17
+ processStart: z.string().optional(),
18
+ /** The command, such as `wt create topic`. */
19
+ command: z.string().optional(),
20
+ });
21
+ const started = new Date(Date.now() - process.uptime() * 1000).toISOString();
22
+ let ownStart;
23
+ /** The record of this command in its lock files. */
24
+ async function ownRecord() {
25
+ ownStart ??= processStart(process.pid);
26
+ const owner = {
27
+ pid: process.pid,
28
+ host: hostname(),
29
+ started,
30
+ processStart: await ownStart,
31
+ command: [
32
+ 'wt',
33
+ ...process.argv.slice(2),
34
+ ].join(' '),
35
+ };
36
+ return `${JSON.stringify(owner)}\n`;
37
+ }
38
+ /** The owner in a lock record, also in the line that wt 1.4.0 and older wrote. */
39
+ export function parseOwner(record) {
40
+ try {
41
+ return ownerSchema.parse(JSON.parse(record));
42
+ }
43
+ catch {
44
+ const [, pid, started, command] = /^(\d+)(?: \(started ([^)]*)\): (.*))?$/s.exec(record.trim()) ?? [];
45
+ return ownerSchema.safeParse({
46
+ pid: Number(pid),
47
+ started,
48
+ command,
49
+ }).data;
50
+ }
51
+ }
52
+ /** The owner as messages show it, such as `PID 123 (wt create topic, started … on host)`. */
53
+ export function describeOwner({ pid, host, started, command }) {
54
+ const start = [
55
+ started === undefined
56
+ ? ''
57
+ : `started ${started}`,
58
+ host === undefined
59
+ ? ''
60
+ : `on ${host}`,
61
+ ].filter(Boolean).join(' ');
62
+ const details = [command ?? '', start].filter(Boolean).join(', ');
63
+ return `PID ${pid}${details && ` (${details})`}`;
64
+ }
65
+ async function ownerStatus(owner) {
66
+ if (owner.host !== hostname())
67
+ return 'unknown';
68
+ try {
69
+ process.kill(owner.pid, 0);
70
+ }
71
+ catch (error) {
72
+ const { code } = error;
73
+ if (code === 'ESRCH')
74
+ return 'exited';
75
+ // EPERM: the process runs under another user.
76
+ if (code !== 'EPERM')
77
+ return 'unknown';
78
+ }
79
+ if (owner.processStart === undefined)
80
+ return 'running';
81
+ const start = await processStart(owner.pid);
82
+ return start === undefined || start === owner.processStart
83
+ ? 'running'
84
+ : 'replaced';
85
+ }
86
+ /** The content of a lock file, `undefined` when it does not exist, or empty when it cannot be read. */
87
+ async function readRecord(path) {
88
+ try {
89
+ return await readFile(path, 'utf8');
90
+ }
91
+ catch (error) {
92
+ return error.code === 'ENOENT'
93
+ ? undefined
94
+ : '';
95
+ }
96
+ }
97
+ async function inspectFile(path) {
98
+ const record = await readRecord(path);
99
+ if (record === undefined)
100
+ return undefined;
101
+ const owner = parseOwner(record);
102
+ return owner === undefined
103
+ ? { path, record, status: 'unknown' }
104
+ : {
105
+ path,
106
+ record,
107
+ owner,
108
+ status: await ownerStatus(owner),
109
+ };
110
+ }
111
+ function takeoverPath(path) {
112
+ return `${path}.takeover`;
113
+ }
114
+ /** The lock at `path` with its owner and a takeover of it, or `undefined` when nobody holds it. */
115
+ export async function inspectLock(path) {
116
+ const held = await inspectFile(path);
117
+ return held && { ...held, takeover: await inspectFile(takeoverPath(path)) };
118
+ }
119
+ function isStale(held) {
120
+ return held.status === 'exited' || held.status === 'replaced';
121
+ }
122
+ function temporaryPath(path) {
123
+ return join(dirname(path), `${randomUUID()}.tmp`);
124
+ }
125
+ async function removeFile(path) {
126
+ await unlink(path).catch((error) => {
127
+ if (error.code !== 'ENOENT')
128
+ throw error;
129
+ });
130
+ }
131
+ /** Releases a lock, unless another command owns it by now because wt unlock removed it. */
132
+ function release(path, record) {
133
+ return async () => {
134
+ if (await readRecord(path) === record)
135
+ await removeFile(path);
136
+ };
137
+ }
138
+ /** Creates the lock file at `path` atomically, or returns `undefined` when it exists. */
139
+ async function claim(path, record) {
140
+ const temporary = temporaryPath(path);
141
+ await writeFile(temporary, record, { mode: 0o600, flag: 'wx' });
142
+ try {
143
+ await link(temporary, path);
144
+ return release(path, record);
145
+ }
146
+ catch (error) {
147
+ if (error.code !== 'EEXIST')
148
+ throw error;
149
+ return undefined;
150
+ }
151
+ finally {
152
+ await unlink(temporary);
153
+ }
154
+ }
155
+ /** Replaces the stale lock `held` with `record`, unless another command takes it over or it changed. */
156
+ async function takeOver(held, record) {
157
+ const releaseTakeover = await claim(takeoverPath(held.path), record);
158
+ if (releaseTakeover === undefined)
159
+ return false;
160
+ try {
161
+ if (await readRecord(held.path) !== held.record)
162
+ return false;
163
+ const temporary = temporaryPath(held.path);
164
+ await writeFile(temporary, record, { mode: 0o600, flag: 'wx' });
165
+ await rename(temporary, held.path);
166
+ return true;
167
+ }
168
+ finally {
169
+ await releaseTakeover();
170
+ }
171
+ }
172
+ /** What to do about a lock that another command holds. */
173
+ function advice(held, { unlock }) {
174
+ if (held === undefined)
175
+ return 'Retry.';
176
+ const remove = `remove the lock with ${unlock}`;
177
+ if (held.status === 'running')
178
+ return 'Retry when it exits.';
179
+ if (isStale(held)) {
180
+ if (held.takeover?.status === 'running')
181
+ return 'It no longer runs, and another wt command is taking the lock over. Retry when that command exits.';
182
+ return held.takeover === undefined
183
+ ? 'It no longer runs. Retry.'
184
+ : `It no longer runs, but another command did not finish taking the lock over. Remove the lock with ${unlock}.`;
185
+ }
186
+ if (held.owner === undefined)
187
+ return `The lock file does not name its owner. If no wt command holds the lock, ${remove}.`;
188
+ if (held.owner.host === undefined)
189
+ return `Retry when it exits. An older wt version took the lock, so wt cannot check whether it still runs. If it does not, ${remove}.`;
190
+ return `Retry when it exits. If it no longer runs${held.owner.host === hostname()
191
+ ? ''
192
+ : ` on ${held.owner.host}`}, ${remove}.`;
193
+ }
194
+ /**
195
+ * Creates the lock file at `path` atomically, with this command as its
196
+ * owner. A lock that another command left behind is taken over when that
197
+ * command no longer runs. Fails with `locked` while another command holds
198
+ * the lock.
199
+ */
200
+ export async function acquireLock(path, label) {
201
+ const record = await ownRecord();
202
+ let held;
203
+ // The lock may be released or taken over while it is inspected, so look again.
204
+ for (let attempt = 0; attempt < 3; attempt++) {
205
+ const unlock = await claim(path, record);
206
+ if (unlock !== undefined)
207
+ return unlock;
208
+ held = await inspectLock(path);
209
+ if (held === undefined)
210
+ continue;
211
+ if (!isStale(held) || held.takeover !== undefined)
212
+ break;
213
+ if (await takeOver(held, record)) {
214
+ reportNote(`Took over ${label.lock} from ${describeOwner(held.owner)}, which no longer runs.`);
215
+ return release(path, record);
216
+ }
217
+ }
218
+ const owner = held?.owner === undefined
219
+ ? ''
220
+ : ` by ${describeOwner(held.owner)}`;
221
+ throw new WtError('locked', `${label.busy} at ${path}${owner}. ${advice(held, label)}`);
222
+ }
223
+ /**
224
+ * Removes a lock that `inspectLock` returned, together with the takeover it
225
+ * found. Fails with `changed` when the lock changed since then, for example
226
+ * because another command took it over.
227
+ */
228
+ export async function removeLock(held) {
229
+ const takeover = takeoverPath(held.path);
230
+ if (held.takeover !== undefined && await readRecord(takeover) === held.takeover.record)
231
+ await removeFile(takeover);
232
+ const changed = new WtError('changed', `The lock at ${held.path} changed while waiting. Retry the command.`);
233
+ const releaseTakeover = await claim(takeover, await ownRecord());
234
+ if (releaseTakeover === undefined)
235
+ throw changed;
236
+ try {
237
+ const record = await readRecord(held.path);
238
+ if (record !== undefined && record !== held.record)
239
+ throw changed;
240
+ await removeFile(held.path);
241
+ }
242
+ finally {
243
+ await releaseTakeover();
244
+ }
245
+ }
@@ -0,0 +1,29 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import process from 'node:process';
3
+ import { run } from '../operations/process.js';
4
+ /**
5
+ * When the process `pid` started, as the operating system records it, or
6
+ * `undefined` when it does not run or cannot be inspected. The value stays
7
+ * the same while the process runs, even when the clock is changed, and
8
+ * differs for a later process that reuses the PID.
9
+ */
10
+ export async function processStart(pid, platform = process.platform) {
11
+ if (platform === 'linux') {
12
+ // Field 22 counts clock ticks from boot to the start. The command name in
13
+ // field 2 is in parentheses and may contain spaces and parentheses itself.
14
+ const stat = await readFile(`/proc/${pid}/stat`, 'utf8').catch(() => '');
15
+ return stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19] || undefined;
16
+ }
17
+ // ps prints the start time the kernel recorded. UTC and the C locale keep
18
+ // the output the same for every caller.
19
+ const started = await run('ps', [
20
+ '-o',
21
+ 'lstart=',
22
+ '-p',
23
+ String(pid),
24
+ ], '/', {
25
+ env: { ...process.env, LC_ALL: 'C', TZ: 'UTC0' },
26
+ timeout: 5000,
27
+ }).catch(() => '');
28
+ return started || undefined;
29
+ }
@@ -1,12 +1,13 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { link, mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises';
1
+ import { mkdir, readdir, readFile, unlink } from 'node:fs/promises';
3
2
  import { dirname, join } from 'node:path';
4
3
  import process from 'node:process';
5
4
  import { setTimeout as sleep } from 'node:timers/promises';
6
5
  import { z } from 'zod';
7
6
  import { WtError } from '../errors.js';
8
7
  import { currentSignal } from '../operations/process.js';
8
+ import { onStepStarted } from '../operations/progress.js';
9
9
  import { writeAtomicFile } from './atomic-file.js';
10
+ import { acquireLock, inspectLock } from './lock-file.js';
10
11
  const status = z.enum([
11
12
  'creating',
12
13
  'ready',
@@ -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,43 +66,55 @@ 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;
64
- /** What a lock file records about the command that holds it. */
65
- function lockOwner() {
66
- const started = new Date(Date.now() - process.uptime() * 1000).toISOString();
67
- const command = [
68
- 'wt',
69
- ...process.argv.slice(2),
70
- ].join(' ');
71
- return `${process.pid} (started ${started}): ${command}`;
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
+ });
72
93
  }
73
94
  /**
74
- * Creates the lock file at `path` atomically with the owner's details. A lock
75
- * file is never removed by another command, because its owner may still run.
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.
76
97
  */
77
- async function acquire(path, locked) {
78
- const temporary = join(dirname(path), `${randomUUID()}.tmp`);
79
- await writeFile(temporary, `${lockOwner()}\n`, { mode: 0o600, flag: 'wx' });
80
- try {
81
- await link(temporary, path);
82
- }
83
- catch (error) {
84
- if (error.code !== 'EEXIST')
85
- throw error;
86
- const owner = await readFile(path, 'utf8').catch(() => '');
87
- throw new WtError('locked', `${locked} at ${path}${owner.trim()
88
- ? ` by PID ${owner.trim()}`
89
- : ''}. Retry when it exits. If the lock is stale, verify the owner has exited before removing the lock file.`);
90
- }
91
- finally {
92
- await unlink(temporary);
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);
93
116
  }
94
- return async () => unlink(path);
117
+ return recorder;
95
118
  }
96
119
  class JsonStore {
97
120
  directory;
@@ -114,9 +137,30 @@ class JsonStore {
114
137
  throw new Error(`Invalid ${this.kind} state in ${path}`, { cause: error });
115
138
  }
116
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
+ */
117
146
  async save(state) {
118
- await mkdir(this.directory, { recursive: true });
119
- 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));
120
164
  }
121
165
  /** Returns the state saved under `name`, or `undefined` when there is none. */
122
166
  async find(name) {
@@ -136,7 +180,9 @@ class JsonStore {
136
180
  return state;
137
181
  }
138
182
  async remove(name) {
139
- await unlink(this.pathFor(name, '.json'));
183
+ const path = this.pathFor(name, '.json');
184
+ runningOperations.delete(path);
185
+ await queueWrite(async () => unlink(path));
140
186
  }
141
187
  async list() {
142
188
  const files = await readdir(this.directory).catch((error) => {
@@ -164,15 +210,25 @@ export class StateStore extends JsonStore {
164
210
  constructor(gitCommonDir) {
165
211
  super(join(gitCommonDir, 'wt'), stateSchema, 'worktree');
166
212
  }
213
+ worktreeLockPath(name) {
214
+ return join(this.directory, 'locks', `${encodeURIComponent(name.toLowerCase())}.lock`);
215
+ }
216
+ get repositoryLockPath() {
217
+ return join(this.directory, 'repository.lock');
218
+ }
167
219
  /**
168
220
  * Locks one worktree for as long as a command changes it. Fails at once when
169
221
  * another command holds the lock, because that command may run for minutes.
170
222
  * Names that differ only in case share a lock.
171
223
  */
172
224
  async lockWorktree(name) {
173
- const directory = join(this.directory, 'locks');
174
- await mkdir(directory, { recursive: true });
175
- return acquire(join(directory, `${encodeURIComponent(name.toLowerCase())}.lock`), `Worktree ${name} is busy: it is locked`);
225
+ const path = this.worktreeLockPath(name);
226
+ await mkdir(dirname(path), { recursive: true });
227
+ return acquireLock(path, {
228
+ busy: `Worktree ${name} is busy: it is locked`,
229
+ lock: `the lock of worktree ${name}`,
230
+ unlock: `wt unlock ${name}`,
231
+ });
176
232
  }
177
233
  /**
178
234
  * Locks the repository's shared state for a short step: checking that a new
@@ -182,11 +238,14 @@ export class StateStore extends JsonStore {
182
238
  */
183
239
  async lockRepository(timeout = repositoryLockTimeout) {
184
240
  await mkdir(this.directory, { recursive: true });
185
- const path = join(this.directory, 'repository.lock');
186
241
  const deadline = Date.now() + timeout;
187
242
  for (;;) {
188
243
  try {
189
- return await acquire(path, 'Worktree operations are locked');
244
+ return await acquireLock(this.repositoryLockPath, {
245
+ busy: 'Worktree operations are locked',
246
+ lock: 'the repository lock',
247
+ unlock: 'wt unlock --repository',
248
+ });
190
249
  }
191
250
  catch (error) {
192
251
  if (error.code !== 'locked' || Date.now() >= deadline)
@@ -206,6 +265,14 @@ export class StateStore extends JsonStore {
206
265
  await unlock();
207
266
  }
208
267
  }
268
+ /** The lock of worktree `name` and its owner, or `undefined` when it is not locked. */
269
+ async inspectWorktreeLock(name) {
270
+ return inspectLock(this.worktreeLockPath(name));
271
+ }
272
+ /** The repository lock and its owner, or `undefined` when it is not locked. */
273
+ async inspectRepositoryLock() {
274
+ return inspectLock(this.repositoryLockPath);
275
+ }
209
276
  }
210
277
  /**
211
278
  * Worktrees of a repository that has no Docker environment of its own. Each
@@ -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,
@@ -1,13 +1,19 @@
1
1
  import process from 'node:process';
2
+ import { withProgress } from '../operations/progress.js';
2
3
  import { isHookLabel } from './progress-state.js';
4
+ /**
5
+ * Runs `operation` and shows its progress on stderr, in a terminal UI when
6
+ * there is a terminal. Notes reported during the operation are shown too.
7
+ */
3
8
  export async function showOperation(label, operation, interrupt) {
4
9
  if (!process.stderr.isTTY || !process.stdin.isTTY || !process.stdout.isTTY) {
5
- return operation((event) => {
10
+ const report = (event) => {
6
11
  if (event.status === 'log')
7
12
  process.stderr.write(event.text);
8
13
  else if (event.status === 'started')
9
14
  process.stderr.write(`${event.label}\n`);
10
- });
15
+ };
16
+ return withProgress(report, async () => operation(report));
11
17
  }
12
18
  // Ink takes ~200 ms to load, so only load it when a terminal UI is drawn.
13
19
  const [{ render }, { createElement }, { OperationView }] = await Promise.all([
@@ -29,7 +35,7 @@ export async function showOperation(label, operation, interrupt) {
29
35
  showsHookOutput ||= event.status === 'log' || isHookLabel(event.label);
30
36
  report(event);
31
37
  };
32
- void operation(track, confirm).then(resolve, reject);
38
+ void withProgress(track, async () => operation(track, confirm)).then(resolve, reject);
33
39
  },
34
40
  };
35
41
  instance = render(createElement(OperationView, props), {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@joberthel/worktree",
3
3
  "type": "module",
4
- "version": "1.4.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",