@n-seiji/hop 0.0.0-stage → 0.3.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/cli.js ADDED
@@ -0,0 +1,630 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ normalizeCliArgs,
4
+ isRunningAsCompiledBinary,
5
+ isUpdateRequest,
6
+ isHelpRequest,
7
+ isVersionRequest,
8
+ dispatchCliArgs,
9
+ wantsJson,
10
+ reportFatalError,
11
+ VERSION
12
+ } from "./cli-nrb5hg6g.js";
13
+ import {
14
+ GIT_EXECUTABLE_OVERRIDE_ENV,
15
+ GIT_NOT_FOUND_ERROR_CODE,
16
+ gitExecutableCandidates,
17
+ gitNotFoundMessage,
18
+ describeFatalError
19
+ } from "./cli-n74f2vav.js";
20
+ import {
21
+ createTermPort
22
+ } from "./cli-9b4r23jn.js";
23
+ import {
24
+ render,
25
+ reportResult
26
+ } from "./cli-dbzx9nzg.js";
27
+ import {
28
+ UPSTREAM_FORMAT,
29
+ parseUpstreamStates
30
+ } from "./cli-btqjpf1q.js";
31
+ import {
32
+ EXIT_SUCCESS,
33
+ EXIT_USAGE_ERROR,
34
+ EXIT_CANCELLED,
35
+ ok
36
+ } from "./cli-77yanq37.js";
37
+ import {
38
+ isWithinOrSelf
39
+ } from "./cli-a56b2ar0.js";
40
+
41
+ // src/cli-args.ts
42
+ var DASH = "-";
43
+ var FLAG_PREFIX = "--";
44
+ var NEGATION_PREFIX = "no-";
45
+ var camelize = (name) => name.replaceAll(/-(?<letter>[a-z])/gu, (_match, letter) => letter.toUpperCase());
46
+ var parseBooleanValue = (value) => value !== "false";
47
+ var parseFlagToken = (token, next, spec, state) => {
48
+ const nextIsValue = next !== undefined && !next.startsWith(DASH);
49
+ const isLong = token.startsWith(FLAG_PREFIX);
50
+ const body = token.slice(isLong ? FLAG_PREFIX.length : DASH.length);
51
+ if (isLong && body.startsWith(NEGATION_PREFIX)) {
52
+ const name = camelize(body.slice(NEGATION_PREFIX.length));
53
+ if (spec.booleans.has(name)) {
54
+ state.booleans[name] = false;
55
+ }
56
+ return 0;
57
+ }
58
+ const equalsIndex = body.indexOf("=");
59
+ const rawName = equalsIndex === -1 ? body : body.slice(0, equalsIndex);
60
+ const inlineValue = equalsIndex === -1 ? undefined : body.slice(equalsIndex + 1);
61
+ const name = isLong ? camelize(rawName) : rawName.slice(-1);
62
+ if (spec.booleans.has(name)) {
63
+ state.booleans[name] = inlineValue === undefined || parseBooleanValue(inlineValue);
64
+ return 0;
65
+ }
66
+ if (spec.strings.has(name)) {
67
+ if (inlineValue !== undefined) {
68
+ state.strings[name] = inlineValue;
69
+ return 0;
70
+ }
71
+ state.strings[name] = nextIsValue ? next : "";
72
+ return nextIsValue ? 1 : 0;
73
+ }
74
+ return inlineValue === undefined && nextIsValue ? 1 : 0;
75
+ };
76
+ var parseCliArgs = (tokens, spec) => {
77
+ const flagSpec = {
78
+ booleans: new Set(spec.booleans),
79
+ strings: new Set(spec.strings)
80
+ };
81
+ const state = { booleans: {}, strings: {}, positionals: [] };
82
+ for (let index = 0;index < tokens.length; index += 1) {
83
+ const token = tokens[index] ?? "";
84
+ if (token === FLAG_PREFIX) {
85
+ state.positionals.push(...tokens.slice(index + 1));
86
+ break;
87
+ }
88
+ if (token === DASH || !token.startsWith(DASH)) {
89
+ state.positionals.push(token);
90
+ } else {
91
+ index += parseFlagToken(token, tokens[index + 1], flagSpec, state);
92
+ }
93
+ }
94
+ const positionals = {};
95
+ for (const [index, { name, required }] of (spec.positionals ?? []).entries()) {
96
+ const value = state.positionals[index];
97
+ if (value === undefined && required) {
98
+ throw new Error(`Missing required positional argument: ${name.toUpperCase()}`);
99
+ }
100
+ positionals[name] = value;
101
+ }
102
+ const booleans = {};
103
+ for (const name of flagSpec.booleans) {
104
+ booleans[name] = state.booleans[name] ?? false;
105
+ }
106
+ return { positionals, booleans, strings: state.strings };
107
+ };
108
+
109
+ // src/infra/fs.ts
110
+ import { mkdir as mkdirFs, readdir, realpath as realpathFs } from "node:fs/promises";
111
+ var createFsPort = () => ({
112
+ async exists(path) {
113
+ try {
114
+ await realpathFs(path);
115
+ return true;
116
+ } catch {
117
+ return false;
118
+ }
119
+ },
120
+ realpath(path) {
121
+ return realpathFs(path);
122
+ },
123
+ async mkdir(path) {
124
+ await mkdirFs(path, { recursive: true });
125
+ },
126
+ async listDirNames(path) {
127
+ try {
128
+ const entries = await readdir(path, { withFileTypes: true });
129
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
130
+ } catch {
131
+ return [];
132
+ }
133
+ }
134
+ });
135
+
136
+ // src/infra/git.ts
137
+ import { execFile as execFileCb } from "node:child_process";
138
+ import { promisify } from "node:util";
139
+
140
+ // src/domain/dirty.ts
141
+ var filterOutNestedWorktreePaths = (relativePaths, targetPath, otherWorktreePaths) => {
142
+ const target = stripTrailingSlash(targetPath);
143
+ const others = otherWorktreePaths.map((path) => stripTrailingSlash(path)).filter((path) => path !== target);
144
+ if (others.length === 0) {
145
+ return [...relativePaths];
146
+ }
147
+ return relativePaths.filter((relativePath) => {
148
+ const absolutePath = stripTrailingSlash(`${target}/${relativePath}`);
149
+ return !others.some((other) => isWithinOrSelf(other, absolutePath));
150
+ });
151
+ };
152
+ var isDirtyFromStatus = (statusOutput, targetPath, otherWorktreePaths) => {
153
+ const paths = parseStatusPaths(statusOutput);
154
+ return filterOutNestedWorktreePaths(paths, targetPath, otherWorktreePaths).length > 0;
155
+ };
156
+ var stripTrailingSlash = (path) => path.endsWith("/") ? path.slice(0, -1) : path;
157
+ var STATUS_CODE_WIDTH = 3;
158
+ var RECORDS_PER_RENAME_OR_COPY = 2;
159
+ var RECORDS_PER_ORDINARY_ENTRY = 1;
160
+ var isRenameOrCopyCode = (code) => code.includes("R") || code.includes("C");
161
+ var parseStatusPaths = (statusOutput) => {
162
+ const records = statusOutput.split("\x00").filter((record) => record.length > 0);
163
+ const paths = [];
164
+ let index = 0;
165
+ while (index < records.length) {
166
+ const record = records[index];
167
+ if (record === undefined || record.length <= STATUS_CODE_WIDTH) {
168
+ index += RECORDS_PER_ORDINARY_ENTRY;
169
+ } else {
170
+ paths.push(record.slice(STATUS_CODE_WIDTH));
171
+ const code = record.slice(0, STATUS_CODE_WIDTH - 1);
172
+ index += isRenameOrCopyCode(code) ? RECORDS_PER_RENAME_OR_COPY : RECORDS_PER_ORDINARY_ENTRY;
173
+ }
174
+ }
175
+ return paths;
176
+ };
177
+
178
+ // src/infra/executable.ts
179
+ import { constants } from "node:fs";
180
+ import { access, stat } from "node:fs/promises";
181
+ var isExecutableFile = async (path) => {
182
+ try {
183
+ const stats = await stat(path);
184
+ if (!stats.isFile()) {
185
+ return false;
186
+ }
187
+ await access(path, constants.X_OK);
188
+ return true;
189
+ } catch {
190
+ return false;
191
+ }
192
+ };
193
+ var firstExecutable = async (candidates) => {
194
+ const probes = candidates.map(async (candidate) => await isExecutableFile(candidate) ? candidate : null);
195
+ for (const probe of probes) {
196
+ const found = await probe;
197
+ if (found !== null) {
198
+ return found;
199
+ }
200
+ }
201
+ return null;
202
+ };
203
+
204
+ // src/infra/git-executable.ts
205
+ var resolveGitExecutable = async (env) => {
206
+ const candidates = gitExecutableCandidates({
207
+ override: env[GIT_EXECUTABLE_OVERRIDE_ENV],
208
+ path: env.PATH
209
+ });
210
+ const found = await firstExecutable(candidates);
211
+ if (found !== null) {
212
+ return found;
213
+ }
214
+ throw Object.assign(new Error(gitNotFoundMessage(candidates)), {
215
+ code: GIT_NOT_FOUND_ERROR_CODE
216
+ });
217
+ };
218
+ var createGitExecutableResolver = (env) => {
219
+ let cached = null;
220
+ return () => {
221
+ cached ??= resolveGitExecutable(env);
222
+ return cached;
223
+ };
224
+ };
225
+
226
+ // src/infra/git.ts
227
+ var execFile = promisify(execFileCb);
228
+ var gitExecutable = createGitExecutableResolver(process.env);
229
+ var MAX_BUFFER_BYTES = 64 * 1024 * 1024;
230
+ var GIT_ANCESTOR_EXIT_CODE = 1;
231
+ var run = async (cwd, args) => {
232
+ const { stdout } = await execFile(await gitExecutable(), [...args], {
233
+ cwd,
234
+ maxBuffer: MAX_BUFFER_BYTES
235
+ });
236
+ return stdout;
237
+ };
238
+ var failedWithExitCode = (error, code) => typeof error === "object" && error !== null && ("code" in error) && error.code === code;
239
+ var parseRemoteRefs = (out) => {
240
+ const parsed = [];
241
+ for (const line of out.split(`
242
+ `)) {
243
+ const match = /^refs\/remotes\/(?<remote>[^/]+)\/(?<branchName>.+)$/u.exec(line.trim());
244
+ if (match?.groups?.remote !== undefined && match.groups.branchName !== undefined) {
245
+ parsed.push({
246
+ remote: match.groups.remote,
247
+ branchName: match.groups.branchName
248
+ });
249
+ }
250
+ }
251
+ return parsed;
252
+ };
253
+ var createWorktreeMethods = () => ({
254
+ listWorktreesPorcelain(cwd) {
255
+ return run(cwd, ["worktree", "list", "--porcelain", "-z"]);
256
+ },
257
+ async commonDir(cwd) {
258
+ const out = await run(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
259
+ return out.trim();
260
+ },
261
+ async isDirty(path, otherWorktreePaths) {
262
+ const status = await run(path, ["status", "--porcelain", "-z", "--untracked-files=all"]);
263
+ return isDirtyFromStatus(status, path, otherWorktreePaths);
264
+ },
265
+ async addWorktree(cwd, path, branch, options) {
266
+ const args = ["worktree", "add"];
267
+ if (options.createBranch) {
268
+ if (options.track !== undefined) {
269
+ args.push("--track");
270
+ }
271
+ args.push("-b", branch);
272
+ }
273
+ args.push(path);
274
+ if (options.track !== undefined) {
275
+ args.push(options.track);
276
+ } else if (!options.createBranch) {
277
+ args.push(branch);
278
+ }
279
+ await run(cwd, args);
280
+ },
281
+ async removeWorktree(cwd, path, force) {
282
+ const args = ["worktree", "remove"];
283
+ if (force) {
284
+ args.push("--force");
285
+ }
286
+ args.push(path);
287
+ await run(cwd, args);
288
+ },
289
+ async upstreamStates(cwd) {
290
+ try {
291
+ const out = await run(cwd, ["for-each-ref", `--format=${UPSTREAM_FORMAT}`, "refs/heads/"]);
292
+ return parseUpstreamStates(out);
293
+ } catch {
294
+ return new Map;
295
+ }
296
+ }
297
+ });
298
+ var createBranchMethods = () => ({
299
+ async listBranches(cwd) {
300
+ const out = await run(cwd, ["for-each-ref", "--format=%(refname:short)", "refs/heads/"]);
301
+ return out.split(`
302
+ `).map((line) => line.trim()).filter((line) => line.length > 0);
303
+ },
304
+ async remotesWithBranch(cwd, branch) {
305
+ const out = await run(cwd, ["for-each-ref", "--format=%(refname)", "refs/remotes/"]);
306
+ const remotes = new Set;
307
+ for (const { remote, branchName } of parseRemoteRefs(out)) {
308
+ if (branchName === branch) {
309
+ remotes.add(remote);
310
+ }
311
+ }
312
+ return [...remotes];
313
+ },
314
+ async listRemoteBranches(cwd) {
315
+ const out = await run(cwd, ["for-each-ref", "--format=%(refname)", "refs/remotes/"]);
316
+ const branches = new Set;
317
+ for (const { branchName } of parseRemoteRefs(out)) {
318
+ if (branchName !== "HEAD") {
319
+ branches.add(branchName);
320
+ }
321
+ }
322
+ return [...branches];
323
+ },
324
+ async switchBranch(cwd, ref, options = {}) {
325
+ const args = ["switch"];
326
+ if (options.createBranch) {
327
+ if (options.track !== undefined) {
328
+ args.push("--track");
329
+ }
330
+ args.push("-c", ref);
331
+ if (options.track !== undefined) {
332
+ args.push(options.track);
333
+ }
334
+ } else {
335
+ args.push("--end-of-options", ref);
336
+ }
337
+ await run(cwd, args);
338
+ },
339
+ async deleteBranch(cwd, branch) {
340
+ await run(cwd, ["branch", "-D", "--end-of-options", branch]);
341
+ },
342
+ async detachHead(cwd) {
343
+ await run(cwd, ["switch", "--detach", "HEAD"]);
344
+ }
345
+ });
346
+ var createGarbagePolicyMethods = () => ({
347
+ async resolveDefaultBranchRef(cwd) {
348
+ try {
349
+ const out = await run(cwd, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
350
+ const ref = out.trim();
351
+ if (ref.length > 0) {
352
+ return ref;
353
+ }
354
+ } catch {}
355
+ try {
356
+ await run(cwd, ["rev-parse", "--verify", "--quiet", "main"]);
357
+ return "main";
358
+ } catch {}
359
+ try {
360
+ await run(cwd, ["rev-parse", "--verify", "--quiet", "master"]);
361
+ return "master";
362
+ } catch {
363
+ return null;
364
+ }
365
+ },
366
+ async isAncestor(cwd, branch, ref) {
367
+ try {
368
+ await run(cwd, ["merge-base", "--is-ancestor", "--end-of-options", branch, ref]);
369
+ return true;
370
+ } catch (error) {
371
+ if (failedWithExitCode(error, GIT_ANCESTOR_EXIT_CODE)) {
372
+ return false;
373
+ }
374
+ return "unknown";
375
+ }
376
+ },
377
+ async hasEquivalentCommits(cwd, branch, ref) {
378
+ try {
379
+ const out = await run(cwd, ["cherry", "--end-of-options", ref, branch]);
380
+ return !out.split(`
381
+ `).some((line) => line.startsWith("+"));
382
+ } catch {
383
+ return "unknown";
384
+ }
385
+ }
386
+ });
387
+ var createGitPort = () => ({
388
+ ...createWorktreeMethods(),
389
+ ...createBranchMethods(),
390
+ ...createGarbagePolicyMethods()
391
+ });
392
+
393
+ // src/usage.ts
394
+ var USAGE = `Usage: hop [command] [options]
395
+
396
+ hop Pick a worktree/branch interactively and cd into it (TTY); lists worktrees otherwise
397
+ hop <branch> Create-or-jump: cd into <branch>'s worktree (pass --create to create a missing one)
398
+ hop root cd into the root clone
399
+ hop - cd back to the previous worktree
400
+ hop -- <branch> Escape a branch name that collides with a reserved command (ls/rm/clean/root/init/help)
401
+
402
+ hop ls [--json] List worktrees (dirty, ahead/behind, kind)
403
+ hop rm <branch> Remove a worktree, keeping the branch
404
+ hop clean Auto-detect and remove garbage worktrees
405
+ hop root <branch> Temporarily switch the root clone (for verification)
406
+ hop root - Switch the root clone back
407
+ hop init zsh Print the zsh shell integration (eval "$(hop init zsh)")
408
+
409
+ hop --update Replace a standalone binary with the latest release (else: how to update)
410
+ hop --update --check Only report whether an update is available; change nothing
411
+ hop --version Print hop's version
412
+
413
+ Interactive picker keys:
414
+ Enter cd into the selected candidate
415
+ Tab, →, Ctrl+L, Ctrl+F Open the action panel, as a column beside the list
416
+ (stacks below it instead on narrow terminals)
417
+ Ctrl+X Delete the selected worktree (y/N confirmation)
418
+ Ctrl+R Switch the root clone to the selected branch (y/N first for an external worktree)
419
+ ↑/↓, Ctrl+P/N, Ctrl+K Move the selection (arrow, emacs, and vim keys all work)
420
+ Esc Cancel (exit 0, no output)
421
+ Ctrl+C Cancel like an interrupt (exit 130, same as SIGINT)
422
+ In the action panel: same up/down movement keys, Enter to run the highlighted
423
+ action, c/d/r to run cd/delete/switchRoot directly, Esc/Tab/←/Ctrl+H to close
424
+
425
+ Options:
426
+ --create Create the worktree when jumping to a branch without one (always required, TTY or not)
427
+ --json Output JSON instead of plain text
428
+ --force Force removal even if the worktree is dirty (hop rm)
429
+ --ext Also include external worktrees in the auto-cleanup scope (hop clean)
430
+ --yes Skip confirmation and execute (hop clean)
431
+ --dry-run Only report candidates as JSON, without deleting (hop clean)
432
+ --with-branch Also delete the branch when cleaning (hop clean)
433
+ -h, --help Show this help and exit
434
+ `;
435
+
436
+ // src/cli.ts
437
+ var ports = null;
438
+ var getPorts = () => {
439
+ ports ??= { git: createGitPort(), fs: createFsPort(), term: createTermPort() };
440
+ return ports;
441
+ };
442
+ var JSON_FLAG = "json";
443
+ var runLs = async (json) => {
444
+ const [{ ls }, { reportLs }] = await Promise.all([
445
+ import("./ls-hvwtaxv8.js"),
446
+ import("./render-ls-str0w03j.js")
447
+ ]);
448
+ const { git, fs } = getPorts();
449
+ reportLs(await ls(git, fs, { cwd: process.cwd() }), json);
450
+ };
451
+ var runJump = async (target, options) => {
452
+ const { jump } = await import("./jump-3262fxj4.js");
453
+ const { git, fs } = getPorts();
454
+ const result = await jump(git, fs, {
455
+ cwd: process.cwd(),
456
+ target,
457
+ create: options.create,
458
+ ...options.track === undefined ? {} : { track: options.track }
459
+ });
460
+ reportResult("jump", result, options.json);
461
+ };
462
+ var runInteractivePick = async (json) => {
463
+ const {
464
+ createPickerCallbacks,
465
+ loadPickCandidates,
466
+ renderSwitchRootOutcome,
467
+ runInteractivePicker
468
+ } = await import("./cli-pick-aj567n01.js");
469
+ const { git, fs } = getPorts();
470
+ const candidates = await loadPickCandidates(git, fs, json);
471
+ if (candidates === null) {
472
+ return;
473
+ }
474
+ let lastSwitchRootOutcome = null;
475
+ const callbacks = createPickerCallbacks(git, fs, json, (outcome) => {
476
+ lastSwitchRootOutcome = outcome;
477
+ });
478
+ const outcome = await runInteractivePicker(candidates, callbacks);
479
+ if (outcome.type === "cancelled") {
480
+ process.exitCode = outcome.reason === "esc" ? EXIT_SUCCESS : EXIT_CANCELLED;
481
+ return;
482
+ }
483
+ if (outcome.type === "path") {
484
+ renderSwitchRootOutcome(outcome.path, lastSwitchRootOutcome, json);
485
+ return;
486
+ }
487
+ const selected = outcome.candidate;
488
+ if (selected.kind === "worktree") {
489
+ const result = ok({
490
+ path: selected.worktree.path,
491
+ data: { branch: selected.worktree.branch, created: false }
492
+ });
493
+ render("pick", result, json);
494
+ return;
495
+ }
496
+ await runJump(selected.branch, { create: true, json });
497
+ };
498
+ var JUMP_ARGS = {
499
+ positionals: [{ name: "target", required: false }],
500
+ booleans: ["create", JSON_FLAG],
501
+ strings: ["track"]
502
+ };
503
+ var runJumpFromArgs = async (tokens) => {
504
+ const args = parseCliArgs(tokens, JUMP_ARGS);
505
+ const json = args.booleans.json ?? false;
506
+ const { target } = args.positionals;
507
+ if (target === undefined) {
508
+ if (getPorts().term.isTTY()) {
509
+ await runInteractivePick(json);
510
+ return;
511
+ }
512
+ await runLs(json);
513
+ return;
514
+ }
515
+ const { track } = args.strings;
516
+ await runJump(target, {
517
+ create: args.booleans.create ?? false,
518
+ json,
519
+ ...track === undefined ? {} : { track }
520
+ });
521
+ };
522
+ var runRm = async (tokens) => {
523
+ const args = parseCliArgs(tokens, {
524
+ positionals: [{ name: "branch", required: true }],
525
+ booleans: ["force", JSON_FLAG]
526
+ });
527
+ const { rm } = await import("./rm-5v1exwwn.js");
528
+ const { git, fs } = getPorts();
529
+ const result = await rm(git, fs, {
530
+ cwd: process.cwd(),
531
+ branch: args.positionals.branch ?? "",
532
+ force: args.booleans.force ?? false
533
+ });
534
+ reportResult("rm", result, args.booleans.json ?? false);
535
+ };
536
+ var runClean = async (tokens) => {
537
+ const args = parseCliArgs(tokens, {
538
+ booleans: ["ext", "withBranch", "dryRun", "yes", JSON_FLAG]
539
+ });
540
+ const { clean } = await import("./clean-e451psab.js");
541
+ const { git, fs, term } = getPorts();
542
+ const result = await clean(git, fs, term, {
543
+ cwd: process.cwd(),
544
+ ext: args.booleans.ext ?? false,
545
+ withBranch: args.booleans.withBranch ?? false,
546
+ dryRun: args.booleans.dryRun ?? false,
547
+ yes: args.booleans.yes ?? false
548
+ });
549
+ reportResult("clean", result, args.booleans.json ?? false);
550
+ };
551
+ var runRoot = async (tokens) => {
552
+ const args = parseCliArgs(tokens, {
553
+ positionals: [{ name: "branch", required: false }],
554
+ booleans: [JSON_FLAG],
555
+ strings: ["track"]
556
+ });
557
+ const { root } = await import("./root-q4zr60sk.js");
558
+ const { git, fs } = getPorts();
559
+ const { branch } = args.positionals;
560
+ const { track } = args.strings;
561
+ const result = await root(git, fs, {
562
+ cwd: process.cwd(),
563
+ ...branch === undefined ? {} : { target: branch },
564
+ ...track === undefined ? {} : { track }
565
+ });
566
+ reportResult("root", result, args.booleans.json ?? false);
567
+ };
568
+ var runInit = async (tokens) => {
569
+ const args = parseCliArgs(tokens, {
570
+ positionals: [{ name: "shell", required: true }]
571
+ });
572
+ const shell = args.positionals.shell ?? "";
573
+ if (shell !== "zsh") {
574
+ process.stderr.write(`Unsupported shell: ${shell}
575
+ `);
576
+ process.exitCode = EXIT_USAGE_ERROR;
577
+ return;
578
+ }
579
+ const { renderInit } = await import("./init-xfq1pt2h.js");
580
+ process.stdout.write(renderInit());
581
+ };
582
+ var RESERVED_COMMANDS = {
583
+ ls: (tokens) => runLs(parseCliArgs(tokens, { booleans: [JSON_FLAG] }).booleans.json ?? false),
584
+ rm: runRm,
585
+ clean: runClean,
586
+ root: runRoot,
587
+ init: runInit
588
+ };
589
+ var ARGV_USER_ARGS_START = 2;
590
+ var dispatchAndRun = async (dispatch) => {
591
+ const command = dispatch.kind === "reserved" ? RESERVED_COMMANDS[dispatch.name] : undefined;
592
+ await (command === undefined ? runJumpFromArgs(dispatch.args) : command(dispatch.args));
593
+ };
594
+ var runUpdate = async (rawArgs) => {
595
+ const update = await import("./cli-update-82cttjfc.js");
596
+ await update.runUpdate(rawArgs, getPorts().term);
597
+ };
598
+ var main = async () => {
599
+ const rawArgs = normalizeCliArgs(process.argv.slice(ARGV_USER_ARGS_START), process.argv0, isRunningAsCompiledBinary());
600
+ if (isHelpRequest(rawArgs)) {
601
+ process.stderr.write(USAGE);
602
+ process.exitCode = 0;
603
+ return;
604
+ }
605
+ if (isVersionRequest(rawArgs)) {
606
+ process.stdout.write(`${VERSION}
607
+ `);
608
+ process.exitCode = EXIT_SUCCESS;
609
+ return;
610
+ }
611
+ if (isUpdateRequest(rawArgs)) {
612
+ await runUpdate(rawArgs);
613
+ return;
614
+ }
615
+ const dispatch = dispatchCliArgs(rawArgs, Object.keys(RESERVED_COMMANDS));
616
+ try {
617
+ await dispatchAndRun(dispatch);
618
+ } catch (error) {
619
+ const command = dispatch.kind === "reserved" ? dispatch.name : "jump";
620
+ reportFatalError(command, wantsJson(rawArgs), error);
621
+ }
622
+ };
623
+ try {
624
+ await main();
625
+ } catch (error) {
626
+ const fatal = describeFatalError(error);
627
+ process.stderr.write(`hop: ${fatal.message}
628
+ `);
629
+ process.exitCode = fatal.exitCode;
630
+ }
@@ -0,0 +1,64 @@
1
+ // src/commands/init.ts
2
+ var ZSH_TEMPLATE = `# hop shell integration for zsh.
3
+ # Usage: eval "$(hop init zsh)"
4
+ hop() {
5
+ # stdout is not a terminal (e.g. inside p=$(hop ...)): a cd here would only
6
+ # affect the capturing subshell and leave the caller with an empty string,
7
+ # so just print the path.
8
+ if [[ ! -t 1 ]]; then
9
+ command hop "$@"
10
+ return $?
11
+ fi
12
+
13
+ if [[ "$1" == "-" ]]; then
14
+ cd - > /dev/null || return $?
15
+ return 0
16
+ fi
17
+
18
+ local should_cd=1
19
+ case "$1" in
20
+ ls|rm|clean|init) should_cd=0 ;;
21
+ --) ;; # "hop -- <branch>" escapes a reserved word; still a jump, so cd.
22
+ "")
23
+ # Bare "hop": picker on a real terminal (cd on success), ls fallback
24
+ # otherwise (prints a listing, not a path — don't cd). fd 2/0 are what
25
+ # the child inherits unchanged; fd 1 is about to become the capture
26
+ # pipe below, so it can't be checked here — this mirrors hop's own
27
+ # isTTY() check (stderr + stdin), not stdout.
28
+ if [[ -t 2 && -t 0 ]]; then
29
+ should_cd=1
30
+ else
31
+ should_cd=0
32
+ fi
33
+ ;;
34
+ --*) should_cd=0 ;;
35
+ esac
36
+
37
+ # Nothing to cd into: run hop with the terminal as its stdout, so a listing
38
+ # keeps its colors (hop only colors stdout when it is a terminal).
39
+ if [[ $should_cd -eq 0 ]]; then
40
+ command hop "$@"
41
+ return $?
42
+ fi
43
+
44
+ # "status" is a zsh read-only special parameter (mirrors $?); using it as a
45
+ # local name fails with "read-only variable: status". Use "rc" instead, and
46
+ # declare it before the command substitution so the exit code isn't
47
+ # clobbered by "local"'s own exit status.
48
+ local out rc
49
+ out="$(command hop "$@")"
50
+ rc=$?
51
+
52
+ if [[ $rc -eq 0 && $should_cd -eq 1 && -n "$out" ]]; then
53
+ cd -- "$out" || return $?
54
+ elif [[ -n "$out" ]]; then
55
+ print -r -- "$out"
56
+ fi
57
+
58
+ return $rc
59
+ }
60
+ `;
61
+ var renderInit = () => ZSH_TEMPLATE;
62
+ export {
63
+ renderInit
64
+ };