@joberthel/worktree 1.3.0 → 1.5.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,10 +1,12 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { link, mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
1
+ import { mkdir, readdir, readFile, unlink } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
4
3
  import process from 'node:process';
4
+ import { setTimeout as sleep } from 'node:timers/promises';
5
5
  import { z } from 'zod';
6
6
  import { WtError } from '../errors.js';
7
+ import { currentSignal } from '../operations/process.js';
7
8
  import { writeAtomicFile } from './atomic-file.js';
9
+ import { acquireLock, inspectLock } from './lock-file.js';
8
10
  const status = z.enum([
9
11
  'creating',
10
12
  'ready',
@@ -57,6 +59,8 @@ const attachedSchema = z.object({
57
59
  function isMissing(error) {
58
60
  return error.code === 'ENOENT';
59
61
  }
62
+ const repositoryLockTimeout = 60_000;
63
+ const lockPollInterval = 100;
60
64
  class JsonStore {
61
65
  directory;
62
66
  schema;
@@ -128,27 +132,68 @@ export class StateStore extends JsonStore {
128
132
  constructor(gitCommonDir) {
129
133
  super(join(gitCommonDir, 'wt'), stateSchema, 'worktree');
130
134
  }
131
- async lock(name) {
135
+ worktreeLockPath(name) {
136
+ return join(this.directory, 'locks', `${encodeURIComponent(name.toLowerCase())}.lock`);
137
+ }
138
+ get repositoryLockPath() {
139
+ return join(this.directory, 'repository.lock');
140
+ }
141
+ /**
142
+ * Locks one worktree for as long as a command changes it. Fails at once when
143
+ * another command holds the lock, because that command may run for minutes.
144
+ * Names that differ only in case share a lock.
145
+ */
146
+ async lockWorktree(name) {
147
+ const path = this.worktreeLockPath(name);
148
+ await mkdir(dirname(path), { recursive: true });
149
+ return acquireLock(path, {
150
+ busy: `Worktree ${name} is busy: it is locked`,
151
+ lock: `the lock of worktree ${name}`,
152
+ unlock: `wt unlock ${name}`,
153
+ });
154
+ }
155
+ /**
156
+ * Locks the repository's shared state for a short step: checking that a new
157
+ * worktree's name and directory are free, registering it, and adding or
158
+ * removing Git worktrees. Waits up to `timeout` milliseconds for another
159
+ * command to finish its step.
160
+ */
161
+ async lockRepository(timeout = repositoryLockTimeout) {
132
162
  await mkdir(this.directory, { recursive: true });
133
- const path = this.pathFor(name, '.lock');
134
- const temporary = this.pathFor(randomUUID(), '.tmp');
135
- const started = new Date(Date.now() - process.uptime() * 1000).toISOString();
136
- await writeFile(temporary, `${process.pid} (started ${started})\n`, { mode: 0o600, flag: 'wx' });
137
- try {
138
- await link(temporary, path);
163
+ const deadline = Date.now() + timeout;
164
+ for (;;) {
165
+ try {
166
+ return await acquireLock(this.repositoryLockPath, {
167
+ busy: 'Worktree operations are locked',
168
+ lock: 'the repository lock',
169
+ unlock: 'wt unlock --repository',
170
+ });
171
+ }
172
+ catch (error) {
173
+ if (error.code !== 'locked' || Date.now() >= deadline)
174
+ throw error;
175
+ }
176
+ await sleep(lockPollInterval);
177
+ currentSignal()?.throwIfAborted();
139
178
  }
140
- catch (error) {
141
- if (error.code !== 'EEXIST')
142
- throw error;
143
- const owner = await readFile(path, 'utf8').catch(() => '');
144
- throw new WtError('locked', `Worktree operations are locked at ${path}${owner.trim()
145
- ? ` by PID ${owner.trim()}`
146
- : ''}. Retry when it exits. If the lock is stale, verify the owner has exited before removing the lock file.`);
179
+ }
180
+ /** Runs `work` while the repository lock is held. */
181
+ async withRepositoryLock(work) {
182
+ const unlock = await this.lockRepository();
183
+ try {
184
+ return await work();
147
185
  }
148
186
  finally {
149
- await unlink(temporary);
187
+ await unlock();
150
188
  }
151
- return async () => unlink(path);
189
+ }
190
+ /** The lock of worktree `name` and its owner, or `undefined` when it is not locked. */
191
+ async inspectWorktreeLock(name) {
192
+ return inspectLock(this.worktreeLockPath(name));
193
+ }
194
+ /** The repository lock and its owner, or `undefined` when it is not locked. */
195
+ async inspectRepositoryLock() {
196
+ return inspectLock(this.repositoryLockPath);
152
197
  }
153
198
  }
154
199
  /**
@@ -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.3.0",
4
+ "version": "1.5.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",
@@ -6,7 +6,7 @@
6
6
  "type": "object",
7
7
  "properties": {
8
8
  "host": {
9
- "description": "Runs this repository inside the Docker environment of a host repository. Cannot be combined with `worktrees`.",
9
+ "description": "Runs this repository inside the Docker environment of a host repository. Cannot be combined with `worktrees` or `volumes`.",
10
10
  "type": "object",
11
11
  "properties": {
12
12
  "path": {
@@ -63,6 +63,28 @@
63
63
  }
64
64
  ]
65
65
  },
66
+ "volumes": {
67
+ "description": "How the named Docker volumes of the source project are cloned.",
68
+ "default": {
69
+ "pause_source": false
70
+ },
71
+ "anyOf": [
72
+ {
73
+ "type": "object",
74
+ "properties": {
75
+ "pause_source": {
76
+ "default": false,
77
+ "description": "Pauses the running containers that mount a source volume while `wt create` and `wt reset` copy the volumes, for a crash-consistent copy. These services do not respond until the copy has finished.",
78
+ "type": "boolean"
79
+ }
80
+ },
81
+ "additionalProperties": false
82
+ },
83
+ {
84
+ "type": "null"
85
+ }
86
+ ]
87
+ },
66
88
  "hooks": {
67
89
  "description": "Commands run by `wt create` and `wt reset`.",
68
90
  "anyOf": [
@@ -200,9 +222,19 @@
200
222
  },
201
223
  "additionalProperties": false,
202
224
  "not": {
203
- "required": [
204
- "host",
205
- "worktrees"
225
+ "anyOf": [
226
+ {
227
+ "required": [
228
+ "host",
229
+ "worktrees"
230
+ ]
231
+ },
232
+ {
233
+ "required": [
234
+ "host",
235
+ "volumes"
236
+ ]
237
+ }
206
238
  ]
207
239
  }
208
240
  }
@@ -1,64 +0,0 @@
1
- import process from 'node:process';
2
- import { afterEach, beforeEach, vi } from 'vitest';
3
- export function commandMocks() {
4
- return {
5
- composeOperation: vi.fn(),
6
- createEnvironment: vi.fn(),
7
- inspectEnvironment: vi.fn(),
8
- listEnvironmentNames: vi.fn(),
9
- listEnvironments: vi.fn(),
10
- removeEnvironment: vi.fn(),
11
- resetEnvironment: vi.fn(),
12
- resolveEnvironmentName: vi.fn(),
13
- runningEnvironmentNames: vi.fn(),
14
- };
15
- }
16
- /** The `process.stdout` error listeners that were there before wt added its own. */
17
- export const originalListeners = new Set(process.stdout.listeners('error'));
18
- /**
19
- * Registers hooks that load a fresh CLI for each test, record stdout and
20
- * stderr, and restore the process afterwards. The returned spies are replaced
21
- * before each test.
22
- */
23
- export function setupCli(mocks) {
24
- const originalArgv = process.argv;
25
- const io = {};
26
- beforeEach(() => {
27
- vi.resetModules();
28
- vi.clearAllMocks();
29
- io.stdout = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
30
- io.stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
31
- mocks.resolveEnvironmentName.mockImplementation(async (name) => name ?? 'detected');
32
- mocks.composeOperation.mockResolvedValue(undefined);
33
- process.exitCode = 0;
34
- });
35
- afterEach(() => {
36
- vi.restoreAllMocks();
37
- vi.unstubAllEnvs();
38
- process.argv = originalArgv;
39
- process.exitCode = 0;
40
- for (const listener of process.stdout.listeners('error')) {
41
- if (!originalListeners.has(listener))
42
- process.stdout.off('error', listener);
43
- }
44
- });
45
- return io;
46
- }
47
- export async function cli(...args) {
48
- process.argv = ['node', 'wt', ...args];
49
- await import('../cli.js');
50
- }
51
- /** Runs the CLI a second time in the same test. */
52
- export async function cliAgain(...args) {
53
- vi.resetModules();
54
- await cli(...args);
55
- }
56
- /** An error of the module graph the next `cli` call loads, so `instanceof` holds there. */
57
- export async function codedError(code, message) {
58
- const { WtError } = await import('../errors.js');
59
- return new WtError(code, message);
60
- }
61
- /** The handler wt installed for `signal`, called directly so the test runner never sees the signal. */
62
- export function signalHandler(signal) {
63
- return process.listeners(signal).at(-1);
64
- }
@@ -1,67 +0,0 @@
1
- import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
- import process from 'node:process';
5
- import { vi } from 'vitest';
6
- import { StateStore } from '../../state/store.js';
7
- /**
8
- * Creates a source checkout and a saved, ready `feature` environment in a
9
- * temporary directory, and gives the mocks working defaults.
10
- */
11
- export async function createFixture(mocks) {
12
- vi.resetAllMocks();
13
- const base = await realpath(await mkdtemp(join(tmpdir(), 'wt-manage-')));
14
- const source = join(base, 'source');
15
- const common = join(source, '.git');
16
- const store = new StateStore(common);
17
- const state = {
18
- schemaVersion: 1,
19
- repositoryId: 'repo',
20
- name: 'feature',
21
- path: join(base, 'feature'),
22
- branch: 'feature',
23
- sourceWorktreePath: source,
24
- sourceProject: 'parent',
25
- composeFiles: [
26
- join(source, 'compose.yml'),
27
- ],
28
- overridePath: join(store.directory, 'feature.compose.yml'),
29
- projectName: 'wt-repo-feature',
30
- volumes: { db: 'old' },
31
- status: 'ready',
32
- };
33
- await mkdir(state.path);
34
- await store.save(state);
35
- mocks.repositoryInfo.mockResolvedValue({ root: source, repositoryRoot: source, gitCommonDir: common });
36
- mocks.git.mockResolvedValue('');
37
- mocks.docker.mockImplementation(async (args) => {
38
- if (args[0] === 'volume' && args[1] === 'inspect')
39
- return '{"com.wt.repository":"repo","com.wt.worktree":"feature"}';
40
- return '';
41
- });
42
- mocks.resolveSourceVolumes.mockResolvedValue({ db: 'source-volume' });
43
- mocks.prepareVolumeCopy.mockResolvedValue('image');
44
- mocks.cloneNamedVolumes.mockImplementation(async (_sources, _owner, _cwd, _image, record) => {
45
- await record('fresh', { db: 'fresh' });
46
- return { db: 'fresh' };
47
- });
48
- return { base, source, common, state, store };
49
- }
50
- export async function removeFixture(fixture) {
51
- vi.restoreAllMocks();
52
- await rm(fixture.base, { recursive: true, force: true });
53
- }
54
- /** Runs `operation` while `process.stdin.isTTY` reports `isTTY`. */
55
- export async function withTTY(isTTY, operation) {
56
- const previous = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
57
- Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: isTTY });
58
- try {
59
- return await operation();
60
- }
61
- finally {
62
- if (previous)
63
- Object.defineProperty(process.stdin, 'isTTY', previous);
64
- else
65
- Reflect.deleteProperty(process.stdin, 'isTTY');
66
- }
67
- }