diff --git a/.changeset/cool-turtles-tickle.md b/.changeset/cool-turtles-tickle.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/cool-turtles-tickle.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/website/astro.config.mjs b/website/astro.config.mjs index f67ac169c..0bccd1f3c 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -91,6 +91,15 @@ export default defineConfig({ { label: "Layout and display", slug: "docs/configure/layout-and-display" }, ], }, + { + label: "Extend", + items: [ + { label: "Extensions", slug: "docs/extend/extensions" }, + { label: "Extension API", slug: "docs/extend/extension-api" }, + { label: "VCS adapters", slug: "docs/extend/vcs-adapters" }, + { label: "Custom sidebars", slug: "docs/extend/custom-sidebars" }, + ], + }, { label: "Reference", items: [ diff --git a/website/src/content/docs/docs/configure/configuration.md b/website/src/content/docs/docs/configure/configuration.md index 6ace060b2..9fdd1bf78 100644 --- a/website/src/content/docs/docs/configure/configuration.md +++ b/website/src/content/docs/docs/configure/configuration.md @@ -59,4 +59,4 @@ Command sections are named after the input Hunk parses, which is not always the When you change view preferences and quit, Hunk can offer to persist them. It writes to an existing repository config when one exists; otherwise it keeps personal view choices in the user config. Set `prompt_save_view_preferences = false` to disable that prompt. -The [config reference](/docs/reference/config/) lists every key, default, and alias. +The [config reference](/docs/reference/config/) lists every key, default, and alias. The root-only `[extensions]` table has its own guide: [Extensions](/docs/extend/extensions/). diff --git a/website/src/content/docs/docs/extend/custom-sidebars.md b/website/src/content/docs/docs/extend/custom-sidebars.md new file mode 100644 index 000000000..09d17eca0 --- /dev/null +++ b/website/src/content/docs/docs/extend/custom-sidebars.md @@ -0,0 +1,198 @@ +--- +title: Custom sidebars +description: Render your own React sidebar view inside Hunk, with selection, scrolling, and event-driven state. +--- + +`hunk.registerSidebarView(view)` contributes a sidebar view — your own React component, rendered inside Hunk's OpenTUI tree. Registration is additive: your view exists beside the built-in file navigation, on either side of the review stream, and any number of views can be open at once. Pair it with [`registerCommand`](/docs/extend/extension-api/#hunkregistercommandcommand-handler) so a key opens it: + +```tsx +// ~/.config/hunk/extensions/flat-sidebar.tsx +import { useMemo } from "react"; +import type { ExtensionSidebarViewProps, HunkExtensionAPI } from "hunkdiff/extension"; + +function FlatSidebar({ files, selectedFileId, theme, actions }: ExtensionSidebarViewProps) { + const ordered = useMemo(() => [...files].sort((a, b) => a.path.localeCompare(b.path)), [files]); + + return ( + + {ordered.map((file) => ( + actions.selectFile(file.id)} + /> + ))} + + ); +} + +export default function (hunk: HunkExtensionAPI) { + hunk.registerSidebarView({ + id: "flat", + title: "Flat files", + placement: "right", + component: FlatSidebar, + }); + hunk.registerCommand( + { id: "toggle-flat", title: "Toggle flat sidebar", key: "ctrl+f" }, + (ctx) => { + ctx.sidebars.toggle("flat"); + }, + ); +} +``` + +Beyond `id` and `component`, a view may declare a `title` (for diagnostics and future menu listings), a `placement` of `"left"` (default) or `"right"`, `defaultOpen: true` to start open, or `replacesDefault: true` to start open _in place of_ the built-in file navigation — which stays available, just closed, so a command can reopen it. + +Import `react` normally — Hunk serves its own React instance to extension files at import time, so hooks, context, and JSX all run on the reconciler drawing the rest of the app. **Never bundle or vendor a copy of React into an extension**: a second React means a second hooks dispatcher, and the component will fail to render. OpenTUI elements (`box`, `text`, `scrollbox`, ...) are plain intrinsic elements and need no import. + +## Props + +The component receives fresh props as the app changes: + +| Prop | What it is | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `files` | the visible reviewed files, review-stream order, filtered, frozen views (each carries `changeType`, `statsTruncated`, and `hunks` summaries beside the usual file fields) | +| `selectedFileId` | the selected file, or `null` | +| `selectedHunkIndex` | the selected hunk within that file, or `null` | +| `width` | terminal columns the sidebar pane occupies | +| `theme` | hex color tokens from the active theme, updated on theme switch | +| `keybindings` | the current command bindings, resolved from defaults and the user's `[keybindings]` table | +| `actions` | navigation the sidebar may trigger | + +`actions.selectFile(fileId)` and `actions.selectHunk(fileId, hunkIndex)` route through the same review controller as the built-in sidebar and the keyboard shortcuts, so the review stream scrolls, selection updates, and the `selection_changed` event fires exactly as if the user had clicked a built-in row. `actions.notify(message, type?)` shows a toast attributed to your extension. An action given a file id that is not currently visible is refused with a warning rather than corrupting the selection. + +The three hunk surfaces line up by design: each file's `hunks` lists public `ExtensionDiffHunk` summaries (`index`, the `@@` header, inclusive old/new line spans) in render order, `selectedHunkIndex` reports the same index, and `actions.selectHunk(fileId, hunkIndex)` accepts it. That is everything a hunk checklist, a per-hunk progress view, or an agent-annotation navigator needs — match an annotation's `oldRange`/`newRange` against the summaries' spans to find its hunk — without touching the opaque `metadata`. + +## Keys inside a component + +A component that owns a key event should ask the injected `keybindings` manager about a **command id**, rather than hard-coding the command's default chord. This keeps local component behavior synchronized with the user's remaps and unbindings: + +```ts +import type { ExtensionKeyEvent, ExtensionSidebarViewProps } from "hunkdiff/extension"; + +export function handleSidebarKey(props: ExtensionSidebarViewProps, key: ExtensionKeyEvent) { + const nextFile = props.files[1]; + if (nextFile && props.keybindings.matches(key, "hunk.review.nextFile")) { + // The user may have remapped this from `.` to another chord. + props.actions.selectFile(nextFile.id); + } +} +``` + +`keybindings.getKeys(commandId)` returns the current chord list for a label or hint; unknown and unbound commands return an empty list. `matches(key, commandId)` returns `false` for those commands too. The manager includes both Hunk commands and extension commands under their documented ids, and its key event argument is structural — OpenTUI's `KeyEvent` works directly. + +`matchesKey`, `parseKeyChord`, and `matchesKeyChord` remain exported for extension-local keys that intentionally are not commands. Prefer a named command whenever a shortcut should be user-remappable. + +## The pane is Hunk's, the content is yours + +Hunk keeps owning pane arrangement — widths, resize dividers, responsive show/hide, and dropping panes that no longer fit a narrow terminal — and your component fills the pane it is given. A component that throws while rendering costs you the pane, not the user the session: the failure is reported as a toast naming your extension, the pane closes, and the built-in file navigation reopens if nothing else is showing. + +Props carry the pane's `width` but not its height: the pane is a flex cell, so give your root element `height="100%"` and let layout size it. Everything else about scrolling — pane viewport height, scroll position, keeping a row visible — goes through the `` itself, via a plain React ref. Hunk serves its own `@opentui/core` to extension files, so the renderable a ref hands you is the very instance the host renders with. + +## Scrolling: the scrollbox ref contract + +The one behavior a list sidebar always ends up needing is following the selection. Give your rows stable `id` props, hold a ref to the scrollbox, and scroll the selected row into view from an effect: + +```tsx +import { useEffect, useRef } from "react"; +import type { ScrollBoxRenderable } from "@opentui/core"; +import type { ExtensionSidebarViewProps } from "hunkdiff/extension"; + +function HunkList({ + files, + selectedFileId, + selectedHunkIndex, + theme, + actions, +}: ExtensionSidebarViewProps) { + const scrollRef = useRef(null); + + // Follow policy is deliberately yours: the host never scrolls a pane it + // cannot see into, so decide here when (and whether) to follow. + useEffect(() => { + if (selectedFileId !== null) { + scrollRef.current?.scrollChildIntoView(`row-${selectedFileId}-${selectedHunkIndex ?? 0}`); + } + }, [selectedFileId, selectedHunkIndex]); + + return ( + + {files.flatMap((file) => + (file.hunks ?? []).map((hunk) => { + const selected = file.id === selectedFileId && hunk.index === selectedHunkIndex; + return ( + actions.selectHunk(file.id, hunk.index)} + > + + + ); + }), + )} + + ); +} +``` + +The ref surface this recipe stands on is the exact one the built-in sidebar runs on: + +- **`scrollChildIntoView(id)`** scrolls the descendant with that `id` prop into view. +- **`scrollTop`** and **`viewport.height`** read the current scroll offset and the pane's viewport rows — the pane-height number the props do not carry. A read before the first layout pass reports `0`, so viewport-dependent code belongs behind the events below rather than a bare mount effect. +- **`verticalScrollBar.on("change", handler)`**, **`viewport.on("layout-changed", handler)`**, and **`viewport.on("resized", handler)`** report scrolling and pane resizes; unsubscribe with the matching `.off` in your effect's cleanup. + +That is enough to window a long list yourself: the built-in sidebar renders only the rows near the viewport, plus spacer boxes sized from those same reads (its render-window helper is host code, but nothing it computes needs anything beyond this surface — `useTerminalDimensions` from `@opentui/react` serves as its pre-first-layout viewport estimate). + +One honest caveat: this contract rides on OpenTUI's renderable API, served at whatever version Hunk pins — a wider surface than `hunkdiff/extension` itself. The built-in sidebar exercising the exact same calls is the compatibility guarantee: a change that breaks your scroll code breaks Hunk's own sidebar first. Still, keep scroll handling small and behind your own helpers. + +The built-in sidebar is itself a bundled extension (`src/extensions/default/ui/sidebar/` in the Hunk repository): it registers through this exact call, its component consumes exactly the props documented above, and its windowing and selection follow run on exactly the ref contract above — so it doubles as the reference implementation for everything a third-party sidebar can build, from grouping and stat badges down to scroll behavior. + +## Sidebar state from events + +Lifecycle handlers run outside React, but a sidebar component only rerenders when React sees a change. The recipe that connects them is a module-local store read through `useSyncExternalStore`: the event handler updates the store, and any mounted component subscribed to it rerenders — while the store keeps accumulating even when the pane is closed. + +```tsx +import { useSyncExternalStore } from "react"; +import type { HunkExtensionAPI } from "hunkdiff/extension"; + +let viewedPaths: ReadonlySet = new Set(); +const listeners = new Set<() => void>(); + +function markViewed(path: string) { + if (viewedPaths.has(path)) return; + viewedPaths = new Set(viewedPaths).add(path); // new reference, so React sees the change + for (const listener of listeners) listener(); +} + +function useViewedPaths() { + return useSyncExternalStore( + (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + () => viewedPaths, + ); +} + +function ViewedCount() { + const viewed = useViewedPaths(); + return ; +} + +export default function (hunk: HunkExtensionAPI) { + hunk.on("file_viewed", ({ file }) => markViewed(file.path)); + hunk.registerSidebarView({ id: "progress", component: ViewedCount }); +} +``` + +Snapshots must be immutable — replace the set instead of mutating it, so `useSyncExternalStore` can compare references. Storing state in a hook inside the component instead would lose it every time the pane closes and unmounts. diff --git a/website/src/content/docs/docs/extend/extension-api.md b/website/src/content/docs/docs/extend/extension-api.md new file mode 100644 index 000000000..439a4e83d --- /dev/null +++ b/website/src/content/docs/docs/extend/extension-api.md @@ -0,0 +1,240 @@ +--- +title: Extension API +description: Register themes, languages, transforms, commands, dialogs, and events through the extension API object. +--- + +The extension factory receives one API object. Registration calls are only valid while the factory is running; Hunk seals the object afterwards so a deferred callback cannot mutate the registry mid-session. This page indexes the whole object; the two largest registration calls are documented in depth on their own pages and summarized in place below. + +## `hunk.apiVersion` + +The API generation this Hunk speaks (currently `1`). Branch on it if you want one file to support several Hunk versions. + +## `hunk.registerTheme(theme)` + +Contribute one selectable theme. The object is the same shape as a `[themes.]` config table: + +```ts +hunk.registerTheme({ + id: "midnight-review", + label: "Midnight Review", + base: "catppuccin-mocha", + accent: "#7fd1ff", + syntaxScopes: { "keyword.operator": "#7fd1ff" }, +}); +``` + +Theme ids are lowercase words separated by `-` or `_` and cannot reuse a built-in id. Config-defined themes win over extension themes for the same id. Extension themes appear in the selector after config themes, in load order. + +## `hunk.registerFileLanguage(extension, language)` + +Map a file extension to a syntax-highlighting language. The extension may be written with or without a leading dot and is lowercased. + +```ts +hunk.registerFileLanguage(".zig", "zig"); +hunk.registerFileLanguage("bzl", "python"); +``` + +Later registrations win. Hunk's own `.mts` and `.cts` mappings cannot be overridden. + +## `hunk.registerVcsAdapter(adapter)` + +Contribute an additional version-control backend — the same call Hunk's own bundled Git, Jujutsu, and Sapling backends make. An adapter declares `detect`, its `operations` (`working-tree-diff`, `revision-show`, `stash-show`), and optionally detection priority, watch support, exact file sources, extra files, and rich user-fixable failures. + +Full contract: [VCS adapters](/docs/extend/vcs-adapters/). + +## `hunk.registerSidebarView(view)` + +Contribute a sidebar view — your own React component, rendered inside Hunk's OpenTUI tree beside (or in place of) the built-in file navigation. Views receive live review props, guarded navigation actions, the user's resolved keybindings, and a scrollbox ref contract for selection-following and windowing. + +Full contract: [Custom sidebars](/docs/extend/custom-sidebars/). + +## `hunk.transformChangeset(fn)` + +Rewrite the loaded changeset before it reaches the review UI. Transforms run in registration order, each seeing the previous one's output, on first load and on every reload. + +```ts +hunk.transformChangeset((changeset) => ({ + ...changeset, + files: changeset.files.filter((file) => !file.path.endsWith(".lock")), +})); +``` + +The function may be async. Filtering and reordering `files` is fully supported — the sidebar and the review stream follow whatever you return. + +Each file carries an opaque `metadata` field — the parsed diff the renderer draws from — so pass it through untouched; spreading a file preserves it. Returns are validated: a transform that throws or returns something the review UI cannot draw is skipped, and the previous changeset carries forward. + +You never need `metadata` to know a file's hunks: the read-only views Hunk hands outward (event payloads, sidebar props, a command's selection) carry a `hunks` list of public summaries — `index`, the `@@` header, and the inclusive old/new line spans, in render order. Like `changeType`, it is derived at that boundary; a transform neither receives nor produces it. + +## `hunk.registerCommand(command, handler)` + +Register a named command, optionally bound to a key. Commands are the same mechanism Hunk's own shortcuts dispatch through — one table, one loop, built-ins first. + +```ts +import type { HunkExtensionAPI } from "hunkdiff/extension"; + +export default function (hunk: HunkExtensionAPI) { + hunk.registerCommand({ id: "hello", title: "Say hello", key: "ctrl+g" }, (ctx) => { + ctx.notify("hello from a command"); + }); +} +``` + +Key chords join `ctrl`, `alt`/`option`, `cmd`/`meta`, and `shift` with `+` around a base key — a character (`"y"`), an uppercase letter for its shifted form (`"G"`), or a named key (`"f2"`, `"pageup"`). For a shifted symbol or digit, bind the character shift produces (`"!"`, not `"shift+1"`). `key` also takes a list of chords; omit it to register a command with no binding. A chord already owned by a built-in or an earlier-loaded extension stays with its owner. + +Declared keys are defaults: users remap commands by id in their `[keybindings]` table — yours is `"."`. See [`docs/keybindings.md`](https://github.com/modem-dev/hunk/blob/main/docs/keybindings.md). + +Registered commands are also listed in the menu bar's **Extensions** menu under their `title`, showing whichever key they currently answer to — a command with no binding is still reachable with the mouse. + +The handler fires when the key is pressed outside modal UI (dialogs, menus, and focused text inputs own their keys; pager mode does not dispatch extension commands). It receives the standard context plus: + +- `ctx.sidebars.open(viewId)` / `close(viewId)` / `toggle(viewId)` / `isOpen(viewId)` — a bare id names your own view, `"files"` the built-in file navigation, `":"` any registered view. Opening also reveals a hidden sidebar area. +- `ctx.selection` — where the review was pointing when the command fired. +- `ctx.navigation` — moves the review stream. +- `ctx.dialogs` — asks the user, below. + +```ts +hunk.registerCommand( + { id: "show-selection", title: "Show the selected file", key: "ctrl+y" }, + (ctx) => { + const { file, hunkIndex } = ctx.selection; + if (!file) { + ctx.notify("No file selected"); + return; + } + + ctx.notify(hunkIndex === null ? file.path : `${file.path} — hunk ${hunkIndex + 1}`); + }, +); +``` + +`selection.file` is a frozen view, identical to a sidebar's `files` entries; it is `null` only when no files are visible. `selection.hunkIndex` is `null` whenever `file` is, or when the file has no hunks. The values are captured when the command fires, so an async handler keeps the selection it started from. + +`ctx.navigation.selectFile(fileId)` and `selectHunk(fileId, hunkIndex)` route through the same guarded review controller as a sidebar's `actions` — the stream scrolls, selection updates, `selection_changed` fires. Unlike `selection` it is live: a handler that awaits a dialog and then navigates still works. + +A handler may be async; a failure becomes a warning naming your extension. + +### Asking the user + +`ctx.dialogs` puts a question on screen and waits for the answer. Three methods, all return promises: + +- `confirm({ title, body?, confirmLabel?, cancelLabel? })` → `true` or `false` +- `select({ title, options })` → the chosen string, or `null` +- `input({ title, placeholder?, initial? })` → the typed string, or `null` + +```ts +hunk.registerCommand( + { id: "reformat", title: "Reformat the selected file", key: "ctrl+r" }, + async (ctx) => { + const file = ctx.selection.file; + if (!file) { + return; + } + + const proceed = await ctx.dialogs.confirm({ + title: `Reformat ${file.path}?`, + body: "The file is rewritten in place.", + confirmLabel: "reformat", + }); + + ctx.notify(proceed ? `Reformatting ${file.path}` : "Left it alone"); + }, +); +``` + +`select` fits acting on part of the selection — asking which hunk to jump to, then navigating there: + +```ts +hunk.registerCommand({ id: "pick-hunk", title: "Pick a hunk", key: "ctrl+k" }, async (ctx) => { + const file = ctx.selection.file; + const hunks = file?.hunks ?? []; + if (!file || hunks.length === 0) { + ctx.notify("Nothing to pick from", "warning"); + return; + } + + const labels = hunks.map((hunk) => hunk.header || `hunk ${hunk.index + 1}`); + const picked = await ctx.dialogs.select({ title: "Which hunk?", options: labels }); + + // `navigation` is live, so the jump is valid even after awaiting the dialog. + if (picked !== null) { + ctx.navigation.selectHunk(file.id, labels.indexOf(picked)); + } +}); +``` + +Hunk draws the dialog; your text fills the title, body, and choices, and the frame carries an `ext ` attribution line — the same marker `notify` toasts use — so a prompt cannot present itself as Hunk asking. + +One dialog shows at a time; concurrent requests queue in call order, across extensions. Escape cancels (`false` or `null`), Enter accepts; confirm dialogs also answer to `y`/`n`, select dialogs to `↑`/`↓`, and everything is clickable. A session reload cancels open and queued dialogs, and a dialog pending at shutdown resolves its cancel value. + +## `hunk.on(event, handler)` + +Subscribe to a lifecycle or UI event. Handlers may be async; Hunk never blocks the UI waiting for one. Every handler receives `ctx.sidebars` alongside `cwd` and `notify`, so a `changeset_loaded` handler can reveal its extension's sidebar without a keypress. + +| Event | Payload | When | +| ---------------------- | ----------------------- | -------------------------------------------------------- | +| `startup` | `{ cwd }` | once, after the app mounts with its first changeset | +| `changeset_loaded` | `{ changeset }` | first load and every reload | +| `selection_changed` | `{ fileId, hunkIndex }` | when the review selection settles (debounced ~150ms) | +| `file_viewed` | `{ file, hunkIndex }` | when selection settles on a file or a reload replaces it | +| `filter_changed` | `{ filter }` | whenever the file-filter query changes | +| `theme_changed` | `{ themeId }` | when the user commits a new theme | +| `layout_changed` | `{ mode, layout }` | mode or responsive split/stack layout changes | +| `watch_reload_pending` | `{}` | watcher observed a change before its reload check | +| `note_created` | `{ note }` | a user saves an inline review note | +| `note_edited` | `{ note }` | an in-progress inline note's body changes | +| `session_reload` | `{ changeset, reason }` | on every session reload | +| `shutdown` | `{}` | on exit, best-effort within a short timeout | + +- `selection_changed` is trailing-debounced: holding `[`/`]` retargets many times a second, and handlers only care where the user landed. `fileId` and `hunkIndex` are `null` when nothing is selected. +- `session_reload`'s `reason` is `"watch"`, `"daemon"` (an agent command through the session broker), or `"manual"`. +- `note_created` and `note_edited` cover notes authored in Hunk's own UI this session. Agent session comments do not emit them, and a reload may remap or drop notes — an accumulated list is not a complete review record. +- `shutdown` handlers get 250ms before Hunk exits anyway; treat it as best-effort flushing. + +## `hunk.events` + +A small bus shared by every loaded extension, for coordinating without coupling through global state. Namespace event names with your extension id. Delivery is fire-and-forget; events emitted while factories are still loading are queued until every extension has subscribed. + +```ts +import type { HunkExtensionAPI } from "hunkdiff/extension"; + +export default function (hunk: HunkExtensionAPI) { + hunk.events.on<{ fileCount: number }>("summary:ready", (payload, ctx) => { + if (payload.fileCount > 100) ctx.sidebars.open("summary"); + }); + + hunk.on("changeset_loaded", ({ changeset }, ctx) => { + hunk.events.emit("summary:ready", { fileCount: changeset.files.length }); + ctx.sidebars.open("summary"); + }); +} +``` + +Bus payloads are shallow-frozen copies when they are objects. Keep nested data immutable if multiple extensions will read it. + +## `hunk.config` + +Your extension's own `[extension.]` config table, as a plain object. Hunk does not interpret the keys, and repo config overrides user config key by key. + +**Treat these values as untrusted.** A repository under review can set or override the table for an extension you installed globally (deliberate — team-level tuning of a shared extension), so never use `hunk.config` for exec-adjacent decisions such as binary paths, shell commands, or module loading. Validate those against something the user controls. + +```toml +# ~/.config/hunk/config.toml +[extension.collapse-generated] +patterns = ["*.lock", "dist/**"] +``` + +```ts +const patterns = (hunk.config.patterns as string[] | undefined) ?? ["*.lock"]; +``` + +## `ctx.notify(message, type?)` + +Every handler and transform receives a context with `cwd` and `notify`; event and bus handlers add `sidebars` and `events.emit`, command handlers add `sidebars`, `selection`, `navigation`, and `dialogs`. `notify` shows one transient line at the bottom of the app; `type` is `"info"` (default), `"warning"`, or `"error"`. Messages raised before the UI mounts are buffered, so a `startup` handler can notify safely. + +## `hunk.log(message)` + +Record a diagnostic line. Logs are collected per extension rather than written to the terminal, because the TUI owns the screen. + +## Not contributable yet + +Menu entries, standalone keybindings (chords without a command — `registerCommand` commands are already user-remappable), custom note renderers, session commands, and CLI subcommands. See [`docs/extension-system-exploration.md`](https://github.com/modem-dev/hunk/blob/main/docs/extension-system-exploration.md) for the design and phasing. diff --git a/website/src/content/docs/docs/extend/extensions.md b/website/src/content/docs/docs/extend/extensions.md new file mode 100644 index 000000000..658b2c18b --- /dev/null +++ b/website/src/content/docs/docs/extend/extensions.md @@ -0,0 +1,170 @@ +--- +title: Extensions +description: Load plain TypeScript extensions, understand discovery and trust, and configure them. +--- + +A Hunk extension is one TypeScript (or JavaScript) file that default-exports a function. Hunk imports it at startup and hands it an API object. No build step is required. + +```ts +// ~/.config/hunk/extensions/hello.ts +import type { HunkExtensionAPI } from "hunkdiff/extension"; + +export default function (hunk: HunkExtensionAPI) { + hunk.on("startup", (_event, ctx) => { + ctx.notify("Hello from my extension"); + }); +} +``` + +**The API is experimental**: `hunkdiff/extension` may change in breaking ways between minor releases while it stabilizes. Breaking changes are called out in release notes, and `hunk.apiVersion` identifies the surface an extension was written against. + +What an extension can register is covered by the companion pages: the [extension API](/docs/extend/extension-api/), [VCS adapters](/docs/extend/vcs-adapters/), and [custom sidebars](/docs/extend/custom-sidebars/). + +## Where Hunk looks + +| Group | Source | Runs | +| ----- | ---------------------------------------------------- | --------------------- | +| 1 | `--extension ` (repeatable) | immediately | +| 2 | `[extensions] paths` in your user config | immediately | +| 3 | `~/.config/hunk/extensions/` | immediately | +| 4 | `.hunk/extensions/` in the repo under review | after [trust](#trust) | +| 4 | `[extensions] paths` in the repo `.hunk/config.toml` | after [trust](#trust) | + +- Groups load in order; within a group, entries sort alphabetically by resolved path. The first occurrence of a path wins. +- The two repo-local sources are one group: one trust decision, one sort order. +- A directory source matches `*.ts`, `*.tsx`, `*.js`, `*.jsx`, `*.mjs` directly inside it, plus one level of folder extensions. +- `--no-extensions` disables user extensions for one run; nothing on disk is read. +- `--extension` is explicit intent: it loads immediately, without a trust prompt, even from inside the reviewed repo — so never pass a path you have not read. + +### Folder extensions + +A folder is an extension if its `package.json` declares entries under the `hunk` field, or failing that if it has an `index.{ts,tsx,js,jsx,mjs}` (in that preference order): + +```text +~/.config/hunk/extensions/my-ext/ + package.json # {"hunk": {"extensions": ["./src/index.ts"]}} + node_modules/ # bun install / npm install, right here + src/ + index.ts # the declared entry + helper.ts +``` + +- Manifest paths resolve against the folder and may list several entries; each loads as its own extension, in manifest order. +- The manifest is a real `package.json`, so a folder extension can depend on npm packages installed into its own `node_modules`. +- Pointing `--extension` or `[extensions] paths` at a directory works either way: a folder extension loads as one extension; any other directory is scanned as a directory _of_ extensions. + +### Extension ids + +The **id** is the file stem, or the folder name for `/index.ts` and single-entry manifests. It is the key for everything the extension owns: + +- config: `[extension.]` +- commands: `.` +- sidebar views: `:` + +Ids start with a letter or digit, then letters, digits, `-`, or `_`. `hunk`, `git`, `jj`, and `sl` are reserved. An invalid id — or a second source offering an already-loaded id — is skipped with a startup notice. + +## Bundled extensions + +Hunk's own Git, Jujutsu, and Sapling backends and the built-in file-navigation sidebar are themselves extensions, registered through the same public API — which is what keeps that API honest. They differ from yours in three ways: + +- statically imported, so they load before config resolution picks the session's VCS +- implicitly trusted, with no `[extension.]` config table +- still loaded under `--no-extensions` and `[extensions] enabled = false` — those switches triage extensions _you_ installed + +## Trust + +Extensions run with your full user permissions, and reviewing a repository must never execute code that came with it. So the repo-local sources stay inert until you approve them, once per repository: + +```text +Run this repository's extensions? + + This repository contains extensions in .hunk/extensions. + Extensions run with your user permissions. + + enter/t trust · esc not now · n never +``` + +**Trust** records the decision and reloads the session; **not now** asks again next time; **never** stops the offers. The prompt is a dialog over the review stream, not a gate in front of it — dismiss it and keep reviewing. + +Decisions are stored per repository root in `~/.config/hunk/state.json`, keyed by path (the VS Code workspace-trust model). A different repository later occupying a trusted path inherits the decision; clear the entry if that matters for a path you reuse. + +## Failure isolation + +A broken extension is contained, not fatal: a failed import, missing default export, or throwing factory is skipped and rolled back with a startup notice; a handler or transform that throws later becomes a warning naming the extension. Event handlers receive frozen changeset copies, so accidental mutation throws instead of corrupting the review. + +This is crash containment, not a sandbox — an extension can do anything your shell can. + +## CLI flags and config + +```bash +hunk diff --extension ./path/to/entry.ts # load one entry file (repeatable) +hunk diff --extension ./my-ext # a folder extension: loads ./my-ext/index.ts +hunk diff --no-extensions # disable user extensions for this run +``` + +```toml +# ~/.config/hunk/config.toml or .hunk/config.toml +[extensions] +enabled = true # false disables loading for this layer +paths = ["~/dev/hunk-ext/index.ts"] # extra entry files or directories + +[extension.my-extension] # opaque payload handed to that extension +some_key = "some value" +``` + +`[extensions] enabled` layers like every other option (repo config overrides user config); `--no-extensions` is a hard off switch no config layer can re-enable. `[extension.]` tables pass through to the extension uninterpreted — see [`hunk.config`](/docs/extend/extension-api/#hunkconfig) for the merge rules and their caveats. + +## A complete example + +Collapse lockfiles and generated output out of every review, and say how many files were hidden. + +```ts +// ~/.config/hunk/extensions/collapse-generated.ts +import type { HunkExtensionAPI } from "hunkdiff/extension"; + +/** Match one path against a `*`-only glob, anchored at both ends. */ +function matchesPattern(path: string, pattern: string) { + const source = pattern + .split("*") + .map((part) => part.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")) + .join(".*"); + return new RegExp(`^${source}$`).test(path); +} + +export default function (hunk: HunkExtensionAPI) { + const patterns = (hunk.config.patterns as string[] | undefined) ?? [ + "*.lock", + "*-lock.json", + "dist/*", + ]; + + hunk.transformChangeset((changeset, ctx) => { + const kept = changeset.files.filter( + (file) => !patterns.some((pattern) => matchesPattern(file.path, pattern)), + ); + + const hidden = changeset.files.length - kept.length; + if (hidden > 0) { + ctx.notify(`Collapsed ${hidden} generated ${hidden === 1 ? "file" : "files"}`); + } + + return { ...changeset, files: kept }; + }); +} +``` + +Configure it without touching the code: + +```toml +# .hunk/config.toml +[extension.collapse-generated] +patterns = ["*.lock", "bun.lockb", "generated/*"] +``` + +Try it against the working tree without installing it: + +```bash +hunk diff --extension ./collapse-generated.ts +``` + +Continue with the [extension API](/docs/extend/extension-api/) for everything the API object offers. diff --git a/website/src/content/docs/docs/extend/vcs-adapters.md b/website/src/content/docs/docs/extend/vcs-adapters.md new file mode 100644 index 000000000..aff70f9fc --- /dev/null +++ b/website/src/content/docs/docs/extend/vcs-adapters.md @@ -0,0 +1,175 @@ +--- +title: VCS adapters +description: Contribute a version-control backend with detection, watch support, exact file sources, and rich failures. +--- + +`hunk.registerVcsAdapter(adapter)` contributes an additional VCS backend. This is the same call Hunk's own bundled Git, Jujutsu, and Sapling backends make. + +```ts +hunk.registerVcsAdapter({ + id: "hg", + name: "Mercurial", + detect: (cwd) => (existsSync(join(cwd, ".hg")) ? { id: "hg", repoRoot: cwd } : null), + operations: { + "working-tree-diff": { + async load(input, ctx) { + return { + repoRoot: ctx.cwd, + sourceLabel: ctx.cwd, + title: "Mercurial working copy", + patchText: await runHgDiff(ctx.cwd), + untrackedPaths: await listHgUnknownFiles(ctx.cwd), + }; + }, + }, + }, +}); +``` + +The ids Hunk ships with — `git`, `jj`, and `sl` — are reserved. An adapter that reuses one is skipped with a notice. + +`operations` is optional and may implement any of `working-tree-diff`, `revision-show`, and `stash-show`; an operation you leave out — or leaving the map off entirely — produces a clear "not supported" error for that command instead of a crash. + +A `load` result is patch text plus how to label it. Everything else on it is optional, and each optional field buys one thing: + +| Field | What it adds | +| ---------------- | ----------------------------------------------------------------- | +| `untrackedPaths` | files your VCS calls unknown, synthesized into added-file diffs | +| `readFileSource` | exact whole-file contents, for context expansion and highlighting | +| `extraFiles` | files reviewed outside the patch, including skipped placeholders | + +`untrackedPaths` is the shorthand: list the repo-root-relative paths your VCS reports as unknown and Hunk synthesizes the added-file diffs for you, skipping binaries and files too large to render. Honor `input.options.excludeUntracked` when you do, so `--exclude-untracked` still means what it says. The other two are covered below. + +## Detection order + +Detection prefers the **nearest** checkout: a Git repository nested inside a jj workspace is reviewed as Git, whatever the priorities say. The same rule covers your adapter — a Mercurial checkout inside a Git repository is reviewed as Mercurial. `detectionPriority` only decides which backend wins when several recognize the _same_ directory — the colocated case, where one working copy carries two sets of markers. + +| Adapter | Priority | +| ------------------------ | -------------------------------------------- | +| bundled `jj` | 200 | +| bundled `sl` | 100 | +| bundled `git` | 0 (`HUNK_CORE_VCS_DETECTION_PRIORITY`) | +| your adapter, by default | -100 (`HUNK_DEFAULT_VCS_DETECTION_PRIORITY`) | + +Higher is consulted first; equal priorities fall back to registration order. jj and Sapling sit above Git because a colocated jj repository — or a Sapling repository created with `sl init --git` — also carries Git metadata, and the Git view is the wrong one. + +The default puts your adapter below Git, so installing an extension never silently changes how an existing repository is reviewed. Set `detectionPriority` explicitly to outrank a shipped backend; it is your machine. + +```ts +import { HUNK_CORE_VCS_DETECTION_PRIORITY } from "hunkdiff/extension"; + +hunk.registerVcsAdapter({ + id: "hg", + name: "Mercurial", + detectionPriority: HUNK_CORE_VCS_DETECTION_PRIORITY + 10, + detect, +}); +``` + +Detection runs the same way for every adapter, whichever tier registered it: the nearest checkout wins, `detectionPriority` breaks ties between adapters that recognize the same root, and equal priorities fall back to registration order. Config resolves the session's VCS before your extension has been imported, so detection runs again once extensions are loaded — with the full adapter list — and that second answer is the one the session uses. + +What detection never overrides is an explicit choice: a `vcs = ""` in Hunk config naming a backend this session loaded is honored as-is, however near a checkout some other adapter finds. + +## Watch support + +`--watch` works through extension adapters. Each operation may add: + +- `watchSignature(input, ctx)` — a cheap fingerprint of the reviewed state. Hunk polls it and reloads when it changes. +- `watchPlan(input, ctx)` — the filesystem targets that cover that state, so Hunk reacts to events instead of polling on a timer. + +```ts +watchPlan: (input, ctx) => ({ + coverage: "hybrid", + targets: [ + { + kind: "directory-tree", + directory: ctx.cwd, + ignoredRoots: [join(ctx.cwd, ".hg")], + sources: ["worktree"], + }, + ], +}), +``` + +`coverage: "hybrid"` promises the targets cover the reviewed state. Leaving `watchPlan` out is equivalent to `poll-only` and still works — it just costs a subprocess per tick. + +## Exact file sources + +A patch carries the changed lines and a little context, and nothing else. If your VCS can produce a file's _whole_ contents on each side, say so with `readFileSource` and Hunk will expand context past the hunk, highlight against the real file, and word-diff accurately. + +```ts +async load(input, ctx) { + // Pin the revisions while the operation loads, then close over them: by the + // time Hunk asks for a file, nothing can have moved underneath it. + const [oldRev, newRev] = await resolveHgRevisions(input, ctx.cwd); + + return { + repoRoot: ctx.cwd, + sourceLabel: ctx.cwd, + title: "Mercurial working copy", + patchText: await runHgDiff(ctx.cwd), + readFileSource: async ({ path, previousPath, changeType, side }) => { + if (side === "old") { + return changeType === "new" ? null : hgCat(oldRev, previousPath ?? path); + } + return changeType === "deleted" ? null : hgCat(newRev, path); + }, + }; +} +``` + +Return `null` for a side that has no content — the old side of an added file, a path the revision never contained — rather than throwing. Hunk calls the reader **at most once per file and side** and caches what it resolves, so you do not need your own cache, and it never calls it for a file the diff reports as binary. Leaving `readFileSource` off is fine: Hunk falls back to the content the patch itself carries, which renders the same diff with less context available. + +## Files outside the patch + +`extraFiles` lists files to review that your `patchText` does not contain, in the order they should appear. Each entry is one of two kinds, and Hunk builds the diff model for both — you describe files, you never assemble them. + +A **patch** entry is a file with its own one-file diff. Reach for it when your VCS produces better text for a file than Hunk reading the working copy would — its own binary detection, its own path quoting: + +```ts +extraFiles: [ + { + kind: "patch", + path: "notes.md", + patchText: await hgDiffOneFile("notes.md"), + isUntracked: true, + }, +]; +``` + +A **skipped** entry is a file Hunk should list but not render. Reviewing a multi-hundred-megabyte generated file costs more than it is worth, so report the file and why instead of producing a diff nothing will read: + +```ts +extraFiles: [ + { + kind: "skipped", + path: "dist/bundle.js", + reason: "too-large", + changeType: "change", + stats: { additions: 100_001, deletions: 0 }, + statsTruncated: true, + }, +]; +``` + +`readFileSource` covers the patch entries too; a skipped entry has no content to read, so it never gets a source reader. + +`untrackedPaths` remains the shorthand for the common case: list the paths your VCS calls unknown and Hunk synthesizes the added-file diffs from the working copy, skipping binaries and files too large to render. Use `extraFiles` instead only when your VCS renders those files better than a plain read would. + +## Moved lines + +`input.options.colorMoved` is true when the user asked for move detection. Hunk reads move classes back out of the patch itself, so emit ANSI-colored diff text painting moved additions cyan and moved deletions magenta — what `git diff --color-moved` produces — and those lines render as moved. This is ordinary post-processing over whatever patch text an adapter returns, not a Git special case. A backend with no notion of moved lines can ignore the option. + +## Failures the user can fix + +Throw a `HunkExtensionUserError` when the problem is how Hunk was invoked rather than a bug — no repository here, an unresolvable revision, a missing binary. Hunk prints the message without a stack trace and lists the suggestions beneath it. Anything else is reported as an unexpected error. + +```ts +import { HunkExtensionUserError } from "hunkdiff/extension"; + +throw new HunkExtensionUserError("`hunk stash show` is not supported by Mercurial.", { + suggestions: ["Use `hunk show ` to review a commit instead."], +}); +``` + +Hunk detects this structurally — an object whose `name` is `"HunkExtensionUserError"` with an optional `suggestions` array of strings — so a plain-JavaScript extension, or one bundling its own copy of the class, is treated the same way. `HUNK_EXTENSION_USER_ERROR_NAME` is exported if you would rather not hard-code the string. Hunk's own bundled Git, Jujutsu, and Sapling backends raise their failures exactly this way. diff --git a/website/src/content/docs/docs/index.mdx b/website/src/content/docs/docs/index.mdx index 089ea2af4..074bedd2e 100644 --- a/website/src/content/docs/docs/index.mdx +++ b/website/src/content/docs/docs/index.mdx @@ -36,6 +36,11 @@ Hunk is a terminal diff viewer for reviewing complete changesets and keeping age href="/docs/configure/configuration/" description="Set layered preferences, choose themes, and control layout and display behavior." /> +