@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.
package/dist/help.js ADDED
@@ -0,0 +1,111 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { commandOptions, commands, printsScript } from './cli-spec.js';
3
+ /*
4
+ * Help for people and, with `--format json`, for scripts and coding agents.
5
+ * Both are read from the command table in cli-spec.ts.
6
+ */
7
+ const description = 'Manage isolated Git worktrees with Docker Compose.';
8
+ const workingDirOption = {
9
+ name: '--working-dir',
10
+ alias: '-w',
11
+ value: '<dir>',
12
+ description: 'Run as if wt was started in <dir>',
13
+ repeatable: false,
14
+ };
15
+ const formatOption = {
16
+ name: '--format',
17
+ alias: null,
18
+ value: '<text|json>',
19
+ description: 'Output format (default: text, or WT_FORMAT)',
20
+ repeatable: false,
21
+ };
22
+ /** The commands without JSON output, as help names them. */
23
+ const textOnlyCommands = new Intl.ListFormat('en').format(Object.entries(commands).filter(([, spec]) => !spec.shared).map(([name]) => name));
24
+ function optionHelp(command) {
25
+ return [
26
+ ...commandOptions(command).map(([name, { type, value, description }]) => ({
27
+ name: `--${name}`,
28
+ alias: null,
29
+ value: value ?? null,
30
+ description,
31
+ repeatable: type === 'strings',
32
+ })),
33
+ ...(printsScript(command)
34
+ ? []
35
+ : [workingDirOption]),
36
+ ...(commands[command].shared
37
+ ? [formatOption]
38
+ : []),
39
+ ];
40
+ }
41
+ function optionFlags({ name, alias, value }) {
42
+ return `${alias === null
43
+ ? ''
44
+ : `${alias}, `}${name}${value === null
45
+ ? ''
46
+ : ` ${value}`}`;
47
+ }
48
+ function commandUsage(command) {
49
+ return `wt ${command} ${commands[command].usage}`.trimEnd();
50
+ }
51
+ export function usage(command) {
52
+ if (command !== undefined) {
53
+ const options = optionHelp(command).map(option => [
54
+ optionFlags(option),
55
+ option.description,
56
+ ]);
57
+ const width = Math.max(...options.map(([flags]) => flags.length));
58
+ const optionList = options.length
59
+ ? `\n\nOptions:\n${options.map(([flags, text]) => ` ${flags.padEnd(width)} ${text}`).join('\n')}`
60
+ : '';
61
+ return `Usage: ${commandUsage(command)}\n\n${commands[command].summary}${optionList}`;
62
+ }
63
+ const width = Math.max(...Object.keys(commands).map(name => name.length));
64
+ const list = Object.entries(commands).map(([name, spec]) => ` ${name.padEnd(width)} ${spec.usage.padEnd(43)} ${spec.summary}`).join('\n');
65
+ return `${description}\n\nUsage: wt [-w <dir>] <command>\n\n${list}\n\n -w, --working-dir <dir> Run as if wt was started in <dir>\n --format <text|json> Output format, for all commands except ${textOnlyCommands}\n -h, --help Show help\n -v, --version Show the version`;
66
+ }
67
+ function commandHelpJson(command) {
68
+ return {
69
+ name: command,
70
+ usage: commandUsage(command),
71
+ summary: commands[command].summary,
72
+ options: optionHelp(command),
73
+ formats: commands[command].shared
74
+ ? ['text', 'json']
75
+ : ['text'],
76
+ };
77
+ }
78
+ /** `--help --format json`: the commands and options, read from the same table as the text help. */
79
+ export function helpJson(command) {
80
+ if (command !== undefined)
81
+ return commandHelpJson(command);
82
+ return {
83
+ name: 'wt',
84
+ description,
85
+ version: version(),
86
+ usage: 'wt [-w <dir>] <command>',
87
+ commands: Object.keys(commands).map(name => commandHelpJson(name)),
88
+ options: [
89
+ workingDirOption,
90
+ { ...formatOption, description: `Output format, for all commands except ${textOnlyCommands} (default: text, or WT_FORMAT)` },
91
+ {
92
+ name: '--help',
93
+ alias: '-h',
94
+ value: null,
95
+ description: 'Show help',
96
+ repeatable: false,
97
+ },
98
+ {
99
+ name: '--version',
100
+ alias: '-v',
101
+ value: null,
102
+ description: 'Show the version',
103
+ repeatable: false,
104
+ },
105
+ ],
106
+ };
107
+ }
108
+ export function version() {
109
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
110
+ return pkg.version;
111
+ }
@@ -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 = {
@@ -7,6 +7,7 @@ import { AttachedStore, StateStore } from '../state/store.js';
7
7
  import { attachedHost, createAttached, removeAttached, resetAttached } from './attached.js';
8
8
  import { createManagedEnvironment, withCreateContext } from './create.js';
9
9
  import * as manage from './manage.js';
10
+ export { unlockEnvironment } from './unlock.js';
10
11
  /*
11
12
  * Entry points of the CLI. A name refers to an environment of the current
12
13
  * repository or to a worktree attached to an environment of a host
@@ -43,27 +44,36 @@ export async function listEnvironments(cwd) {
43
44
  listedEnvironments(cwd),
44
45
  projectUrls(cwd),
45
46
  ]);
46
- return rows.map(row => ({
47
+ return Promise.all(rows.map(async (row) => ({
47
48
  ...row,
48
- url: url(row.projectName),
49
- }));
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 };
50
61
  }
51
62
  async function listedEnvironments(cwd) {
52
- const own = await manage.listEnvironments(cwd);
53
63
  const { gitCommonDir } = await repositoryInfo(cwd);
54
64
  const states = await new AttachedStore(gitCommonDir).list();
55
65
  if (states.length === 0)
56
- return own;
66
+ return manage.listEnvironments(cwd);
67
+ // One docker ps serves the own and the attached worktrees.
57
68
  const dockerStatus = await manage.dockerStatuses(cwd);
69
+ const own = await manage.listEnvironments(cwd, dockerStatus);
58
70
  const rows = await Promise.all(states.map(async (state) => {
59
71
  const host = await attachedHost(state);
60
72
  return {
61
73
  name: state.name,
62
74
  branch: state.branch,
63
75
  path: state.path,
64
- status: state.status !== 'ready'
65
- ? state.status
66
- : host?.status,
76
+ ...setupState(state, host),
67
77
  projectName: host?.projectName ?? '-',
68
78
  dockerStatus: host === undefined
69
79
  ? 'missing'
@@ -92,6 +102,15 @@ export async function listEnvironmentNames(cwd) {
92
102
  .map(({ name, branch }) => ({ name, branch }))
93
103
  .sort((a, b) => a.name.localeCompare(b.name));
94
104
  }
105
+ /**
106
+ * The path of an environment's worktree, read from the state files only. It
107
+ * never asks Docker, so `wt path` and `wt cd` stay fast.
108
+ */
109
+ export async function environmentPath(name, cwd) {
110
+ const { gitCommonDir } = await repositoryInfo(cwd);
111
+ const state = await new AttachedStore(gitCommonDir).find(name) ?? await new StateStore(gitCommonDir).get(name);
112
+ return state.path;
113
+ }
95
114
  /**
96
115
  * Names of the environments whose Compose services run. It asks Docker once
97
116
  * and gives up after `timeout` milliseconds, so it suits shell completion.
@@ -131,9 +150,7 @@ export async function inspectEnvironment(name, cwd) {
131
150
  name: state.name,
132
151
  branch: state.branch,
133
152
  path: state.path,
134
- status: state.status !== 'ready'
135
- ? state.status
136
- : details.status,
153
+ ...setupState(state, details),
137
154
  error: state.error ?? details.error,
138
155
  host: { name: state.host.name, path: host?.path ?? '-' },
139
156
  };
@@ -25,3 +25,14 @@ export function formatDryRun(request) {
25
25
  'Dry run: nothing was changed.',
26
26
  ].join('\n');
27
27
  }
28
+ /** Runs an operation up to its confirmation, declines it, and returns what it asked. */
29
+ export async function preview(operation) {
30
+ let request;
31
+ await operation(async (asked) => {
32
+ request = asked;
33
+ return false;
34
+ });
35
+ if (request === undefined)
36
+ throw new Error('The operation finished without asking for confirmation.');
37
+ return request;
38
+ }
@@ -9,7 +9,7 @@ import { copyConfiguredPaths } from './copy-paths.js';
9
9
  import { startWithHooks, validateSourceHooks, validateWorktreeHooks } from './hooks.js';
10
10
  import { sourceLock, withLocks, worktreeLock } from './locks.js';
11
11
  import { checkInterrupted, withoutOperationSignal } from './process.js';
12
- import { runStep } from './progress.js';
12
+ import { cloneLabel, runStep } from './progress.js';
13
13
  const namePattern = /^\w[\w.-]*(?:\/\w[\w.-]*)*$/;
14
14
  export function validateCreateInput(name, options) {
15
15
  if (!namePattern.test(name))
@@ -100,7 +100,8 @@ async function createLocked(name, options, { root, gitCommonDir, repositoryRoot
100
100
  await nested?.checkedOut(target);
101
101
  const targetComposeFiles = await composeFilesForWorktree(source.files, source.workingDir, target);
102
102
  await validateWorktreeHooks(config.hooks, target);
103
- created.volumes = await runStep(progress, 'Cloning named Docker volumes (live writes may cause inconsistent data)', async () => cloneNamedVolumes(sources, created, root, image, async (_volume, volumes) => {
103
+ const { pause_source: pauseSource } = config.volumes;
104
+ created.volumes = await runStep(progress, cloneLabel('Cloning named Docker volumes', pauseSource), async () => cloneNamedVolumes(sources, created, root, { image, pauseSource }, async (_volume, volumes) => {
104
105
  created.volumes = volumes;
105
106
  await store.save(created);
106
107
  }));
@@ -3,10 +3,11 @@ import { access, realpath, unlink } from 'node:fs/promises';
3
3
  import { isAbsolute, relative, resolve, sep } from 'node:path';
4
4
  import process from 'node:process';
5
5
  import { createInterface } from 'node:readline/promises';
6
+ import { isDeepStrictEqual } from 'node:util';
6
7
  import { configPath, loadConfig } from '../config/load.js';
7
8
  import { cloneNamedVolumes, composeFilesForWorktree, docker, prepareVolumeCopy, resolveSourceVolumes, runCompose, writeVolumeOverride } from '../docker/compose.js';
8
- import { containerAddresses, domainsLabel, orbstackNetwork, parseDomains } from '../docker/orbstack.js';
9
- import { parsePorts } from '../docker/ports.js';
9
+ import { projectContainers } from '../docker/containers.js';
10
+ import { containerAddresses, orbstackNetwork } from '../docker/orbstack.js';
10
11
  import { WtError } from '../errors.js';
11
12
  import { git, repositoryInfo } from '../git/repository.js';
12
13
  import { AttachedStore, StateStore } from '../state/store.js';
@@ -15,7 +16,7 @@ import { copyConfiguredPaths } from './copy-paths.js';
15
16
  import { startWithHooks, validateSourceHooks, validateWorktreeHooks } from './hooks.js';
16
17
  import { sourceLock, withLocks, worktreeLock } from './locks.js';
17
18
  import { checkInterrupted, currentSignal } from './process.js';
18
- import { outputReporter, runStep } from './progress.js';
19
+ import { cloneLabel, outputReporter, runStep } from './progress.js';
19
20
  async function context(cwd) {
20
21
  const info = await repositoryInfo(cwd);
21
22
  return {
@@ -70,15 +71,20 @@ async function removeClonedVolumes(state, cwd, keep = []) {
70
71
  for (const volume of volumes)
71
72
  await removeOwnedVolume(volume, state.repositoryId, state.name, cwd);
72
73
  }
73
- export async function listEnvironments(cwd) {
74
+ /**
75
+ * Lists the managed environments with the status of their Compose project.
76
+ * It asks Docker only when there are environments and no `dockerStatus`
77
+ * lookup is given.
78
+ */
79
+ export async function listEnvironments(cwd, dockerStatus) {
74
80
  const { store } = await context(cwd);
75
81
  const states = await store.list();
76
82
  if (states.length === 0)
77
83
  return [];
78
- const dockerStatus = await dockerStatuses(cwd);
84
+ const status = dockerStatus ?? await dockerStatuses(cwd);
79
85
  return states.map(state => ({
80
86
  ...state,
81
- dockerStatus: dockerStatus(state.projectName),
87
+ dockerStatus: status(state.projectName),
82
88
  }));
83
89
  }
84
90
  /** Reads all Compose containers once and returns a summary lookup by project name. */
@@ -109,32 +115,11 @@ export async function inspectEnvironment(name, cwd) {
109
115
  const { state } = await managed(name, cwd);
110
116
  return inspectState(state, cwd);
111
117
  }
112
- export function parseContainers(output) {
113
- return output.split('\n').filter(Boolean).map((line) => {
114
- const [name, service, domains = '', ports = '', state, ...status] = line.split('\t');
115
- return {
116
- name,
117
- service: service || name,
118
- state: state ?? '',
119
- status: status.join('\t'),
120
- domains: parseDomains(domains),
121
- ports: parsePorts(ports),
122
- };
123
- }).sort((a, b) => a.service.localeCompare(b.service) || a.name.localeCompare(b.name));
124
- }
125
118
  export async function inspectState(state, cwd) {
126
- const [output, network] = await Promise.all([
127
- docker([
128
- 'ps',
129
- '-a',
130
- '--filter',
131
- `label=com.docker.compose.project=${state.projectName}`,
132
- '--format',
133
- `{{.Names}}\t{{.Label "com.docker.compose.service"}}\t{{.Label "${domainsLabel}"}}\t{{.Ports}}\t{{.State}}\t{{.Status}}`,
134
- ], cwd),
119
+ const [containers, network] = await Promise.all([
120
+ projectContainers(state.projectName, cwd),
135
121
  orbstackNetwork(cwd),
136
122
  ]);
137
- const containers = parseContainers(output);
138
123
  const addresses = network && containerAddresses(containers, state.projectName, network);
139
124
  return {
140
125
  ...state,
@@ -354,7 +339,7 @@ export async function resetLocked(state, store, config, cwd, { progress, nested
354
339
  : '';
355
340
  await store.save({ ...current, status: 'resetting' });
356
341
  try {
357
- const volumes = await runStep(progress, 'Cloning fresh Docker volumes', async () => cloneNamedVolumes(sources, state, sourceRoot, image, async (volume) => {
342
+ const volumes = await runStep(progress, cloneLabel('Cloning fresh Docker volumes', config.volumes.pause_source), async () => cloneNamedVolumes(sources, state, sourceRoot, { image, pauseSource: config.volumes.pause_source }, async (volume) => {
358
343
  current.retiredVolumes.push(volume);
359
344
  await store.save({ ...current, status: 'resetting' });
360
345
  }));
@@ -402,8 +387,14 @@ export async function exists(path) {
402
387
  throw error;
403
388
  }
404
389
  }
390
+ /**
391
+ * Throws `changed` when the saved state differs from `state`, which was read
392
+ * before the command waited for its locks. Key order does not matter, and a
393
+ * property set to `undefined` counts as absent, as `save` leaves it out.
394
+ */
405
395
  export async function checkUnchanged(store, state) {
406
- if (JSON.stringify(await store.get(state.name)) !== JSON.stringify(state))
396
+ const asSaved = (value) => JSON.parse(JSON.stringify(value));
397
+ if (!isDeepStrictEqual(asSaved(await store.get(state.name)), asSaved(state)))
407
398
  throw new WtError('changed', `Worktree ${state.name} changed while waiting. Retry the command.`);
408
399
  }
409
400
  async function downEnvironment(state, cwd, removeImages) {
@@ -1,7 +1,40 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import process from 'node:process';
1
3
  import { checkInterrupted } from './process.js';
4
+ const operationProgress = new AsyncLocalStorage();
5
+ /** Runs `operation` with `progress` as the reporter of its notes. */
6
+ export async function withProgress(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);
18
+ }
19
+ /**
20
+ * Shows a note as a finished step of the current operation, for code that is
21
+ * not passed a reporter, such as the lock store. Outside an operation the
22
+ * note goes to stderr.
23
+ */
24
+ export function reportNote(label) {
25
+ const progress = operationProgress.getStore()?.progress;
26
+ if (progress === undefined) {
27
+ process.stderr.write(`${label}\n`);
28
+ return;
29
+ }
30
+ progress({ label, status: 'started' });
31
+ progress({ label, status: 'completed' });
32
+ }
2
33
  export async function runStep(progress, label, operation) {
3
34
  checkInterrupted();
4
35
  progress?.({ label, status: 'started' });
36
+ for (const listener of operationProgress.getStore()?.stepListeners ?? [])
37
+ listener(label);
5
38
  try {
6
39
  const result = await operation();
7
40
  checkInterrupted();
@@ -21,6 +54,12 @@ export function hookLabel(name, hook, scope) {
21
54
  ? ''
22
55
  : `${scope} `}${name} hook (${detail})`;
23
56
  }
57
+ /** Label of a step that clones volumes, with whether the source containers can write meanwhile. */
58
+ export function cloneLabel(step, pauseSource) {
59
+ return `${step} (${pauseSource
60
+ ? 'source containers paused'
61
+ : 'live writes may cause inconsistent data'})`;
62
+ }
24
63
  export function outputReporter(progress, label) {
25
64
  if (progress === undefined)
26
65
  return undefined;
@@ -0,0 +1,111 @@
1
+ import process from 'node:process';
2
+ import { WtError } from '../errors.js';
3
+ import { repositoryInfo } from '../git/repository.js';
4
+ import { describeOwner, removeLock } from '../state/lock-file.js';
5
+ import { AttachedStore, StateStore } from '../state/store.js';
6
+ import { requestConfirmation } from './manage.js';
7
+ /**
8
+ * The locks that commands on worktree `name` take, or the repository locks
9
+ * when `name` is `undefined`. Commands on a worktree of a nested repository
10
+ * also lock its host worktree in the host repository, so it is found by
11
+ * either name.
12
+ */
13
+ async function heldLocks(name, cwd) {
14
+ const { gitCommonDir } = await repositoryInfo(cwd);
15
+ const store = new StateStore(gitCommonDir);
16
+ const attached = await new AttachedStore(gitCommonDir).list();
17
+ let locks;
18
+ if (name === undefined) {
19
+ const hosts = new Set(attached.map(state => state.host.gitCommonDir));
20
+ locks = [
21
+ store,
22
+ ...[...hosts].map(host => new StateStore(host)),
23
+ ].map(async (repository) => repository.inspectRepositoryLock());
24
+ }
25
+ else {
26
+ const lower = name.toLowerCase();
27
+ const nested = attached.find(state => state.name.toLowerCase() === lower || state.host.name.toLowerCase() === lower);
28
+ locks = nested === undefined
29
+ ? [
30
+ store.inspectWorktreeLock(name),
31
+ ]
32
+ : [
33
+ store.inspectWorktreeLock(nested.name),
34
+ new StateStore(nested.host.gitCommonDir).inspectWorktreeLock(nested.host.name),
35
+ ];
36
+ }
37
+ return (await Promise.all(locks)).filter(held => held !== undefined);
38
+ }
39
+ function statusText(held) {
40
+ if (held.status === 'exited' || held.status === 'replaced')
41
+ return 'No longer runs';
42
+ if (held.owner === undefined)
43
+ return 'Unknown: the lock file does not name its owner';
44
+ return held.owner.host === undefined
45
+ ? 'Unknown: an older wt version took the lock'
46
+ : `Unknown: wt cannot check whether it still runs on ${held.owner.host}`;
47
+ }
48
+ function lockDetails(held) {
49
+ const { owner, takeover } = held;
50
+ const takeoverOwner = takeover?.owner === undefined
51
+ ? ''
52
+ : ` by ${describeOwner(takeover.owner)}`;
53
+ return [
54
+ { label: 'Lock', value: held.path },
55
+ ...(owner === undefined
56
+ ? []
57
+ : [
58
+ {
59
+ label: 'Owner',
60
+ value: describeOwner(owner),
61
+ },
62
+ ]),
63
+ {
64
+ label: 'Status',
65
+ value: statusText(held),
66
+ },
67
+ ...(takeover === undefined
68
+ ? []
69
+ : [
70
+ { label: 'Takeover', value: `${takeover.path}${takeoverOwner}` },
71
+ ]),
72
+ ];
73
+ }
74
+ function unlockRequest(name, locks) {
75
+ const plural = locks.length > 1
76
+ ? 's'
77
+ : '';
78
+ return {
79
+ title: name === undefined
80
+ ? `Remove the repository lock${plural}?`
81
+ : `Remove the lock${plural} of worktree ${name}?`,
82
+ details: locks.flatMap(lockDetails),
83
+ note: 'Remove a lock only when its command no longer runs: two wt commands that change the same worktrees at once can break them.',
84
+ action: 'Remove',
85
+ };
86
+ }
87
+ /**
88
+ * Removes the lock of worktree `name`, or the repository lock when `name` is
89
+ * `undefined`, that a command left behind when it was killed. Asks first,
90
+ * unless `force` is set, and refuses while the command that holds a lock
91
+ * still runs. Returns whether the locks were removed.
92
+ */
93
+ export async function unlockEnvironment(name, cwd, force = false, confirm) {
94
+ const locks = await heldLocks(name, cwd);
95
+ if (locks.length === 0) {
96
+ throw new WtError('not_locked', name === undefined
97
+ ? 'Worktree operations are not locked.'
98
+ : `Worktree ${name} is not locked.`);
99
+ }
100
+ for (const held of locks.flatMap(lock => [lock, lock.takeover])) {
101
+ if (held?.status === 'running')
102
+ throw new WtError('locked', `The lock at ${held.path} is held by ${describeOwner(held.owner)}, which still runs. Retry when it exits.`);
103
+ }
104
+ if (!force && confirm === undefined && !process.stdin.isTTY)
105
+ throw new WtError('confirmation_required', 'wt unlock requires an interactive terminal or --force. Run it with --dry-run to see what it removes.');
106
+ if (!force && !await requestConfirmation(unlockRequest(name, locks), confirm))
107
+ return false;
108
+ for (const held of locks)
109
+ await removeLock(held);
110
+ return true;
111
+ }
@@ -0,0 +1,46 @@
1
+ /*
2
+ * The shell function behind `wt cd`. A program cannot change the directory of
3
+ * the shell that runs it, so `wt shell-init` prints a function named `wt` for
4
+ * the shell's startup file. It runs `wt cd [name]` as `cd "$(wt path [name])"`
5
+ * and passes every other command to the wt program.
6
+ *
7
+ * It is not part of the completion script, because that script may be
8
+ * installed as a file that the shell only loads when it completes `wt`.
9
+ *
10
+ * The same function works in zsh and bash. It finds the command after any
11
+ * `-w` options, so `wt -w <dir> cd` works too, and passes `wt cd --help` on.
12
+ * It never expands an empty array, which bash 3.2 rejects under `set -u`, and
13
+ * never indexes an array, which zsh's KSH_ARRAYS option changes.
14
+ */
15
+ function shellFunction(shell) {
16
+ return `# wt shell function for ${shell}. Load it with: eval "$(wt shell-init ${shell})"
17
+ # It runs wt cd [name] as cd "$(wt path [name])" and passes everything else to wt.
18
+ wt() {
19
+ local -a prefix
20
+ local arg dir
21
+ prefix=(wt)
22
+ while (( $# )); do
23
+ case $1 in
24
+ -w | --working-dir) (( $# > 1 )) || break; prefix+=("$1" "$2"); shift 2 ;;
25
+ -w?* | --working-dir=*) prefix+=("$1"); shift ;;
26
+ *) break ;;
27
+ esac
28
+ done
29
+ if [[ \${1-} != cd ]]; then
30
+ command "\${prefix[@]}" "$@"
31
+ return
32
+ fi
33
+ shift
34
+ for arg; do
35
+ case $arg in
36
+ -h | --help) command "\${prefix[@]}" cd "$@"; return ;;
37
+ esac
38
+ done
39
+ dir=$(WT_FORMAT=text command "\${prefix[@]}" path "$@") && builtin cd -- "$dir"
40
+ }
41
+ `;
42
+ }
43
+ export const shellInitScripts = {
44
+ zsh: shellFunction('zsh'),
45
+ bash: shellFunction('bash'),
46
+ };