SLOPSHOPPER

lens

Review a repo's changes in a pane: the changed files with editor-style diagnostics (pyright, ruff, tsc, eslint, terraform), a diff view, a git graph, commits…

paneguardcommandtoaststatusprocess
★ 1v0.2.0MITupdated 2026-10-11BuddyLim/claude-code-mod-lens
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · lens
│ ┃ Lens ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ Nothing to review here ⏺ Read(src/auth.ts) │ ┃ This folder is not inside a git ⎿ Read 6 lines │ ┃ repository, and no repo has been ⏺ Update(src/auth.ts) │ ┃ reviewed yet. ⎿ Added 2 lines, removed 1 line │ ┃ Name one: /lens ~/Code/my-repo [base ⏺ Bash(bun test) │ ┃ branch or commit] ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /lens │ ⎿ lens: Nothing has been reviewed lately. Name a folder: /lens ~/C │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Lens
Nothing to review here This folder is not inside a git repository, and no repo has been reviewed yet. Name one: /lens ~/Code/my-repo [base branch or commit]
README

lens

A Claude Code mod that puts a code review pane beside your session: the files a change touches, each read whole with editor-style diagnostics, a diff view, a git graph, commits and stashes, and pull request comments.

It is for reading what you (or Claude) just changed without leaving the terminal: what differs, what is wrong with it, and whether the change brought the problem or it was already there.

What it does

  • Changed files with problems inline. /lens lists what differs from a base (uncommitted changes by default) as a tree or a list, with each file's line counts and its errors and warnings. Python is checked with pyright and ruff, TypeScript with tsc and eslint, Terraform with terraform validate; language servers are asked first where they are installed, and bring other languages with them.
  • New or pre-existing. The base's version of each changed file is checked too, so every problem is marked as brought by the change or already there.
  • A file view. The whole file with syntax colours, diagnostics under the lines they are on, a minimap, find, blame, a breadcrumb with the file's outline, inlay hints, and a diff view that interleaves what the base had. Press v again to cut the diff down to the changes only: each change and each commented line, with three lines around it. Markdown is shown rendered.
  • Look things up. Select a name to see its type and where it is defined, then list its uses, callers, callees and implementations, or search the project's names.
  • A git graph. Branches, stashes and uncommitted work, with each commit's files a press away. Check out a branch or commit, undo the last commit, or compare any two branches, commits or pull requests.
  • Commit, stash and discard the files you tick, from the file tree.
  • Pull and merge requests. Compare with #12 (or a link) to review a request's changes; the repo's open requests are offered in the compare panel. Review threads show as cards on the lines they are on: reply, resolve or reopen one, post a new comment under a line, list every thread, and submit a review (approve, request changes or comment). GitHub through gh, GitLab through glab.
  • Worktrees. Each other worktree of the repo is a badge on the commit it has checked out; press it to review that worktree where you left it. Compare with @name to read your files against another worktree's as they stand, uncommitted work included.
  • Review findings from the ledger mod, where it is installed. Each finding a reviewing agent records shows on its line as a thread does, counts among the file's threads, and is listed with them; a fixed one shows as resolved. They cannot be answered or resolved from here: the ledger closes them. Without the ledger, nothing changes.
  • Hand things to Claude. Send a line's problems, a function, your selection or every new issue to the prompt (appended, never submitted), or have Claude told automatically what its own edits broke.
  • Picks up where you left off. Each repo's comparison and layout are kept between sessions; /lens recent offers the recent ones.
  • Requests, and a page of every change. p in the file tree lists the repo's open pull or merge requests, yours first; pressing one reviews it. d puts every change of the comparison on one page to scroll through, with the comments under their lines. While a request is under review each file has a box to tick once you have read it; the ticks are kept between sessions.
  • A review from start to finish. e is the request at a glance: its description rendered, checks, reviews, whether it merges, and merge, close or check out from there. Comments wait for the review and go with your verdict; they can be on a line, several lines, a removed line or a whole file, be edited, deleted or offered as a suggested change. Ticks follow GitHub's own "Viewed" marks.
  • More on the page of changes. Words that changed are lit; the two sides can sit side by side (v); f searches; n p j k c x jump by file, change and comment; and a change of your working tree is staged or undone a hunk at a time.
  • Folders without git. A folder in no repository opens too: every file of it is listed, its code files are checked, and anything else is left alone. Nothing is compared there, so there is no diff, graph or commit box.

Use

/lens                       the folder you are in: a repo's uncommitted changes, or a plain folder's files
/lens main                  the working tree against main
/lens ~/Code/my-repo main   another repo
/lens ~/Documents/scripts   a folder that is not a repo
/lens recent                pick one reviewed lately

Press h in the pane for the keys of the screen you are on.

Settings

/config has a row for each checker, for asking language servers first, for the new-or-pre-existing pass, the pane's side padding, whether the less-used keys always show, remembering reviews, and cleaning up when a session ends.

Other languages

Python, TypeScript and Terraform have command-line checkers. Any other language is checked by its language server alone, and the same server answers the lookups: types, definitions, uses, callers, the outline, colours and inlay hints, as far as that server offers them.

These are used when they are on your PATH, with nothing to set up:

LanguageServerA project is the folder holding
C and C++clangdcompile_commands.json, compile_flags.txt, .clangd, CMakeLists.txt
C#csharp-ls, else OmniSharp -lsp*.sln, *.csproj
Gogoplsgo.work, go.mod
Rustrust-analyzerCargo.toml
Pulumi YAMLpulumi-lsp (Pulumi.yaml, Pulumi.*.yaml only)Pulumi.yaml

When a change has files of one of these and its server is not installed, a note under the file list says what to install.

To add a server of your own, or change or switch off one of the above, write ~/.claude/lens/servers.json. It is read again at each scan:

{
  "servers": {
    "zls": {
      "language": "Zig",
      "extensions": [".zig"],
      "command": ["zls"],
      "rootMarkers": ["build.zig"],
      "install": "brew install zls"
    },
    "gopls": { "command": ["gopls", "-remote=auto"] },
    "clangd": { "disabled": true }
  }
}

A name the table already has (pyright, tsserver, terraform-ls, clangd, csharp-ls, gopls, rust-analyzer, pulumi-lsp) changes that server, one field at a time; any other name adds a server, which is tried before the built-in ones. The name is also what its problems are labelled with.

FieldWhat it is
extensionsThe file extensions the server reads, each with its dot. Upper or lower case is the same.
filenamesWhole file names it reads (* and ? stand for anything). A name counts before any extension.
commandThe program and its arguments, speaking the Language Server Protocol on stdin and stdout. A list of such lists is tried in order: the first whose program is installed is used.
languageIdWhat the protocol calls the language: "go", or one for each extension ({ ".c": "c", ".cc": "cpp" }). Left out, it is the extension without its dot.
rootMarkersFiles that mark a project, tried in order: the nearest folder at or above the file that holds the first one found is where the server is started (* allowed). With none found it is the repo; with none listed, each folder is its own project.
languageWhat to call the language in a note. Left out, it is the server's name.
installHow to get the server, shown when it is not installed.
disabledtrue switches the server off.

A new server needs a command and either extensions or filenames. pyright and tsserver are found and started in ways of their own, so only disabled can be set for them. An entry with something wrong in it is left out, and a note under the file list says which and why; it never stops the others from working.

This file is the only place servers are read from. Nothing in the repo you are reviewing can add one, because an entry names a command that is run on your machine: a repo you only meant to read must not get to choose it. The servers themselves do read the project's files, as they do in an editor.

Requirements

Nothing is required beyond git; each checker is used where it is found.

  • Python: uv (ruff and pyright run through uvx)
  • TypeScript: the project's own node_modules (tsc, eslint) and Node
  • Terraform: terraform, and optionally terraform-ls
  • Other languages: that language's server (see Other languages)
  • Syntax colours: uv (Pygments runs through it)
  • Pull requests: gh or glab, signed in
  • Icons: a Nerd Font in your terminal

Install

This mod uses Claude Code's function-hooks plugin API.

Clone it into your personal skills folder, where Claude Code loads it in every session:

git clone https://github.com/BuddyLim/claude-code-mod-lens ~/.claude/skills/lens

What it leaves on your machine

While a session runs: exports of the commits it checks under $TMPDIR/lens-base, a language-server keeper under /tmp/lens-lsp-<uid>, and, for a pull request, refs under refs/lens/ in that repo. All three are removed when the session ends (a setting). Nothing is ever checked out, committed or pushed unless you press the key for it.

Develop

claude plugin validate ~/.claude/skills/lens
claude plugin test ~/.claude/skills/lens
uv run --no-project python ~/.claude/skills/lens/tests/bridge_test.py

The last runs what claude plugin test cannot, since it needs real processes: the bridge's table of servers and its config file, and a small fake language server driven through the bridge's own daemon (one of its own, in a temp folder).

License

MIT

Source 45 files
hooks/register.tsx 4011 lines
1// The hooks module: the wiring. It declares the session's state, holds what
2// is too big or too short-lived to be state, and has every function that
3// touches the engine handle `$` (the engine follows `$` only into functions
4// declared at the top of this file, so they cannot live anywhere else). Each
5// of those is thin: it makes a `run` from the handle, calls the module that
6// knows the subject (git.ts, check.ts, scan.ts, lsp.ts, review.ts), and puts
7// the answer where the screens read it. The render hook builds each screen's
8// model and actions and routes to the screen (screens/), which is a pure view.
9
10import { atom, read, update } from 'claude-code'
11import type { EngineInterface, Register, RenderChildren } from 'claude-code'
12
13import type { LineRange, Listing, Lookup, Recent, Scan, Span, View, ChangedFile, LineStat } from '../types'
14import { hasNameSearch } from './check'
15import { diagsByLine, diagsOf } from './diags'
16import * as git from './git'
17import type { Blamed } from './git'
18import {
19  LIST_ROWS,
20  callsList,
21  implementationsList,
22  lookupOf,
23  namesList,
24  usesList,
25  threadsList,
26} from './lists'
27import type { Run as ServerRun } from './lsp'
28import {
29  isServed,
30  lspCalls,
31  lspInlayHints,
32  lspOutline,
33  lspReferences,
34  lspSemanticTokens,
35  lspSymbol,
36  lspWorkspaceSymbols,
37} from './lsp'
38import type { InlayHint, SemanticToken } from './lsp-types'
39import { ISSUES_SENT, codeBlock, diagBlock, issueList, quoteBlock, talkBlock } from './prompt'
40import { cleanUp, recentOf, remember, settledRecents } from './recents'
41import { findingComments, isFinding, placeOf } from './ledger'
42import { hostOf, mediaOf, plain, plainBlock, sampleOf } from './media'
43import type { Picture } from './pictures'
44import { PICTURES_SHOWN, fetchPicture, isFetched, isPictureFile, localPicture } from './pictures'
45import type { PatchFile } from './patch'
46import { CONTEXT, CONTEXTS, applyHunk, hunkMark, readPatch } from './patch'
47import type { Comment, Draft, Listed, Overview, RequestAct, Run as ForgeRun } from './review'
48import {
49  markViewed,
50  readViewed,
51  changeComment,
52  fold,
53  suggestionOf,
54  unfold,
55  whoAmI,
56  actOnRequest,
57  readOverview,
58  draftComment,
59  draftId,
60  isDraft,
61  submitDrafted,
62  fetchComments,
63  parseRequest,
64  isOnWholeFile,
65  postComment,
66  postGeneral,
67  quoteOf,
68  listRequests,
69  replyComment,
70  requestOfBranch,
71  repoPrefix,
72  resolveRequest,
73  resolveThread,
74} from './review'
75import type { Run } from './run'
76import { tail } from './run'
77import type { Job } from './scan'
78import { allFilesOf, historyOf, isQueued, noteTouched, scanRepo } from './scan'
79import type { FileWindow, Insight } from './screens/file'
80import { FILE_COMMENT, fileScreen } from './screens/file'
81import type { Shell } from './screens/frame'
82import { COMMENT_COLOR, TOP_MARGIN, frame, kitOf, moreBelow, stateOf } from './screens/frame'
83import { rowsBelow, rowsOf } from './rows'
84import type { GraphWindow } from './screens/graph'
85import { graphScreen } from './screens/graph'
86import { helpScreen } from './screens/help'
87import { listScreen } from './screens/list'
88import { isMarkdownFile, markdownScreen } from './screens/markdown'
89import type { ChangesWindow } from './screens/changes'
90import { changesScreen } from './screens/changes'
91import { overviewScreen } from './screens/overview'
92import { pictureScreen } from './screens/picture'
93import { recentsScreen } from './screens/recents'
94import { requestsScreen } from './screens/requests'
95import { treeScreen } from './screens/tree'
96import { foldOf } from './semantic'
97import type { Settings } from './settings'
98import { DEFAULTS, settingsOf } from './settings'
99import { readSource } from './source'
100import {
101  NO_CRUMB,
102  NO_LISTING,
103  NO_PICKED,
104  NO_SCAN,
105  NO_SOURCE,
106  NO_SYMBOL,
107  NO_VIEW,
108  changedDiags,
109  comparisonOf,
110  settledPicked,
111  settledScan,
112  settledView,
113  totalsOf,
114} from './state'
115import { stepShown } from './changes'
116import { clamp, foldEnd } from './text'
117
118const PANE = 'lens'
119
120// The parked mod's pane, which lens draws in while that mod hosts it. Parked
121// says so in its own `guest` state when a file of one of its items is opened:
122// the file is then read where the item was, with no other pane to switch to.
123// Parked draws its own rows above (the way back), and lens has the rest.
124const HOST = 'parked'
125const HOST_ROWS = 2
126const GUEST = { plugin: 'parked', key: 'guest' } as const
127const isGuest = ($: EngineInterface): Promise<boolean> =>
128  $.state.get(GUEST).then(
129    got => got.value === true,
130    () => false,
131  )
132// How many unchanged files opened from the tree of every file stay among
133// those checked.
134const EXTRA_FILES = 20
135// The most lines of code sent to the prompt with a review thread.
136const TALK_CODE = 80
137
138// The session's state. Its shapes are the contract's (types/index.d.ts) and
139// its defaults are in state.ts; the atoms are written here because the
140// engine reads a state reference only in the file that uses it.
141const view = atom({ plugin: 'lens', key: 'view' } as const, NO_VIEW)
142const scan = atom({ plugin: 'lens', key: 'scan' } as const, NO_SCAN)
143const source = atom({ plugin: 'lens', key: 'source' } as const, NO_SOURCE)
144const listing = atom({ plugin: 'lens', key: 'listing' } as const, NO_LISTING)
145const picked = atom({ plugin: 'lens', key: 'picked' } as const, NO_PICKED)
146// The repos reviewed lately, as the store holds them between sessions: the
147// copy the recents screen draws from, written by `rememberReview`,
148// `forgetReview` and the /lens command.
149const recents = atom({ plugin: 'lens', key: 'recents' } as const, [] as Recent[])
150// The frame of the busy mark, stepped by the timer while a scan runs.
151const spin = atom({ plugin: 'lens', key: 'spin' } as const, 0)
152const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
153
154// What the module holds beside the state. A reload of the mod drops all of
155// it, and each is asked for again where it is missed. Every one below is
156// written only by the function or hook its comment names; the rest of the
157// session's caches belong to the modules that fill them (the history and
158// the list of every file to scan.ts, the base's diagnostics to check.ts).
159
160// The person's settings, read from the module's options when it registers
161// (a change in the config menu loads the module again with the new ones).
162let settings: Settings = DEFAULTS
163
164// How the repo stood when it was last looked at (see `git.repoMark`), and
165// the timer's count of ticks: every so many, `watchRepo` looks again.
166let repoMarked: { repo: string; mark: string } | undefined
167let ticks = 0
168let isWatching = false
169// Ticks of the 400 ms timer between two looks at the repo: about 4 seconds.
170const WATCH_TICKS = 10
171
172// The scan queue, written by anything that wants a scan and taken by the
173// timer: a reload drops a waiting scan, and the next refresh asks again.
174let job: Job | undefined
175let isBusy = false
176
177// The open file's coloured lines, written by `loadSource`. A whole file is
178// too much to keep as state, so a reload loses them and the render hook asks
179// for them again through `wanted`, which the timer takes.
180let cache:
181  | {
182      path: string
183      // The commit the file was read at; '' for the working tree's.
184      commit: string
185      lines: Span[][]
186      removed: Record<number, string[]>
187      // Where the first of each run of removed lines was, in the base.
188      removedAt: Record<number, number>
189      // A commit's own changed lines; the working tree's come from the scan.
190      changed: LineRange[] | undefined
191    }
192  | undefined
193let wanted: string | undefined
194let isLoading = false
195
196// The commit or stash message as typed so far, and the comment being typed:
197// each field holds its own text, and these are the copies the buttons beside
198// it read. Written by the fields' actions, and cleared by `commitFiles`,
199// `stashFiles` and `postReview` once what was typed has been used.
200let draft = ''
201let draftBody = ''
202let commentDraft = ''
203// Whether anything has been typed since a comment was put in the field to be changed.
204let commentTouched = false
205// How many comments have been sent or dropped: see `FileModel.commentRound`.
206let commentRound = 0
207// The same for the review being written in the file tree's box.
208let reviewDraft = ''
209let reviewRound = 0
210// And for the comment on the request as a whole being written there.
211let talkDraft = ''
212let talkRound = 0
213
214// How the language-server bridge runs its commands, made by `serverRun` from
215// the first handle that needs it.
216let servers: ServerRun | undefined
217
218// What the language server knows of the file the file screen shows, written
219// by `loadInsight` (and dropped by `loadSource` for a commit's file). Read
220// after the file itself, so the file draws first and gains these.
221let insight: ({ path: string } & Insight) | undefined
222// The file `loadInsight` is reading for, while it is: the screen says so.
223let insightFor: string | undefined
224
225// Opens the pane on a file at a line, for another mod that names the place: a
226// path that is absolute, or from the session's folder. The repository the
227// file is in becomes the one under review, unless the folder under review
228// already holds the file.
229const showPlace = async ($: EngineInterface, named: string, line: number): Promise<void> => {
230  // Asked by a mod that is showing lens in its own pane, lens's own pane is
231  // left as it is: opening it would bring it forward whenever the prompt, and
232  // not the host's pane, happened to hold the keyboard.
233  const isHosted = await isGuest($)
234  const run = runOf($)
235  const root = await $.session.cwd().catch(() => '')
236  const full = placeOf(named, root)
237  const now = await read($, view)
238  let repo = now.repo !== '' && full.startsWith(`${now.repo}/`) ? now.repo : ''
239
240  if (repo === '') {
241    const top = await run(['git', '-C', full.replace(/\/[^/]*$/, ''), 'rev-parse', '--show-toplevel'])
242    // Outside any repository, the session's folder is listed where it holds
243    // the file.
244    repo = top.exitCode === 0 ? top.stdout.trim() : root
245
246    if (repo === '' || !full.startsWith(`${repo}/`)) {
247      $.ui.toast(`Lens: ${named} is not in a git repository or this session's folder`)
248
249      return
250    }
251
252    await openReview($, repo, undefined, isHosted)
253  }
254
255  const path = full.slice(repo.length + 1)
256
257  await loadSource($, repo, path)
258  await update(
259    $,
260    view,
261    (last): View => ({
262      ...last,
263      screen: 'file',
264      file: path,
265      commit: '',
266      origin: 'tree',
267      top: Math.max(1, line - 3),
268      cursor: -1,
269      isDiff: false,
270      isPreview: false,
271      symbol: NO_SYMBOL,
272      crumb: NO_CRUMB,
273    }),
274  )
275
276  if (!isHosted) {
277    await $.ui.open({ id: PANE, title: 'Lens', focus: true })
278  }
279}
280
281// The ledger mod's run, where that mod is loaded: its findings are drawn with
282// a request's comments.
283const LEDGER_RUN = { plugin: 'ledger', key: 'run' } as const
284
285// The comments on the pull or merge request under review, as the forge gave
286// them, with the folder under review's place in the repo (`prefix`). Written
287// by `loadComments`; `postReview` adds the comment it posted.
288let commentsCache: { key: string; prefix: string; comments: Comment[] } | undefined
289
290// The open request of the branch checked out, where it has one: its comments
291// show on the working tree's files without a comparison being set up.
292// Written by `findBranchRequest`, with each scan of the working tree.
293let branchRequest:
294  | {
295      repo: string
296      branch: string
297      typed: string
298      label: string
299      // What it is called, the branch it targets, and when the forge said so.
300      title: string
301      baseRef: string
302      url: string
303      at: number
304      // What the branch changes since it forked from that target, read
305      // again with every scan: the commit it forked at, and the files.
306      base: string
307      files: ChangedFile[]
308      stats: Record<string, LineStat>
309    }
310  | undefined
311
312// The repo's open pull or merge requests, for the compare panel to offer.
313// Written by `loadRequests`, when the panel opens.
314let requestsCache: { repo: string; list: Listed[] } | undefined
315// Whether the list is of the requests that are over (merged or closed) in
316// place of the open ones.
317let requestsPast = false
318
319// The whole comparison as one page, for the changes screen: what git said of
320// the repo, base and target in `key`. Written by `loadPatch`, when that
321// screen opens or is refreshed; `patchWanted` is the key being read.
322// `staged` is the marks of the hunks the index holds (see `hunkMark`).
323let patchCache: { key: string; files: PatchFile[]; refusal: string; staged: Set<string> } | undefined
324// How many unchanged lines each file expanded on that page shows round its
325// changes, by path, for the page in `key`; and how many each press adds.
326let pageMore: { key: string; by: Map<string, number> } = { key: '', by: new Map() }
327const MORE_STEP = 20
328// The hunk whose undoing the page is asking about, by its name; '' for none.
329let hunkAsked = ''
330let patchWanted: string | undefined
331// The files of that page as the highlighter coloured them, by path, and the
332// ones asked for: written by `colorPage` as each stretch of the page is drawn.
333let pageColors: { key: string; lines: Map<string, Span[][]>; asked: Set<string> } = {
334  key: '',
335  lines: new Map(),
336  asked: new Set(),
337}
338// How many files are highlighted at a time, and how many times one is asked
339// for before it is left plain; `colorTries` counts them, by page and path.
340const COLORED_AT_ONCE = 3
341const COLOR_TRIES = 3
342const colorTries = new Map<string, number>()
343// The changes screen's window as last drawn, for the scroll hook.
344let pageWindow: ChangesWindow = { maxTop: 0 }
345
346// The view with its count of asked-for drawings one higher: what a module
347// value changing (a list read, a file coloured) writes to have the pane
348// drawn again. A value written back unchanged is no change to draw for.
349const nudged = (last: View): View => ({ ...last, redraws: (last.redraws ?? 0) + 1 })
350
351// How many requests' ticks are kept between sessions.
352const REVIEWED_KEPT = 40
353// And how many ticked files of each.
354const REVIEWED_PATHS = 2000
355// How many lines of a request's description the file tree shows.
356const ABOUT_LINES = 3
357// The most comments one review holds unsent.
358const DRAFTS_KEPT = 200
359
360// What the folder the breadcrumb last opened holds, written by `loadCrumb`.
361let crumbCache: { dir: string; entries: string[] } | undefined
362
363// Who last changed each line of the file the blame column was asked for,
364// written by `loadBlame`.
365let blameCache: { path: string; commit: string; lines: Blamed[] } | undefined
366
367// What the render hook leaves for the scroll hook and the timer: the graph's
368// and the file's windows as last drawn (see `GraphWindow`, `FileWindow`),
369// and whether the pane's own scroll needs holding one row down, for a screen
370// that draws its own window; the drawing asks, the timer does it.
371let graphWindow: GraphWindow = { header: 0, kinds: [], maxTop: 0, bodyMax: 0 }
372let fileWindow: FileWindow = { maxTop: 1, shown: undefined, crumbBox: undefined }
373let wantPin = false
374// How many rows the last drawing of a screen the pane scrolls was reckoned
375// to take, and what the engine then said it took (see `rowsBelow`).
376let paneEstimate = 0
377let paneMeasured: { content: number; estimate: number } | undefined
378
379const noteEdit = async ($: EngineInterface, path: string): Promise<void> => {
380  const { repo, isTelling } = await read($, view)
381
382  if (repo !== '' && path.startsWith(`${repo}/`)) {
383    job = { isProject: false }
384
385    if (isTelling ?? false) {
386      noteTouched(path.slice(repo.length + 1))
387    }
388  }
389}
390
391// Every command of the session is run through this: the handle's own
392// `process.run`, made never to reject (see `Run`).
393const runOf =
394  ($: EngineInterface): Run =>
395  (argv, init) =>
396    $.process
397      .run(argv, init ?? {})
398      .catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: String(error) }))
399
400// The open file where it is a picture: itself and what it was before, each
401// as a file the terminal draws, or undefined where there is none to draw.
402let shot:
403  | { path: string; commit: string; now: Picture | undefined; before: Picture | undefined; against: string }
404  | undefined
405
406// Reads a whole file as coloured lines and keeps it for the file screen, with
407// what the diff view interleaves.
408//
409// With a `commit` the file is read as that commit left it, and its diff is
410// what the commit changed; without one it is the working tree's file, against
411// the base.
412const loadSource = async (
413  $: EngineInterface,
414  repo: string,
415  path: string,
416  commit = '',
417): Promise<void> => {
418  const run = runOf($)
419
420  // A picture is not read as text: it is made a file the terminal draws,
421  // and so is what it was on the other side, where it was a different one.
422  if (isPictureFile(path)) {
423    const { base, target, diffBase } = await read($, view)
424    const own = commit === '' && diffBase?.path === path && diffBase.base !== '' ? diffBase.base : ''
425    const other = commit === '' ? own || base || 'HEAD' : commit === target && base !== '' ? base : `${commit}^`
426    const [now, was] = await Promise.all([localPicture(run, repo, path, commit), localPicture(run, repo, path, other)])
427
428    shot = {
429      path,
430      commit,
431      now,
432      before: was !== undefined && was.file !== now?.file ? was : undefined,
433      against: /^[0-9a-f]{40}$/.test(other) ? other.slice(0, 8) : other,
434    }
435    cache = { path, commit, lines: [], removed: {}, removedAt: {}, changed: undefined }
436    insight = undefined
437    const stamp = await $.clock.now()
438    await update($, source, () => ({ path, lineCount: 0, note: '', stamp }))
439
440    return
441  }
442
443  const committed = commit === '' ? undefined : await git.fileAt(run, repo, path, commit)
444  const { lines, note } = await readSource(
445    run,
446    file => $.fs.read(file).catch(() => ''),
447    repo,
448    path,
449    committed,
450  )
451  const { base, target, diffBase } = await read($, view)
452  // A file of the branch's request is read against where the request forked.
453  const own = commit === '' && diffBase?.path === path && diffBase.base !== '' ? diffBase.base : ''
454  const diff = await git.fileDiff(run, repo, path, commit, own || base, target ?? '', own !== '')
455
456  cache = { path, commit, lines, removed: diff.removed, removedAt: diff.removedAt, changed: diff.changed }
457  const stamp = await $.clock.now()
458  await update($, source, () => ({ path, lineCount: lines.length, note, stamp }))
459
460  // What the language server adds comes after, so the file is not kept
461  // waiting for it; only the working tree's files are on disk for a server.
462  if (commit === '') {
463    void loadInsight($, repo, path)
464  } else {
465    insight = undefined
466  }
467}
468
469// The repos reviewed lately, as the store holds them.
470const readRecents = async ($: EngineInterface): Promise<Recent[]> =>
471  settledRecents(await $.store.get('recents').catch(() => undefined))
472
473// Keeps the review as it stands (its repo, comparison and layout) for the
474// sessions to come, where the person has not switched remembering off.
475const rememberReview = async ($: EngineInterface): Promise<void> => {
476  const now = await read($, view)
477
478  if (!settings.remembers || now.repo === '') {
479    return
480  }
481
482  const list = remember(
483    await readRecents($),
484    recentOf(now, await $.clock.now(), await git.mainRepoOf(runOf($), now.repo)),
485  )
486
487  await $.store.set('recents', list).catch(() => undefined)
488  await update($, recents, () => list)
489}
490
491const forgetReview = async ($: EngineInterface, repo: string): Promise<void> => {
492  const list = (await readRecents($)).filter(one => one.repo !== repo)
493
494  await $.store.set('recents', list).catch(() => undefined)
495  await update($, recents, () => list)
496}
497
498// Starts a review of a repo and opens the pane on it. With no `base` named,
499// the repo is picked up where it was last left: its layout, and its
500// comparison where git still knows both sides (a pull or merge request is
501// fetched again). Answers what it did, in a sentence.
502const openReview = async (
503  $: EngineInterface,
504  repo: string,
505  base: string | undefined,
506  // Set where another mod's pane is to show the review: the pane is not opened.
507  isHosted = false,
508): Promise<string> => {
509  const kept =
510    base === undefined && settings.remembers
511      ? (await readRecents($)).find(one => one.repo === repo)
512      : undefined
513
514  await update($, view, () => ({
515    ...NO_VIEW,
516    repo,
517    base: base ?? 'HEAD',
518    layout: kept?.layout ?? 'tree',
519    isBrowsing: kept?.isBrowsing ?? false,
520  }))
521  // The ticks of the requests reviewed before come back with the review.
522  void readReviewed($).then(reviewed => update($, view, (last): View => ({ ...last, reviewed })))
523  // And the comments written for a review and not sent yet.
524  void readDrafts($).then(drafts => update($, view, (last): View => ({ ...last, drafts })))
525  await update($, scan, () => ({ ...NO_SCAN, status: 'running' }))
526  job = { isProject: false }
527
528  if (!isHosted) {
529    await $.ui.open({ id: PANE, title: 'Lens', focus: true })
530  }
531
532  // A folder git does not know has nothing to compare: its files are listed.
533  if ((await git.findRepo(runOf($), repo)) === '') {
534    return `Listing ${repo}, which is not in a git repository: its code files are checked, and nothing is compared.`
535  }
536
537  if (kept === undefined || (kept.base === 'HEAD' && kept.target === '')) {
538    return `Reviewing ${repo} against ${base ?? 'HEAD'}.`
539  }
540
541  if (kept.requestTyped !== '') {
542    void startCompare($, repo, '', kept.requestTyped)
543
544    return `Reviewing ${repo}: fetching ${kept.requestTyped} again, as you left it.`
545  }
546
547  const run = runOf($)
548  const isKnown =
549    (await git.isCommit(run, repo, kept.base)) &&
550    (kept.target === '' || (await git.isCommit(run, repo, kept.target)))
551
552  if (!isKnown) {
553    return `Reviewing ${repo} against HEAD (what it was last compared with is gone).`
554  }
555
556  await update($, view, (last): View => ({ ...last, base: kept.base, target: kept.target }))
557  job = { isProject: false }
558
559  return `Reviewing ${repo}: ${kept.target === '' ? 'the working tree' : kept.target} against ${kept.base}, as you left it.`
560}
561
562// Scans again when the repo has changed under the pane: a commit, a
563// checkout, a merge, an edit or a stash made anywhere (Claude's own shell,
564// another terminal, an editor). Only while the pane is open, and never
565// while a scan is running or waiting.
566const watchRepo = async ($: EngineInterface): Promise<void> => {
567  const { repo } = await read($, view)
568
569  if (repo === '' || isBusy || job !== undefined) {
570    return
571  }
572
573  const open = await $.ui.panes().catch(() => [])
574
575  if (!open.some(one => one.id === PANE)) {
576    return
577  }
578
579  const mark = await git.repoMark(runOf($), repo)
580
581  if (mark === '') {
582    return
583  }
584
585  // The first look only notes how things stand: the scan that opened the
586  // review has just read them.
587  if (repoMarked !== undefined && repoMarked.repo === repo && repoMarked.mark !== mark) {
588    job ??= { isProject: false }
589  }
590
591  repoMarked = { repo, mark }
592}
593
594// Runs one scan with this handle. The pipeline itself is in scan.ts; what
595// it reads and writes of the session goes through the ports made here.
596const runScan = async ($: EngineInterface, taken: Job): Promise<void> => {
597  const now = await read($, view)
598
599  // Every change of what is compared starts a scan, so this is where the
600  // review is kept for next time.
601  void rememberReview($)
602
603  // With no request under review, the branch checked out may have one open:
604  // its comments are then read as a request's are.
605  const requestTyped =
606    (now.target ?? '') !== '' && (now.requestTyped ?? '') !== ''
607      ? now.requestTyped
608      : (now.target ?? '') === ''
609        ? await findBranchRequest($, now.repo)
610        : ''
611
612  // A comparison with another worktree is with its files as they stand now:
613  // they are read again, and the scan runs against that.
614  let base = now.base
615
616  if ((now.baseWorktree ?? '') !== '') {
617    const taken = await git.snapshotWorktree(runOf($), now.baseWorktree)
618
619    if (taken.hash !== '' && taken.hash !== base) {
620      base = taken.hash
621      await update($, view, (last): View => ({ ...last, base }))
622    }
623  }
624
625  await scanRepo(
626    {
627      run: runOf($),
628      servers: serverRun($),
629      readFile: path => $.fs.read(path).catch(() => ''),
630      readScan: () => read($, scan),
631      writeScan: change => update($, scan, change),
632      onListed: async () => {
633        if (now.screen === 'file') {
634          await loadSource($, now.repo, now.file, now.commit ?? '')
635        }
636      },
637      readComments: typed => loadComments($, now.repo, typed),
638      showStatus: text => {
639        $.ui.status(text === '' ? undefined : text)
640      },
641      tellClaude: text =>
642        $.session
643          .append({ message: { type: 'user', content: [{ type: 'text', text }] } })
644          .catch(() => undefined),
645      // The file being read, where it is the side the checkers run over.
646      openFile: async () => {
647        const { screen, file, commit, target } = await read($, view)
648
649        return screen === 'file' && (commit ?? '') === (target ?? '') ? file : ''
650      },
651      isOvertaken: () => job !== undefined,
652    },
653    {
654      repo: now.repo,
655      base,
656      target: now.target ?? '',
657      extra: now.extra ?? [],
658      isBrowsing: now.isBrowsing ?? false,
659      isTelling: now.isTelling ?? false,
660      requestTyped,
661      use: settings.checkers,
662      marksNew: settings.marksNew,
663    },
664    taken,
665  )
666}
667
668// Throws away the uncommitted changes in the given files, which cannot be
669// undone, and scans again whatever happened.
670const discardFiles = async (
671  $: EngineInterface,
672  repo: string,
673  tracked: string[],
674  staged: string[],
675  untracked: string[],
676): Promise<void> => {
677  const refusal = await git.discard(runOf($), repo, tracked, staged, untracked)
678  const count = tracked.length + staged.length + untracked.length
679
680  $.ui.toast(
681    refusal === '' ? `Discarded the changes in ${count} ${count === 1 ? 'file' : 'files'}` : refusal,
682    { timeoutMs: refusal === '' ? 4000 : 10_000 },
683  )
684  await update($, view, last => ({ ...last, checked: [], isDiscarding: false }))
685  job = { isProject: false }
686}
687
688// How the language-server bridge runs its commands: kept for the session, so
689// the bridge's script is written once.
690const serverRun = ($: EngineInterface): ServerRun => (servers ??= runOf($))
691
692// Reads what the language server knows of a whole file, for the file screen:
693// its outline (exact folds, the breadcrumb), what each name is (colours), the
694// file's own lines (a server counts a tab as one column, the screen draws
695// four), and, when they are switched on, its inlay hints. A file outside the
696// folder under review, or of a kind no server reads, has none.
697const loadInsight = async ($: EngineInterface, repo: string, path: string): Promise<void> => {
698  if (path.startsWith('/') || !isServed(path)) {
699    insight = undefined
700
701    return
702  }
703
704  const run = serverRun($)
705
706  insightFor = path
707
708  const { isHinting } = await read($, view)
709  const [raw, outline, semantic, hinted] = await Promise.all([
710    $.fs.read(`${repo}/${path}`).catch(() => ''),
711    lspOutline(run, repo, path),
712    lspSemanticTokens(run, repo, path),
713    (isHinting ?? false) ? lspInlayHints(run, repo, path, 1, 1_000_000) : undefined,
714  ])
715  const tokens = new Map<number, SemanticToken[]>()
716  const hints = new Map<number, InlayHint[]>()
717
718  for (const token of semantic.tokens) {
719    tokens.set(token.line, [...(tokens.get(token.line) ?? []), token])
720  }
721
722  for (const hint of hinted?.hints ?? []) {
723    hints.set(hint.line, [...(hints.get(hint.line) ?? []), hint])
724  }
725
726  insight = { path, raw: raw.split('\n'), items: outline.items, tokens, hints }
727
728  if (insightFor === path) {
729    insightFor = undefined
730  }
731
732  // The file screen reads the source's stamp: a new one redraws it.
733  await update($, source, last => ({ ...last, stamp: last.stamp + 1 }))
734
735  if ((isHinting ?? false) && (hinted?.hints.length ?? 0) === 0 && (hinted?.notes.length ?? 0) > 0) {
736    $.ui.toast(hinted?.notes[0] ?? '', { timeoutMs: 6000 })
737  }
738}
739
740// Shows a list of places (or anything with a place) on the list screen; one
741// with nothing in it is said in a toast instead, with the server's reason
742// (`notes`) where it gave one.
743const showList = async (
744  $: EngineInterface,
745  { title, rows, prompt, commit }: Listing,
746  notes: readonly string[],
747): Promise<void> => {
748  if (rows.length === 0) {
749    $.ui.toast(notes[0] ?? `${title}: nothing found`, { timeoutMs: 6000 })
750
751    return
752  }
753
754  await update($, listing, () => ({
755    title,
756    rows: rows.slice(0, LIST_ROWS),
757    prompt,
758    ...(commit === undefined ? {} : { commit }),
759  }))
760  // Back from the list returns to the screen it was asked for on.
761  await update(
762    $,
763    view,
764    (last): View => ({
765      ...last,
766      screen: 'list',
767      listBack: last.screen === 'list' ? (last.listBack ?? 'file') : last.screen === 'tree' ? 'tree' : 'file',
768    }),
769  )
770}
771
772// Everywhere the looked-up name is used.
773const listReferences = async ($: EngineInterface, repo: string, at: Lookup): Promise<void> => {
774  const answer = await lspReferences(serverRun($), repo, at.file, at.at, at.col)
775
776  await showList($, usesList(at.name, at.file, answer.places), answer.notes)
777}
778
779// Who calls the looked-up function, or what it calls.
780const listCalls = async (
781  $: EngineInterface,
782  repo: string,
783  at: Lookup,
784  direction: 'incoming' | 'outgoing',
785): Promise<void> => {
786  const answer = await lspCalls(serverRun($), repo, at.file, at.at, at.col, direction)
787
788  await showList($, callsList(at.name, direction, answer.calls), answer.notes)
789}
790
791// What implements the looked-up interface, abstract method or protocol.
792const listImplementations = async ($: EngineInterface, repo: string, at: Lookup): Promise<void> => {
793  const answer = await lspSymbol(serverRun($), repo, at.file, at.at, at.col)
794
795  await showList(
796    $,
797    implementationsList(at.name, answer.implementations ?? []),
798    answer.notes.length > 0 ? answer.notes : ['The language server knows of none'],
799  )
800}
801
802// Names anywhere in the project that match what was typed. `near` is a file
803// of the project to search: it decides the language and the project.
804const searchSymbols = async (
805  $: EngineInterface,
806  repo: string,
807  query: string,
808  near: string,
809): Promise<void> => {
810  if (query.trim() === '') {
811    return
812  }
813
814  if (near === '') {
815    $.ui.toast('There is no Python or TypeScript file here to search from')
816
817    return
818  }
819
820  const answer = await lspWorkspaceSymbols(serverRun($), repo, query.trim(), near, {
821    limit: LIST_ROWS,
822  })
823
824  await showList($, namesList(query.trim(), answer.hits), answer.notes)
825}
826
827// Asks the language server what a name on a line of a file is, and keeps the
828// answer for the file screen to show. The column is found on the file's own
829// text: the screen draws a tab as spaces, which a server does not count.
830const lookUp = async (
831  $: EngineInterface,
832  repo: string,
833  file: string,
834  line: number,
835  name: string,
836): Promise<void> => {
837  const raw = await $.fs.read(`${repo}/${file}`).catch(() => '')
838  const col = Math.max(0, (raw.split('\n')[line - 1] ?? '').indexOf(name)) + 1
839  const answer = await lspSymbol(serverRun($), repo, file, line, col)
840
841  if (answer.text === '' && answer.notes.length > 0) {
842    $.ui.toast(answer.notes[0] ?? 'The language server did not answer', { timeoutMs: 8000 })
843
844    return
845  }
846
847  await update($, view, last => ({ ...last, symbol: lookupOf(file, name, line, col, answer) }))
848}
849
850// Reads what a folder of the folder under review holds, for the breadcrumb's
851// list: folders first (their names end with a slash), then files, git's own
852// folder left out. `left` is the column the list opens under.
853const loadCrumb = async (
854  $: EngineInterface,
855  repo: string,
856  dir: string,
857  left: number,
858): Promise<void> => {
859  const ran = await runOf($)(['ls', '-1Ap', '--', dir === '' ? '.' : dir], { cwd: repo })
860
861  if (ran.exitCode !== 0) {
862    $.ui.toast(`That folder could not be read: ${tail(ran.stderr)}`, { timeoutMs: 6000 })
863
864    return
865  }
866
867  const names = ran.stdout.split('\n').filter(name => name !== '' && name !== '.git/')
868
869  crumbCache = {
870    dir,
871    entries: [
872      ...names.filter(name => name.endsWith('/')),
873      ...names.filter(name => !name.endsWith('/')),
874    ],
875  }
876  await update(
877    $,
878    view,
879    (last): View => ({ ...last, crumb: { kind: 'dir', dir, level: 0, left, top: -1 } }),
880  )
881}
882
883// Reads who last changed each line of a file (as a commit left it, or as the
884// working tree has it) and keeps it for the file screen's blame column.
885const loadBlame = async (
886  $: EngineInterface,
887  repo: string,
888  path: string,
889  commit: string,
890): Promise<void> => {
891  const answer = await git.blame(runOf($), repo, path, commit, () => $.clock.now())
892
893  if ('refusal' in answer) {
894    $.ui.toast(`git blame did not go through: ${answer.refusal}`, { timeoutMs: 8000 })
895
896    return
897  }
898
899  blameCache = { path, commit, lines: answer.lines }
900  await update($, view, last => ({ ...last, isBlame: true }))
901}
902
903// Asks before undoing the last commit, saying whether it has been pushed:
904// one that has stays on the remote, and the branch here falls behind it.
905const askUndo = async ($: EngineInterface, repo: string): Promise<void> => {
906  const pushed = await git.remotesWithHead(runOf($), repo)
907
908  await update($, view, last => ({
909    ...last,
910    isUndoing: true,
911    undoNote:
912      pushed.length === 0
913        ? 'It has not been pushed, so nothing else has it.'
914        : `It is already on ${pushed[0] ?? 'a remote'}: undoing it here leaves it there, and this branch behind it.`,
915  }))
916}
917
918// Takes the last commit back and keeps what it changed, as uncommitted edits.
919const undoCommit = async ($: EngineInterface, repo: string): Promise<void> => {
920  await report(
921    $,
922    await git.undoLastCommit(runOf($), repo),
923    'Undid the last commit; its changes are uncommitted again',
924  )
925  await update($, view, last => ({ ...last, isUndoing: false, selected: '' }))
926}
927
928// Adds text to the end of the person's draft, on its own line, and never
929// submits it: sending stays theirs.
930const sendToComposer = async ($: EngineInterface, text: string): Promise<void> => {
931  const draft = await $.prompt.read().then(
932    box => box.text,
933    () => '',
934  )
935  const lead = draft === '' || draft.endsWith('\n') ? '' : '\n'
936  const filled = await $.prompt.fill({ text: `${lead}${text}\n`, mode: 'append' })
937
938  $.ui.toast(
939    filled.isFilled
940      ? 'Added to the prompt'
941      : `Could not add to the prompt${filled.refusal === undefined ? '' : ` (${filled.refusal})`}`,
942  )
943}
944
945// Says how a git command that changes the repo went: `done` on success, the
946// command's `refusal` (git's own last words) where it has one. A success
947// clears the ticks and scans again, since the working tree is no longer what
948// the pane shows.
949const report = async ($: EngineInterface, refusal: string, done: string): Promise<boolean> => {
950  if (refusal !== '') {
951    $.ui.toast(refusal, { timeoutMs: 10_000 })
952
953    return false
954  }
955
956  $.ui.toast(done)
957  await update($, view, last => ({ ...last, checked: [] }))
958  job = { isProject: false }
959
960  return true
961}
962
963// Commits the ticked files and nothing else.
964const commitFiles = async (
965  $: EngineInterface,
966  repo: string,
967  paths: readonly string[],
968  message: string,
969  body = '',
970): Promise<void> => {
971  if (message.trim() === '') {
972    $.ui.toast('Type a commit message first')
973
974    return
975  }
976
977  if (
978    await report(
979      $,
980      await git.commit(runOf($), repo, paths, message, body),
981      `Committed ${paths.length} ${paths.length === 1 ? 'file' : 'files'}`,
982    )
983  ) {
984    draft = ''
985    draftBody = ''
986  }
987}
988
989// Stashes the ticked files, the untracked ones among them included.
990const stashFiles = async (
991  $: EngineInterface,
992  repo: string,
993  paths: readonly string[],
994  message: string,
995): Promise<void> => {
996  const label = message.trim() || `${paths.length} ${paths.length === 1 ? 'file' : 'files'}`
997
998  if (
999    await report(
1000      $,
1001      await git.stash(runOf($), repo, paths, label),
1002      `Stashed ${paths.length} ${paths.length === 1 ? 'file' : 'files'}`,
1003    )
1004  ) {
1005    draft = ''
1006  }
1007}
1008
1009const applyStash = async (
1010  $: EngineInterface,
1011  repo: string,
1012  ref: string,
1013  isPop: boolean,
1014): Promise<void> => {
1015  await report(
1016    $,
1017    await git.restoreStash(runOf($), repo, ref, isPop),
1018    isPop ? `Popped ${ref}` : `Applied ${ref}`,
1019  )
1020}
1021
1022// How the forge module runs its commands: in the folder under review.
1023const forgeRun =
1024  (run: Run, repo: string): ForgeRun =>
1025  (argv, timeoutMs = 60_000, stdin) =>
1026    run(argv, { cwd: repo, timeoutMs, ...(stdin === undefined ? {} : { stdin }) })
1027
1028// How long what the forge said of a branch's request is taken as still so.
1029const BRANCH_REQUEST_MS = 5 * 60_000
1030
1031// Finds the open request of the branch checked out, asking the forge at most
1032// once in a while for the same branch; '' when it has none.
1033const findBranchRequest = async ($: EngineInterface, repo: string): Promise<string> => {
1034  const run = runOf($)
1035  const branch = (await run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repo })).stdout.trim()
1036  const at = await $.clock.now()
1037
1038  if (
1039    branchRequest === undefined ||
1040    branchRequest.repo !== repo ||
1041    branchRequest.branch !== branch ||
1042    at - branchRequest.at > BRANCH_REQUEST_MS
1043  ) {
1044    const found = await requestOfBranch(forgeRun(run, repo), branch)
1045
1046    branchRequest = {
1047      repo,
1048      branch,
1049      typed: found?.typed ?? '',
1050      label: found?.label ?? '',
1051      title: found?.title ?? '',
1052      baseRef: found?.baseRef ?? '',
1053      url: found?.url ?? '',
1054      at,
1055      base: '',
1056      files: [],
1057      stats: {},
1058    }
1059  }
1060
1061  // The forge's word is kept a while; what the branch changes is git's to
1062  // say, and a commit made since changes it.
1063  if (branchRequest.typed !== '' && branchRequest.baseRef !== '') {
1064    Object.assign(branchRequest, await git.requestChanges(run, repo, branchRequest.baseRef))
1065  }
1066
1067  return branchRequest.typed
1068}
1069
1070// Asks the forge for the repo's open requests and has the compare panel,
1071// which is already open, drawn again with them.
1072// The overview of the request under review, as the forge gave it, or why it
1073// did not. Written by `loadOverview`, when the overview screen opens.
1074let overviewCache: { key: string; overview: Overview | undefined; refusal: string } | undefined
1075let overviewWanted: string | undefined
1076// Who is signed in to the forge for a repo, by the name comments carry: read
1077// once for each, by `loadMe`, so the person's own comments can be told.
1078let meCache: { repo: string; me: string } | undefined
1079let meWanted = ''
1080
1081const loadMe = async ($: EngineInterface, repo: string): Promise<void> => {
1082  meWanted = repo
1083  meCache = { repo, me: await whoAmI(forgeRun(runOf($), repo)) }
1084  await update($, view, nudged)
1085}
1086// The action on a request the overview is asking about before it is done
1087// (of which request, and which), and whether one is under way.
1088// The request being opened from the list, as it is typed; '' for none.
1089let requestOpening = ''
1090// The request whose every commit the overview lists, by its key; '' for none.
1091let commitsOpen = ''
1092// The same for all of its conversation, and for every thread on its files.
1093let talkAll = ''
1094let threadsAll = ''
1095let requestAsked: { key: string; act: RequestAct | '' } = { key: '', act: '' }
1096let requestActing = false
1097
1098// The pictures of descriptions, by their address: fetched (the file that
1099// holds each), being fetched, or not drawable. Held for the session, and
1100// held to a size: the oldest go when it is passed.
1101const pictureCache = new Map<string, Picture | 'loading' | 'none'>()
1102const PICTURES_KEPT = 200
1103
1104// Lets the oldest pictures go once more are held than are kept.
1105const trimPictures = (): void => {
1106  if (pictureCache.size > PICTURES_KEPT) {
1107    for (const old of [...pictureCache.keys()].slice(0, pictureCache.size - PICTURES_KEPT)) {
1108      pictureCache.delete(old)
1109    }
1110  }
1111}
1112
1113// How a request stands, in a few parts for a row of the file tree: its
1114// checks (the worst of them says how they stand), what its reviews come to,
1115// and whether it merges. Each part is the state that colours it, in the
1116// forge's own word, and the words to say.
1117const standingOf = (overview: Overview | undefined): [state: string, words: string][] => {
1118  if (overview === undefined) {
1119    return []
1120  }
1121
1122  const marks = overview.checks.map(check => stateOf(check.state)[0])
1123  const failed = marks.filter(mark => mark === '✖').length
1124  const going = marks.filter(mark => mark === '●').length
1125
1126  return [
1127    ...(overview.checks.length === 0
1128      ? [['NONE', 'no checks'] as [string, string]]
1129      : [
1130          failed > 0
1131            ? (['FAILURE', `${failed} of ${marks.length} checks fail`] as [string, string])
1132            : going > 0
1133              ? (['PENDING', `${going} of ${marks.length} checks running`] as [string, string])
1134              : (['SUCCESS', `${marks.length} ${marks.length === 1 ? 'check passes' : 'checks pass'}`] as [string, string]),
1135        ]),
1136    ...(overview.decision === ''
1137      ? []
1138      : [[overview.decision, overview.decision.toLowerCase().replace(/_/g, ' ')] as [string, string]]),
1139    ...(overview.mergeable === ''
1140      ? []
1141      : [[overview.mergeable, overview.mergeable.toLowerCase().replace(/_/g, ' ')] as [string, string]]),
1142  ]
1143}
1144
1145const loadOverview = async ($: EngineInterface, repo: string, typed: string): Promise<void> => {
1146  const key = `${repo}\n${typed}`
1147
1148  overviewWanted = key
1149
1150  const answer = await readOverview(forgeRun(runOf($), repo), typed)
1151
1152  if (overviewWanted === key) {
1153    overviewWanted = undefined
1154    overviewCache =
1155      'error' in answer
1156        ? { key, overview: undefined, refusal: plain(answer.error).slice(0, 300) }
1157        : { key, overview: answer.overview, refusal: '' }
1158    await update($, view, nudged)
1159  }
1160}
1161
1162const loadRequests = async ($: EngineInterface, repo: string): Promise<void> => {
1163  const isPast = requestsPast
1164  const list = await listRequests(forgeRun(runOf($), repo), isPast)
1165
1166  // An answer for the other list, asked for before the switch, is let go.
1167  if (isPast === requestsPast) {
1168    requestsCache = { repo, list }
1169  }
1170  await update($, view, nudged)
1171}
1172
1173// Reads the whole comparison for the changes screen and has it drawn again.
1174const loadPatch = async (
1175  $: EngineInterface,
1176  repo: string,
1177  base: string,
1178  target: string,
1179  key: string,
1180  context: number,
1181  ignoresSpace: boolean,
1182): Promise<void> => {
1183  patchWanted = key
1184
1185  // With the working tree's own changes, what the index holds is read
1186  // beside them, the same way, to say which hunks are staged.
1187  const [read, index] = await Promise.all([
1188    readPatch(runOf($), repo, base, target, { context, ignoresSpace }),
1189    target === '' && !ignoresSpace
1190      ? readPatch(runOf($), repo, base, '', { context, isStaged: true })
1191      : Promise.resolve({ files: [], refusal: '' }),
1192  ])
1193
1194  // A comparison asked for since is the one that counts.
1195  if (patchWanted === key) {
1196    patchCache = {
1197      key,
1198      ...read,
1199      staged: new Set(index.files.flatMap(file => file.hunks.map(hunk => hunkMark(file, hunk)))),
1200    }
hooks/check.ts 870 lines
1// Checking: given the files of a change, what is wrong with them, and which
2// of it the change brought.
3//
4// Which tools exist is this module's own business. The language servers are
5// asked first and the command-line checkers (ruff, pyright, tsc, eslint,
6// terraform) cover what they could not; a file of any other language is
7// checked by its language server alone, when the bridge has one that is
8// installed. Each tool is run in the project its
9// files belong to, and the base's version of a file is checked in an export
10// of that commit, which git.ts makes. A caller sees diagnostics, notes on what could not run,
11// and the names of the tools still out, and nothing of how any of it is done.
12// The parsers are exported for their tests.
13
14import type { ChangedFile, Diag, Severity } from '../types'
15import { exportCommit, trackedFiles } from './git'
16import type { Run as ServerRun } from './lsp'
17import {
18  isOtherServed,
19  lspDiagnostics,
20  lspIsRunning,
21  lspServed,
22  servedTools,
23  unservedNotes,
24} from './lsp'
25import type { Run } from './run'
26import { FILE_LIMIT, tail } from './run'
27import type { Checkers } from './settings'
28
29const PYTHON = /\.pyi?$/
30const TYPESCRIPT = /\.[cm]?tsx?$/
31const TERRAFORM = /\.(tf|tfvars)$/i
32// The names the language servers' diagnostics carry as their tool.
33const SERVER_TOOLS = ['pyright', 'tsserver', 'terraform-ls', 'terraform']
34// What the language servers' own run is called while it is out.
35const SERVERS = 'language servers'
36
37// tsc and eslint start with `#!/usr/bin/env node`, and a Node installed
38// through nvm is not on the PATH of a process started outside a login shell.
39const WITH_NODE = [
40  'sh',
41  '-c',
42  'command -v node >/dev/null || for d in "$HOME"/.nvm/versions/node/*/bin; do [ -x "$d/node" ] && PATH="$d:$PATH"; done; exec "$@"',
43  'sh',
44]
45
46// For each file after the marker list, prints "file<tab>folder": the nearest
47// folder at or above the file that holds one of the markers, or "." for none.
48const NEAREST = `markers="$1"; shift
49for f in "$@"; do
50  d=$(dirname "$f")
51  while :; do
52    for m in $markers; do
53      if [ -e "$d/$m" ]; then printf '%s\\t%s\\n' "$f" "$d"; continue 3; fi
54    done
55    [ "$d" = "." ] && break
56    d=$(dirname "$d")
57  done
58  printf '%s\\t.\\n' "$f"
59done`
60
61// Whether the language servers are switched on, as the last scan had it: a
62// file of another language has no checker but its server.
63let areServersUsed = true
64
65// Whether a file of another language than the three above is checked: by its
66// language server, when one is installed and the servers are switched on.
67const isOther = (path: string): boolean => areServersUsed && isOtherServed(path)
68
69// Asks the bridge again which other languages it has an installed server for
70// (the screens ask `isCheckable` as they draw, and cannot wait for it), and
71// notes whether the servers are switched on. Resolves with what is wrong
72// with the person's config file; never rejects.
73export const refreshServed = async (servers: ServerRun, isUsed: boolean): Promise<string[]> => {
74  areServersUsed = isUsed
75
76  const notes = await lspServed(servers)
77
78  return isUsed ? notes : []
79}
80
81// One line for each language among `wanted` that would be checked were its
82// server installed, saying what to install.
83export const uncheckedNotes = (wanted: readonly string[]): string[] =>
84  areServersUsed ? unservedNotes(wanted) : []
85
86// Whether a file is of a kind some checker reads; one that is not has
87// nothing to say, which is not the same as being clean.
88export const isCheckable = (path: string): boolean =>
89  PYTHON.test(path) || TYPESCRIPT.test(path) || TERRAFORM.test(path) || isOther(path)
90
91// Whether a file is of a language whose server can search the project's names.
92export const hasNameSearch = (path: string): boolean =>
93  PYTHON.test(path) || TYPESCRIPT.test(path) || isOtherServed(path)
94
95// Whether a file's own checkers are among those still out: `pending` is the
96// tools a check has started and not finished, as `Progress` named them.
97export const isAwaited = (path: string, pending: readonly string[]): boolean =>
98  pending.some(tool =>
99    tool.startsWith(SERVERS)
100      ? isCheckable(path)
101      : PYTHON.test(path)
102        ? tool.startsWith('ruff') || tool.startsWith('pyright')
103        : TERRAFORM.test(path)
104          ? tool.startsWith('terraform')
105          : TYPESCRIPT.test(path) && (tool.startsWith('tsc') || tool.startsWith('eslint')),
106  )
107
108// The tools (as a diagnostic's `tool` names them) whose answers the pending
109// ones will bring: what they found last time is not yet replaced.
110export const toolsAwaited = (pending: readonly string[]): Set<string> =>
111  new Set(
112    pending.flatMap(tool =>
113      tool.startsWith(SERVERS) ? [...SERVER_TOOLS, ...servedTools()] : [tool.split(' ')[0] ?? ''],
114    ),
115  )
116
117// Told as each tool starts and finishes, with everything found so far, so a
118// caller can show results as they come in.
119export type Progress = {
120  start: (tool: string) => void
121  done: (tool: string, found: Diag[]) => void
122}
123
124export type Ports = {
125  run: Run
126  // How the language servers' bridge runs its commands.
127  servers: ServerRun
128  // A file's text by its absolute path; '' for one that cannot be read.
129  readFile: (path: string) => Promise<string>
130}
131
132// What to check: the files `wanted` (relative to `repo`) of a comparison of
133// `base` with the working tree or, when `target.ref` is not '', with that
134// commit. `short` is each side's short hash, '' where git knows none; `files`
135// is what differs between the sides. `isProject` asks for every file of
136// every project, changed or not.
137export type Ask = {
138  repo: string
139  base: { ref: string; short: string }
140  target: { ref: string; short: string }
141  files: readonly ChangedFile[]
142  wanted: readonly string[]
143  isProject: boolean
144  // The checkers the person has left switched on, and whether the base is
145  // checked too, to mark each diagnostic new or already there.
146  use: Checkers
147  marksNew: boolean
148}
149
150// What the checkers said about the base's version of the files last asked
151// about, and those files' lines there. Kept while the base and the files
152// stay the same, so an edit re-checks the working tree alone.
153let before: { key: string; diags: Diag[]; texts: Record<string, string[]> } | undefined
154
155// The same for the target commit, when the comparison is between two commits
156// (a commit does not change, so its diagnostics are kept until the commit or
157// the files asked about do).
158let after: { key: string; diags: Diag[] } | undefined
159
160// Checks the files asked about and marks each diagnostic as new or already
161// there (`isNew`), where the base could be checked too. Never rejects for a
162// tool that cannot run: `notes` says which could not, and why.
163export const checkChange = async (
164  ports: Ports,
165  { repo, base, target, files, wanted, isProject, use, marksNew }: Ask,
166  progress: Progress,
167): Promise<{ diags: Diag[]; notes: string[] }> => {
168  const notes: string[] = []
169  // A language with every one of its checkers switched off is not asked about.
170  const asked: Files = {
171    python: (use.ruff || use.pyright ? wanted.filter(path => PYTHON.test(path)) : []).slice(0, FILE_LIMIT),
172    typescript: (use.tsc || use.eslint ? wanted.filter(path => TYPESCRIPT.test(path)) : []).slice(
173      0,
174      FILE_LIMIT,
175    ),
176    terraform: (use.terraform ? wanted.filter(path => TERRAFORM.test(path)) : []).slice(0, FILE_LIMIT),
177    other: (use.servers ? wanted.filter(isOther) : []).slice(0, FILE_LIMIT),
178  }
179  // A whole-project check wants every file, which the command-line checkers
180  // give; anything else asks the language servers first.
181  const useServers = use.servers && (target.ref !== '' || !isProject)
182  // `side` is the tree the comparison reads and the checkers run over: the
183  // working tree, or, when two commits are compared, an export of the target.
184  let side = repo
185  let checked: Diag[] = []
186
187  if (target.ref === '') {
188    checked = await checkTree(ports, repo, repo, asked, isProject, useServers, use, notes, progress)
189  } else {
190    const sideKey = `${repo}\n${target.short}\n${JSON.stringify(use)}\n${[...asked.python, ...asked.typescript, ...asked.terraform, ...asked.other].join('\n')}`
191    const exported = await exportCommit(ports.run, repo, target.ref, target.short, base.short)
192
193    if (exported.dir === '') {
194      notes.push(
195        `diagnostics are not shown: ${target.ref} could not be exported to check it (${exported.refusal})`,
196      )
197    } else if (after?.key === sideKey) {
198      side = exported.dir
199      checked = after.diags
200    } else {
201      side = exported.dir
202      checked = await checkTree(ports, repo, side, asked, false, useServers, use, notes, progress)
203      after = { key: sideKey, diags: checked }
204    }
205  }
206
207  // New or already there: the same checkers run over the base's version of
208  // each modified file that has a diagnostic, and a diagnostic the base also
209  // had, on a line with the same text, was there before the change.
210  const statusOf = new Map(files.map(one => [one.path, one.status]))
211  const troubled = [...new Set(checked.map(diag => diag.path))]
212    .filter(path => statusOf.get(path) === 'M')
213    .sort()
214  const diags = checked.map(diag =>
215    statusOf.get(diag.path) === '?' || statusOf.get(diag.path) === 'A'
216      ? { ...diag, isNew: true }
217      : diag,
218  )
219
220  if (troubled.length === 0 || !marksNew) {
221    return { diags, notes }
222  }
223
224  const textsIn = async (tree: string): Promise<Record<string, string[]>> => {
225    const texts: Record<string, string[]> = {}
226
227    await Promise.all(
228      troubled.map(async path => {
229        texts[path] = (await ports.readFile(`${tree}/${path}`)).split('\n')
230      }),
231    )
232
233    return texts
234  }
235  const key = `${repo}\n${base.short}\n${useServers}\n${JSON.stringify(use)}\n${troubled.join('\n')}`
236
237  if (before?.key !== key && base.short !== '') {
238    // The base is checked last and all at once; until it is, what is new
239    // and what was there before is not known.
240    progress.start('new or pre-existing')
241
242    const exported = await exportCommit(
243      ports.run,
244      repo,
245      base.ref,
246      base.short,
247      target.short || base.short,
248    )
249
250    if (exported.dir === '') {
251      notes.push(
252        `new or pre-existing is not marked: ${base.ref} could not be exported to check it (${exported.refusal})`,
253      )
254    } else {
255      const missed: string[] = []
256      // The base is asked the same way as the side it is compared with: a
257      // diagnostic is matched by its tool and its words, and the servers
258      // and the command-line checkers do not put them the same.
259      const baseDiags = await checkTree(
260        ports,
261        repo,
262        exported.dir,
263        {
264          python: troubled.filter(path => PYTHON.test(path)),
265          typescript: troubled.filter(path => TYPESCRIPT.test(path)),
266          terraform: troubled.filter(path => TERRAFORM.test(path)),
267          other: use.servers ? troubled.filter(isOther) : [],
268        },
269        false,
270        useServers,
271        use,
272        missed,
273      )
274      const texts = await textsIn(exported.dir)
275
276      if (missed.length > 0) {
277        notes.push(`on the base, ${missed[0] ?? ''}`)
278      }
279
280      before = { key, diags: baseDiags, texts }
281    }
282  }
283
284  return {
285    diags: before?.key === key ? labelNew(diags, before.diags, await textsIn(side), before.texts) : diags,
286    notes,
287  }
288}
289
290// The files to check, by what checks them. `other` is every other language
291// the bridge has an installed server for: nothing but that server reads it.
292type Files = { python: string[]; typescript: string[]; terraform: string[]; other: string[] }
293
294// Runs the checkers over one tree of the repo's files: the working tree
295// itself, or an export of a commit. Projects, virtualenvs and node_modules
296// are always found in the working tree (`repo`), since an export has only
297// what git tracks; `sink` takes a line for each tool that could not run.
298// `isWhole` checks every file of every project with the command-line
299// checkers; otherwise, with `useServers`, the language servers are asked
300// first: they answer for the files given, in milliseconds once warm. The
301// `other` files are asked of the servers either way.
302const checkTree = async (
303  ports: Ports,
304  repo: string,
305  tree: string,
306  { python, typescript, terraform, other }: Files,
307  isWhole: boolean,
308  useServers: boolean,
309  use: Checkers,
310  sink: string[],
311  progress?: Progress,
312): Promise<Diag[]> => {
313  const found: Diag[] = []
314  // A server speaks in the name of the checker it stands in for; what one
315  // says for a checker that is switched off is left out.
316  const isWanted = (diag: Diag): boolean =>
317    diag.tool === 'pyright'
318      ? use.pyright
319      : diag.tool === 'tsserver'
320        ? use.tsc
321        : diag.tool.startsWith('terraform')
322          ? use.terraform
323          : true
324  // `dir` is a folder of the repo, relative to it: the project a tool runs in.
325  const at = (dir: string): string => (dir === '.' ? repo : `${repo}/${dir}`)
326  const inTree = (dir: string): string => (dir === '.' ? tree : `${tree}/${dir}`)
327  const under = (dir: string, path: string): string => (dir === '.' ? path : `${dir}/${path}`)
328  const run = (argv: string[], timeoutMs = 60_000, dir = '.') =>
329    ports.run(argv, { cwd: at(dir), timeoutMs })
330  const exec = (argv: string[], timeoutMs: number, dir = '.') =>
331    ports.run(argv, { cwd: inTree(dir), timeoutMs })
332  const has = async (path: string, dir = '.'): Promise<boolean> =>
333    (await run(['test', '-e', path], 60_000, dir)).exitCode === 0
334  // The projects the given files belong to, each with its files relative to it.
335  const projectsOf = async (markers: string, paths: string[]): Promise<Map<string, string[]>> =>
336    paths.length === 0
337      ? new Map()
338      : groupByRoot((await run(['sh', '-c', NEAREST, 'sh', markers, ...paths])).stdout)
339  // In a whole-project check, every project the repo tracks counts, changed or not.
340  const addTracked = async (projects: Map<string, string[]>, patterns: string[]): Promise<void> => {
341    for (const path of await trackedFiles(ports.run, repo, patterns)) {
342      const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '.'
343
344      if (!projects.has(dir)) {
345        projects.set(dir, [])
346      }
347    }
348  }
349  const collect = (tool: string, parsed: Diag[] | undefined, stderr: string): void => {
350    if (parsed === undefined) {
351      sink.push(explain(tool, stderr))
352    } else {
353      found.push(...parsed)
354    }
355
356    progress?.done(tool, found)
357  }
358  const checks: Promise<void>[] = []
359
360  if (python.length > 0 && use.ruff) {
361    progress?.start('ruff')
362    checks.push(
363      exec(
364        ['uvx', 'ruff', 'check', '--output-format', 'json', '--exit-zero', ...python],
365        60_000,
366      ).then(ran => collect('ruff', parseRuff(ran.stdout, tree), ran.stderr)),
367    )
368  }
369
370  // Each Python project is checked from its own folder, with its own venv.
371  const pythonProjects = await projectsOf('pyrightconfig.json pyproject.toml .venv venv', python)
372
373  if (isWhole) {
374    await addTracked(pythonProjects, ['*pyproject.toml', '*pyrightconfig.json'])
375
376    if (pythonProjects.size === 0) {
377      pythonProjects.set('.', [])
378    }
379  }
380
381  // Each TypeScript project is the folder of the nearest tsconfig.json; its
382  // tools are the nearest node_modules at or above it (a workspace hoists them).
383  const typescriptProjects = await projectsOf('tsconfig.json', typescript)
384
385  if (isWhole) {
386    await addTracked(typescriptProjects, ['*tsconfig.json'])
387  }
388
389  const bins = new Map<string, string>()
390
391  for (const dir of typescriptProjects.keys()) {
392    const nearest = await run(['sh', '-c', NEAREST, 'sh', 'node_modules/.bin/tsc', under(dir, 'x')])
393    const binDir = [...groupByRoot(nearest.stdout).keys()][0] ?? '.'
394
395    bins.set(dir, `${at(binDir)}/node_modules/.bin`)
396
397    // An export has no node_modules of its own; it borrows the working
398    // tree's, so imports resolve there as they do here.
399    if (tree !== repo) {
400      await exec(
401        ['ln', '-sfn', `${at(binDir)}/node_modules`, `${inTree(binDir)}/node_modules`],
402        10_000,
403      )
404    }
405  }
406
407  // The language servers answer first. What they covered is not asked of
408  // the command-line type checkers again; what they could not cover (a
409  // server not installed, a file outside any project) still is.
410  const served = new Set<string>()
411  const asked = useServers && !isWhole ? [...python, ...typescript, ...terraform, ...other] : other
412
413  if (asked.length > 0) {
414    // Servers not yet running take their time over the first answer (the
415    // very first run fetches them), which is said while it lasts.
416    const servers = (await lspIsRunning(ports.servers))
417      ? SERVERS
418      : `${SERVERS} (starting: the first answer can take a minute)`
419
420    progress?.start(servers)
421
422    const answer = await lspDiagnostics(
423      ports.servers,
424      tree,
425      asked,
426      tree === repo ? {} : { envRoot: repo },
427    )
428
429    for (const path of answer.covered) {
430      served.add(path)
431    }
432
433    // A missing terraform-ls is not worth a note: the terraform command
434    // below checks those files, and says so itself when it cannot.
435    sink.push(...answer.notes.filter(note => !note.includes('terraform-ls')).map(explainServer))
436    found.push(...answer.diags.filter(isWanted))
437    progress?.done(servers, found)
438  }
439
440  // Terraform files no server answered for are validated by the terraform
441  // command, a folder at a time: a folder is one configuration.
442  const terraformDirs = new Set(
443    terraform
444      .filter(path => !served.has(path))
445      .map(path => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '.')),
446  )
447
448  for (const dir of terraformDirs) {
449    checks.push(
450      (async () => {
451        progress?.start(`terraform (${dir})`)
452
453        const ran = await exec(['terraform', 'validate', '-json', '-no-color'], 120_000, dir)
454        const parsed = parseTerraform(ran.stdout, dir)
455
456        sink.push(...(parsed?.notes ?? []))
457        collect(`terraform (${dir})`, parsed?.diags, ran.stderr)
458      })(),
459    )
460  }
461
462  for (const [dir, paths] of pythonProjects) {
463    const left = isWhole ? paths : paths.filter(path => !served.has(under(dir, path)))
464
465    if (!use.pyright || (!isWhole && left.length === 0)) {
466      continue
467    }
468
469    checks.push(
470      (async () => {
471        progress?.start(`pyright (${dir})`)
472
473        const [hasDotVenv, hasVenv] = await Promise.all([
474          has('.venv/bin/python', dir),
475          has('venv/bin/python', dir),
476        ])
477        const python3 = hasDotVenv
478          ? `${at(dir)}/.venv/bin/python`
479          : hasVenv
480            ? `${at(dir)}/venv/bin/python`
481            : undefined
482        const args = [
483          '--outputjson',
484          ...(python3 === undefined ? [] : ['--pythonpath', python3]),
485          ...(isWhole ? [] : left),
486        ]
487        const installed = await exec(['pyright', ...args], 300_000, dir)
488        // A pyenv shim only answers in a Python version that has pyright
489        // installed, and a project's .python-version may pin another one;
490        // uvx runs pyright whatever the folder's Python is.
491        const ran =
492          parsePyright(installed.stdout, tree) === undefined
493            ? await exec([...WITH_NODE, 'uvx', 'pyright', ...args], 300_000, dir)
494            : installed
495        collect(`pyright (${dir})`, parsePyright(ran.stdout, tree), ran.stderr)
496      })(),
497    )
498  }
499
500  for (const [dir, paths] of typescriptProjects) {
501    const bin = bins.get(dir) ?? `${at(dir)}/node_modules/.bin`
502    const needsTsc = use.tsc && (isWhole || paths.some(path => !served.has(under(dir, path))))
503
504    checks.push(
505      (async () => {
506        if (needsTsc && !(await has(`${bin}/tsc`))) {
507          // Packages can only be installed where something lists them.
508          const listed = await run(['sh', '-c', NEAREST, 'sh', 'package.json', under(dir, 'x')])
509          const packageDir = [...groupByRoot(listed.stdout).keys()][0] ?? '.'
510
511          sink.push(
512            (await has('package.json', packageDir))
513              ? `tsc skipped in ${here(dir)}: its packages are not installed. Run npm install (or pnpm, yarn, bun) there, then press r`
514              : `tsc skipped in ${here(dir)}: no package.json`,
515          )
516        } else if (needsTsc) {
517          progress?.start(`tsc (${dir})`)
518
519          // A solution-style tsconfig only lists references; the app's own
520          // config is the one that holds the source files.
521          const hasAppConfig = await has('tsconfig.app.json', dir)
522          const ran = await exec(
523            [
524              ...WITH_NODE,
525              `${bin}/tsc`,
526              ...(hasAppConfig ? ['-p', 'tsconfig.app.json'] : []),
527              '--noEmit',
528              '--pretty',
529              'false',
530            ],
531            300_000,
532            dir,
533          )
534          const parsed = parseTsc(ran.stdout).map(diag => ({
535            ...diag,
536            path: under(dir, diag.path),
537          }))
538          const isRun = !(ran.exitCode > 0 && parsed.length === 0)
539
540          // tsc speaks for the whole project, so what the server said of
541          // some of its files is dropped: one tool's word per project.
542          if (isRun) {
543            const prefix = dir === '.' ? '' : `${dir}/`
544
545            for (let at = found.length - 1; at >= 0; at -= 1) {
546              if (found[at]?.tool === 'tsserver' && (found[at]?.path ?? '').startsWith(prefix)) {
547                found.splice(at, 1)
548              }
549            }
550          }
551
552          collect(`tsc (${dir})`, isRun ? parsed : undefined, ran.stdout + ran.stderr)
553        }
554
555        if (paths.length === 0 || !use.eslint) {
556          return
557        }
558
559        // A project that does not use eslint is not missing anything.
560        if (!(await has(`${bin}/eslint`))) {
561          return
562        }
563
564        progress?.start(`eslint (${dir})`)
565
566        const ran = await exec(
567          [...WITH_NODE, `${bin}/eslint`, '-f', 'json', ...paths],
568          120_000,
569          dir,
570        )
571        collect(`eslint (${dir})`, parseEslint(ran.stdout, tree), ran.stderr)
572      })(),
573    )
574  }
575
576  await Promise.all(checks)
577
578  return found
579}
580
581// A project's folder as a person reads it.
582const here = (dir: string): string => (dir === '.' ? 'the folder under review' : dir)
583
584// Why a tool did not run, with what to do about it where the reason is one
585// of the usual ones; the tool's own last words otherwise. `tool` is the name
586// progress knows it by ("pyright (backend)").
587export const explain = (tool: string, stderr: string): string => {
588  const name = tool.split(' ')[0] ?? tool
589  const dir = /\((.*)\)$/.exec(tool)?.[1] ?? '.'
590  const said = stderr.toLowerCase()
591  const isMissing = /not found|no such file|enoent|cannot find|not installed/.test(said)
592
593  if (/timed? ?out|etimedout|sigterm|killed/.test(said)) {
594    return `${tool} was stopped: it took too long. Press r to try again; a first run can be slow while the tool is fetched`
595  }
596
597  if ((name === 'ruff' || name === 'pyright') && isMissing && /\buvx?\b/.test(said)) {
598    return `${tool} did not run: uv is not installed. Install it (brew install uv), then press r`
599  }
600
601  if (name === 'pyright' && isMissing && said.includes('node')) {
602    return `${tool} did not run: pyright needs Node, and none was found. Install Node (brew install node), then press r`
603  }
604
605  if ((name === 'tsc' || name === 'eslint') && isMissing && said.includes('node')) {
606    return `${tool} did not run: Node was not found. Install Node (brew install node, or nvm install), then press r`
607  }
608
609  if (name === 'eslint' && /eslint\.config|no eslint configuration|couldn't find a configuration/.test(said)) {
610    return `${tool} did not run: ${here(dir)} has no eslint config. Add an eslint.config.js there, or switch eslint off in /config`
611  }
612
613  if (name === 'terraform' && isMissing) {
614    return `${tool} did not run: terraform is not installed. Install it (brew install terraform), then press r`
615  }
616
617  return `${tool} did not run: ${tail(stderr) || 'it printed nothing'}. Switch it off in /config if this project does not use it`
618}
619
620// What the language servers' bridge said it could not do, with what to do
621// about it where that is known.
622export const explainServer = (note: string): string =>
623  /\buv\b.*(not found|not installed)|python3?: (command )?not found/i.test(note)
624    ? `${note}. The language servers need uv or python3 (brew install uv); the command-line checkers are used meanwhile`
625    : note
626
627// ---------------------------------------------------------------------------
628// How each tool prints what it found.
629// ---------------------------------------------------------------------------
630
631const relative = (path: string, root: string): string =>
632  path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path
633
634const json = (out: string): unknown => {
635  try {
636    return JSON.parse(out)
637  } catch {
638    return undefined
639  }
640}
641
642// "file<tab>folder" lines into each folder's files, relative to that folder.
643export const groupByRoot = (out: string): Map<string, string[]> => {
644  const groups = new Map<string, string[]>()
645
646  for (const line of out.split('\n')) {
647    const [path, root] = line.split('\t')
648
649    if (path === undefined || root === undefined || path === '') {
650      continue
651    }
652
653    const inside = root === '.' ? path : path.slice(root.length + 1)
654    groups.set(root, [...(groups.get(root) ?? []), inside])
655  }
656
657  return groups
658}
659
660type RuffItem = {
661  code?: string | null
662  message?: string
663  filename?: string
664  location?: { row?: number; column?: number }
665  end_location?: { row?: number; column?: number }
666}
667
668export const parseRuff = (out: string, root: string): Diag[] | undefined => {
669  const items = json(out)
670
671  if (!Array.isArray(items)) {
672    return undefined
673  }
674
675  return (items as RuffItem[]).map(item => ({
676    path: relative(item.filename ?? '', root),
677    line: item.location?.row ?? 1,
678    col: item.location?.column ?? 1,
679    endCol: item.end_location?.row === item.location?.row ? (item.end_location?.column ?? 0) : 0,
680    severity: item.code ? 'warning' : 'error',
681    tool: 'ruff',
682    rule: item.code ?? 'syntax',
683    message: item.message ?? '',
684  }))
685}
686
687type PyrightItem = {
688  file?: string
689  severity?: string
690  message?: string
691  rule?: string
692  range?: {
693    start?: { line?: number; character?: number }
694    end?: { line?: number; character?: number }
695  }
696}
697
698const PYRIGHT_SEVERITY: Record<string, Severity> = {
699  error: 'error',
700  warning: 'warning',
701  information: 'info',
702}
703
704export const parsePyright = (out: string, root: string): Diag[] | undefined => {
705  const report = json(out) as { generalDiagnostics?: PyrightItem[] } | undefined
706
707  if (!Array.isArray(report?.generalDiagnostics)) {
708    return undefined
709  }
710
711  return report.generalDiagnostics.map(item => ({
712    path: relative(item.file ?? '', root),
713    line: (item.range?.start?.line ?? 0) + 1,
714    col: (item.range?.start?.character ?? 0) + 1,
715    endCol:
716      item.range?.end?.line === item.range?.start?.line ? (item.range?.end?.character ?? -1) + 1 : 0,
717    severity: PYRIGHT_SEVERITY[item.severity ?? ''] ?? 'info',
718    tool: 'pyright',
719    rule: item.rule ?? '',
720    message: item.message ?? '',
721  }))
722}
723
724type TerraformItem = {
725  severity?: string
726  summary?: string
727  detail?: string
728  range?: {
729    filename?: string
730    start?: { line?: number; column?: number }
731    end?: { line?: number; column?: number }
732  }
733}
734
735// `terraform validate -json`, run in `dir` (a folder of the repo, '.' for
736// the repo itself). A diagnostic that names no file (the folder needs
737// `terraform init`, say) is a note about the run, not about a line.
738export const parseTerraform = (
739  out: string,
740  dir: string,
741): { diags: Diag[]; notes: string[] } | undefined => {
742  const report = json(out) as { diagnostics?: TerraformItem[] } | undefined
743
744  if (!Array.isArray(report?.diagnostics)) {
745    return undefined
746  }
747
748  const said = (item: TerraformItem): string =>
749    [item.summary, item.detail].filter(part => part !== undefined && part !== '').join(': ')
750  const placed = report.diagnostics.filter(item => item.range?.filename !== undefined)
751
752  return {
753    diags: placed.map(item => ({
754      path: dir === '.' ? (item.range?.filename ?? '') : `${dir}/${item.range?.filename ?? ''}`,
755      line: item.range?.start?.line ?? 1,
756      col: item.range?.start?.column ?? 1,
757      endCol:
758        item.range?.end?.line === item.range?.start?.line ? (item.range?.end?.column ?? 0) : 0,
759      severity: item.severity === 'warning' ? 'warning' : 'error',
760      tool: 'terraform',
761      rule: '',
762      message: said(item),
763    })),
764    notes: report.diagnostics
765      .filter(item => item.range?.filename === undefined)
766      .map(item =>
767        // A folder never initialised has no providers to validate against.
768        /terraform init|not installed|missing required provider/i.test(said(item))
769          ? `terraform (${dir}) is not set up here: run terraform init in ${here(dir)}, then press r`
770          : `terraform (${dir}): ${said(item).replace(/\s+/g, ' ')}`,
771      ),
772  }
773}
774
775// `tsc --pretty false`: "src/a.ts(12,5): error TS2322: message".
776export const parseTsc = (out: string): Diag[] =>
777  out.split('\n').flatMap(line => {
778    const hit = /^(.+?)\((\d+),(\d+)\): (error|warning) (TS\d+): (.*)$/.exec(line)
779
780    return hit === null
781      ? []
782      : [
783          {
784            path: hit[1] ?? '',
785            line: Number(hit[2]),
786            col: Number(hit[3]),
787            endCol: 0,
788            severity: hit[4] === 'error' ? 'error' : 'warning',
789            tool: 'tsc',
790            rule: hit[5] ?? '',
791            message: hit[6] ?? '',
792          } satisfies Diag,
793        ]
794  })
795
796type EslintFile = {
797  filePath?: string
798  messages?: {
799    line?: number
800    column?: number
801    endLine?: number
802    endColumn?: number
803    severity?: number
804    ruleId?: string | null
805    message?: string
806  }[]
807}
808
809export const parseEslint = (out: string, root: string): Diag[] | undefined => {
810  const files = json(out)
811
812  if (!Array.isArray(files)) {
813    return undefined
814  }
815
816  return (files as EslintFile[]).flatMap(file =>
817    (file.messages ?? []).map(message => ({
818      path: relative(file.filePath ?? '', root),
819      line: message.line ?? 1,
820      col: message.column ?? 1,
821      endCol: message.endLine === message.line ? (message.endColumn ?? 0) : 0,
822      severity: message.severity === 2 ? 'error' : 'warning',
823      tool: 'eslint',
824      rule: message.ruleId ?? '',
825      message: message.message ?? '',
826    })),
827  )
828}
829
830// Marks each diagnostic of the files checked on both sides as new or already
831// there. Line numbers shift as a file is edited, so one is matched to the
832// base's by tool, rule, message and the text of the line it sits on; each of
833// the base's stands for one match, so a second copy of an old problem is new.
834export const labelNew = (
835  head: readonly Diag[],
836  base: readonly Diag[],
837  headTexts: Readonly<Record<string, readonly string[]>>,
838  baseTexts: Readonly<Record<string, readonly string[]>>,
839): Diag[] => {
840  const keyOf = (diag: Diag, texts: Readonly<Record<string, readonly string[]>>): string =>
841    [
842      diag.path,
843      diag.tool,
844      diag.rule,
845      diag.message,
846      (texts[diag.path]?.[diag.line - 1] ?? '').trim(),
847    ].join('\u0001')
848  const left = new Map<string, number>()
849
850  for (const diag of base) {
851    const key = keyOf(diag, baseTexts)
852    left.set(key, (left.get(key) ?? 0) + 1)
853  }
854
855  return head.map(diag => {
856    if (headTexts[diag.path] === undefined) {
857      return diag
858    }
859
860    const key = keyOf(diag, headTexts)
861    const count = left.get(key) ?? 0
862
863    if (count > 0) {
864      left.set(key, count - 1)
865    }
866
867    return { ...diag, isNew: count === 0 }
868  })
869}
870
hooks/diags.ts 39 lines
1// Lists of diagnostics, read the ways the screens need: one file's, counted,
2// by the line they show under.
3
4import type { Diag } from '../types'
5
6export const diagsOf = (diags: readonly Diag[], path: string): Diag[] =>
7  diags
8    .filter(diag => diag.path === path)
9    .sort((a, b) => a.line - b.line || a.col - b.col)
10
11export const countLabel = (diags: readonly Diag[]): string => {
12  const errors = diags.filter(diag => diag.severity === 'error').length
13  const others = diags.length - errors
14
15  return [errors > 0 ? `${errors}✖` : '', others > 0 ? `${others}⚠` : '']
16    .filter(part => part !== '')
17    .join(' ')
18}
19
20// The file's diagnostics by the line they show under; one past the end of
21// the file shows under its last line. `diags` is the file's, sorted.
22export const diagsByLine = (
23  diags: readonly Diag[],
24  lineCount: number,
25): Map<number, { diag: Diag; index: number }[]> => {
26  const byLine = new Map<number, { diag: Diag; index: number }[]>()
27
28  diags.forEach((diag, index) => {
29    const line = Math.min(Math.max(1, diag.line), Math.max(1, lineCount))
30    byLine.set(line, [...(byLine.get(line) ?? []), { diag, index }])
31  })
32
33  return byLine
34}
35
36// Whether a diagnostic only says code is never used, at the level of a hint:
37// it fades that code and is no problem to count or list, as in an editor.
38export const isFadeOnly = (diag: Diag): boolean => diag.isUnused === true && diag.severity === 'info'
39
hooks/git.ts 1024 lines
1// Everything that knows a git command line, or how git prints things: what
2// differs and where, the history and its lanes, blame, stashes, and the
3// commands that change the repo. Callers pass the `run` they hold and get
4// the pane's own values back; the parsers are exported for their tests.
5
6import type {
7  ChangedFile,
8  Commit,
9  GraphRow,
10  LineRange,
11  LineStat,
12  Picked,
13  Scan,
14  Span,
15} from '../types'
16import type { Run } from './run'
17import { FILE_LIMIT, tail } from './run'
18
19// `git diff --name-status`: "M\tpath", a rename "R100\told\tnew".
20export const parseNameStatus = (out: string): ChangedFile[] =>
21  out
22    .split('\n')
23    .filter(line => line.includes('\t'))
24    .map(line => {
25      const parts = line.split('\t')
26
27      return { path: parts[parts.length - 1] ?? '', status: line.charAt(0) }
28    })
29
30export const parseUntracked =(out: string): ChangedFile[] =>
31  out
32    .split('\n')
33    .filter(line => line !== '')
34    .map(path => ({ path, status: '?' }))
35
36// `git diff -U0 --no-prefix`: the added side of each hunk, per file.
37export const parseChangedLines = (out: string): Record<string, LineRange[]> => {
38  const changed: Record<string, LineRange[]> = {}
39  let path = ''
40
41  for (const line of out.split('\n')) {
42    if (line.startsWith('+++ ')) {
43      path = line.slice(4).trim()
44      continue
45    }
46
47    const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line)
48    const count = hunk?.[2] === undefined ? 1 : Number(hunk[2])
49
50    if (hunk === null || path === '' || path === '/dev/null' || count === 0) {
51      continue
52    }
53
54    const from = Number(hunk[1])
55    changed[path] = [...(changed[path] ?? []), [from, from + count - 1]]
56  }
57
58  return changed
59}
60
61// One file's `git diff -U0`: the lines the base had and the working tree
62// dropped, keyed by the new file's line they come before. A hunk that only
63// removes names the line it follows, so its lines come before the next one.
64export const parseRemoved = (out: string): Record<number, string[]> => {
65  const removed: Record<number, string[]> = {}
66  let before = 0
67
68  for (const line of out.split('\n')) {
69    const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line)
70
71    if (hunk !== null) {
72      before = Number(hunk[1]) + (hunk[2] === '0' ? 1 : 0)
73    } else if (before > 0 && line.startsWith('-') && !line.startsWith('---')) {
74      removed[before] = [
75        ...(removed[before] ?? []),
76        line.slice(1).replace(/\t/g, '    ').replace(/[\u0000-\u001f\u007f]/g, ''),
77      ]
78    }
79  }
80
81  return removed
82}
83
84// The same diff, for where those lines were: the number, in the base's
85// version of the file, of the first line removed before each such line. The
86// rest of a run follow it one by one.
87export const parseRemovedAt = (out: string): Record<number, number> => {
88  const at: Record<number, number> = {}
89
90  for (const line of out.split('\n')) {
91    const hunk = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line)
92
93    // A hunk that removes nothing (`-12,0`) has no old lines to number.
94    if (hunk !== null && hunk[2] !== '0') {
95      at[Number(hunk[3]) + (hunk[4] === '0' ? 1 : 0)] ??= Number(hunk[1])
96    }
97  }
98
99  return at
100}
101
102export type BlameLine = { hash: string; author: string; time: number; summary: string }
103
104// `git blame --porcelain`: who last changed each line, in the file's order.
105// A commit's details are printed with its first line only, so they are kept
106// by hash for its later ones. A line not committed yet has an all-zero hash.
107export const parseBlame = (out: string): BlameLine[] => {
108  const known = new Map<string, BlameLine>()
109  const lines: BlameLine[] = []
110  let current: BlameLine | undefined
111
112  for (const line of out.split('\n')) {
113    const head = /^([0-9a-f]{40}) \d+ \d+/.exec(line)
114
115    if (head !== null) {
116      const hash = head[1] ?? ''
117
118      current = known.get(hash) ?? { hash, author: '', time: 0, summary: '' }
119      known.set(hash, current)
120    } else if (current === undefined) {
121      continue
122    } else if (line.startsWith('\t')) {
123      lines.push(current)
124    } else if (line.startsWith('author ')) {
125      current.author = line.slice(7)
126    } else if (line.startsWith('author-time ')) {
127      current.time = Number(line.slice(12))
128    } else if (line.startsWith('summary ')) {
129      current.summary = line.slice(8)
130    }
131  }
132
133  return lines
134}
135
136// How long ago, in the shortest form that still reads: 5m, 3h, 12d, 4mo, 2y.
137export const ageOf = (seconds: number): string => {
138  const steps: [size: number, unit: string][] = [
139    [31_536_000, 'y'],
140    [2_592_000, 'mo'],
141    [86_400, 'd'],
142    [3600, 'h'],
143    [60, 'm'],
144  ]
145  const step = steps.find(([size]) => seconds >= size)
146
147  return step === undefined ? 'now' : `${Math.floor(seconds / step[0])}${step[1]}`
148}
149
150// `git diff --numstat`: "added<tab>deleted<tab>path"; a binary file has "-".
151export const parseNumstat = (out: string): Record<string, LineStat> => {
152  const stats: Record<string, LineStat> = {}
153
154  for (const line of out.split('\n')) {
155    const [added, deleted, path] = line.split('\t')
156
157    if (path !== undefined && path !== '') {
158      stats[path] = [Number(added) || 0, Number(deleted) || 0]
159    }
160  }
161
162  return stats
163}
164
165// `wc -l` over untracked files: every line of a new file counts as added.
166export const parseLineCounts = (out: string): Record<string, LineStat> => {
167  const stats: Record<string, LineStat> = {}
168
169  for (const line of out.split('\n')) {
170    const hit = /^\s*(\d+)\s+(.+)$/.exec(line)
171
172    if (hit !== null && hit[2] !== 'total') {
173      stats[hit[2] ?? ''] = [Number(hit[1]), 0]
174    }
175  }
176
177  return stats
178}
179
180// `git log` with each commit's fields set off by \x01: hash, parents, refs,
181// subject, relative date, author.
182export const parseCommits = (out: string): Commit[] =>
183  out
184    .split('\n')
185    .filter(line => line !== '')
186    .map(line => {
187      const [hash = '', parents = '', refs = '', subject = '', when = '', author = ''] =
188        line.split('\u0001')
189
190      return {
191        hash,
192        parents: parents.split(' ').filter(parent => parent !== ''),
193        refs: refs.split(', ').filter(ref => ref !== ''),
194        subject,
195        when,
196        author,
197      }
198    })
199
200// The lane colours of VS Code's Git Graph, in its order.
201const LANE_COLORS = [
202  '#0085d9',
203  '#d9008f',
204  '#00d90a',
205  '#d98500',
206  '#a300d9',
207  '#ff0000',
208  '#00d9cc',
209  '#e138e8',
210  '#85d900',
211  '#dc5b23',
212  '#6f24d6',
213  '#ffcc00',
214]
215
216export const laneColor = (lane: number): string =>
217  LANE_COLORS[lane % LANE_COLORS.length] ?? '#0085d9'
218
219// Lays commits (newest first, children before parents) out in lanes, one row
220// each. A lane holds the hash it waits for; a commit takes the lane waiting
221// for it, closes the other lanes waiting for it (branches that started from
222// it), hands its lane to its first parent and opens or joins a lane for each
223// other parent (a merge).
224export const layoutGraph = (commits: readonly Commit[]): GraphRow[] => {
225  const lanes: (string | undefined)[] = []
226
227  return commits.map(commit => {
228    const before = [...lanes]
229    const waiting = before.indexOf(commit.hash)
230    const free = lanes.findIndex(held => held === undefined)
231    const lane = waiting !== -1 ? waiting : free !== -1 ? free : lanes.length
232    const closing = before.flatMap((held, at) => (held === commit.hash && at !== lane ? [at] : []))
233
234    for (const at of closing) {
235      lanes[at] = undefined
236    }
237
238    lanes[lane] = commit.parents[0]
239
240    const opening: number[] = []
241    const joining: number[] = []
242
243    for (const parent of commit.parents.slice(1)) {
244      const held = lanes.findIndex((one, at) => one === parent && at !== lane)
245
246      if (held !== -1) {
247        joining.push(held)
248        continue
249      }
250
251      const spare = lanes.findIndex((one, at) => one === undefined && at !== lane)
252      const at = spare !== -1 ? spare : lanes.length
253      lanes[at] = parent
254      opening.push(at)
255    }
256
257    while (lanes.length > 0 && lanes[lanes.length - 1] === undefined) {
258      lanes.pop()
259    }
260
261    const width = Math.max(before.length, lanes.length, lane + 1)
262    const reached = [...closing, ...opening, ...joining]
263    const cells: Span[] = []
264
265    const push = (color: string, text: string): void => {
266      const last = cells[cells.length - 1]
267
268      if (last !== undefined && last[0] === color) {
269        last[1] += text
270      } else {
271        cells.push([color, text])
272      }
273    }
274
275    for (let at = 0; at < width; at += 1) {
276      // A connector runs along the row from the commit's lane to each lane it reaches.
277      const crossing = reached.find(to => at > Math.min(lane, to) && at < Math.max(lane, to))
278      const filling = reached.find(to => at >= Math.min(lane, to) && at < Math.max(lane, to))
279      const glyph =
280        at === lane
281          ? '●'
282          : closing.includes(at)
283            ? at > lane
284              ? '╯'
285              : '╰'
286            : opening.includes(at)
287              ? at > lane
288                ? '╮'
289                : '╭'
290              : joining.includes(at)
291                ? at > lane
292                  ? '┤'
293                  : '├'
294                : before[at] !== undefined
295                  ? '│'
296                  : crossing !== undefined
297                    ? '─'
298                    : ' '
299
300      push(
301        glyph === ' ' ? '' : glyph === '─' && crossing !== undefined ? laneColor(crossing) : laneColor(at),
302        glyph,
303      )
304      push(filling === undefined ? '' : laneColor(filling), filling === undefined ? ' ' : '─')
305    }
306
307    // The lanes still open under this commit, drawn on a row of their own so
308    // each dot is joined to the next one down its lane.
309    const below: Span[] = []
310
311    lanes.forEach((held, at) => {
312      const color = held === undefined ? '' : laneColor(at)
313      const last = below[below.length - 1]
314
315      if (last !== undefined && last[0] === color) {
316        last[1] += held === undefined ? '  ' : '│ '
317      } else {
318        below.push([color, held === undefined ? '  ' : '│ '])
319      }
320    })
321
322    return { ...commit, cells, below, width: width * 2, lane }
323  })
324}
325
326export const sumStats = (stats: readonly LineStat[]): LineStat =>
327  stats.reduce<LineStat>((sum, one) => [sum[0] + one[0], sum[1] + one[1]], [0, 0])
328
329// ---------------------------------------------------------------------------
330// The commands. Each takes the `run` its caller holds and the folder under
331// review, and answers in the pane's own terms; none rejects.
332// ---------------------------------------------------------------------------
333
334// The most commits the graph reads. Only the rows in view are drawn, so the
335// limit is on what git prints and the module holds, not on the pane.
336export const GRAPH_COMMITS = 5000
337
338// The row that stands for what is not committed yet: a commit of the graph's
339// own making whose parent is the commit checked out, so it is laid out in a
340// lane that runs down to that commit like any other child of it.
341export const UNCOMMITTED = '*'
342const UNCOMMITTED_COLOR = '#8b949e'
343
344export type Stash = Scan['stashes'][number]
345
346// `git worktree list --porcelain`: a block per worktree, its folder first,
347// then its commit and the branch it has checked out (none when detached).
348export const parseWorktrees = (out: string): { path: string; branch: string; head: string }[] =>
349  out
350    .split(/\n\s*\n/)
351    .map(block => ({
352      path: /^worktree (.+)$/m.exec(block)?.[1] ?? '',
353      branch: /^branch refs\/heads\/(.+)$/m.exec(block)?.[1] ?? '',
354      head: /^HEAD ([0-9a-f]+)$/m.exec(block)?.[1] ?? '',
355    }))
356    .filter(one => one.path !== '')
357
358// Exports a commit ($1, its short hash $2) of the folder it runs in to a
359// temporary folder and prints that folder's real path. A repo folder keeps
360// this export and the one named by $3 (the comparison's other side, when it
361// is a commit too); older ones are removed. Nothing in the repo or its .git
362// changes, which a `git worktree` would.
363const EXPORT_BASE = [
364  'root="${TMPDIR:-/tmp}/lens-base"',
365  'name=$(basename "$PWD")',
366  'dir="$root/$name-$2"',
367  'if [ ! -d "$dir" ]; then',
368  '  mkdir -p "$root" || exit 1',
369  // Only what is inside the folder: `find` would otherwise offer the folder
370  // itself, whose name a repo's can match (a repo called "lens", "lens-base").
371  '  find "$root" -mindepth 1 -maxdepth 1 -name "$name-*" ! -name "$name-$2" ! -name "$name-${3:-$2}" -exec rm -rf {} +',
372  '  mkdir "$dir.partial" && git archive "$1" | tar -x -C "$dir.partial" && mv "$dir.partial" "$dir" || exit 1',
373  'fi',
374  'cd "$dir" && pwd -P',
375].join('\n')
376
377const lines = (out: string): string[] => out.split('\n').filter(line => line !== '')
378
379// The real path of the folder a person named (`~` and all), when it is inside
380// a git repository; '' when it is not. A shell resolves it, and the folder
381// rides as an argument.
382export const findRepo = async (run: Run, folder: string): Promise<string> => {
383  const resolved = await run([
384    'sh',
385    '-c',
386    'case "$1" in "~"*) set -- "$HOME${1#\\~}";; esac; cd "$1" && git rev-parse --git-dir >/dev/null && pwd -P',
387    'sh',
388    folder,
389  ])
390
391  return resolved.exitCode !== 0 ? '' : resolved.stdout.trim()
392}
393
394// The real path of a folder a person named (`~` and all), whether or not git
395// knows it; '' when there is no such folder.
396export const findFolder = async (run: Run, folder: string): Promise<string> => {
397  const resolved = await run([
398    'sh',
399    '-c',
400    'case "$1" in "~"*) set -- "$HOME${1#\\~}";; esac; cd "$1" && pwd -P',
401    'sh',
402    folder,
403  ])
404
405  return resolved.exitCode !== 0 ? '' : resolved.stdout.trim()
406}
407
408// The most files listed of a folder git does not know.
409export const PLAIN_FILES = 5000
410
411// The folders left out of such a list: what tools make, never read by hand.
412const MADE_FOLDERS = [
413  '.git',
414  'node_modules',
415  '.venv',
416  'venv',
417  '__pycache__',
418  '.terraform',
419  '.mypy_cache',
420  '.ruff_cache',
421  '.pytest_cache',
422  '.tox',
423  '.next',
424  '.cache',
425]
426
427const FIND_FILES = `find . \\( ${MADE_FOLDERS.map(name => `-name ${name}`).join(' -o ')} \\) -prune -o -type f ! -name .DS_Store -print`
428
429// Whether git's answer says the folder is in no repository, which is not the
430// same as git failing there.
431const isOutside = (ran: { exitCode: number; stderr: string }): boolean =>
432  ran.exitCode !== 0 && /not a git repository/i.test(ran.stderr)
433
434// The files of a folder git does not know, sorted, the folders tools make
435// left out; the first `PLAIN_FILES` of a larger folder.
436export const folderFiles = async (run: Run, folder: string): Promise<string[]> =>
437  lines(
438    (
439      await run(
440        ['sh', '-c', `${FIND_FILES} 2>/dev/null | head -n ${PLAIN_FILES} | sed 's|^\\./||' | sort`],
441        { cwd: folder, timeoutMs: 60_000 },
442      )
443    ).stdout,
444  )
445
446// The history as the graph draws it: the uncommitted row first (where there
447// is anything uncommitted: `hasPending`), then the commits, laid out in lanes. The uncommitted row's lane is drawn grey down
448// to the commit checked out, where the branch's own colour takes over: its
449// cell is the first of each row until then.
450export const layoutHistory = (
451  commits: readonly Commit[],
452  checkedOut: string,
453  hasPending = true,
454): GraphRow[] => {
455  if (!hasPending) {
456    return layoutGraph([...commits])
457  }
458
459  const laidOut = layoutGraph([
460    {
461      hash: UNCOMMITTED,
462      parents: checkedOut === '' ? [] : [checkedOut],
463      refs: [],
464      subject: '',
465      when: '',
466      author: '',
467    },
468    ...commits,
469  ])
470  const headAt = laidOut.findIndex(row => row.hash === checkedOut)
471  const pendingColor = laneColor(laidOut[0]?.lane ?? 0)
472  const grey = (cells: Span[]): Span[] =>
473    cells.map((cell, at): Span =>
474      at === 0 && cell[0] === pendingColor ? [UNCOMMITTED_COLOR, cell[1]] : cell,
475    )
476
477  return laidOut.map((row, at) =>
478    at < headAt || (headAt === -1 && at === 0)
479      ? { ...row, cells: grey(row.cells), below: grey(row.below) }
480      : row,
481  )
482}
483
484// What git alone can say of a comparison: the files that differ and where,
485// their line counts, what is checked out, what is not committed, the stashes
486// and the whole history. `refusal` is git's reason when the comparison itself
487// could not be read, and absent when it was.
488export type Changes = {
489  files: ChangedFile[]
490  changed: Record<string, LineRange[]>
491  stats: Record<string, LineStat>
492  branches: string[]
493  head: string
494  headHash: string
495  dirty: string[]
496  stashes: Stash[]
497  worktrees: Scan['worktrees']
498  history: GraphRow[]
499  // Whether the folder is in no git repository: nothing is compared then,
500  // and its files are listed as they stand.
501  isPlain: boolean
502  refusal?: string
503}
504
505// Reads the comparison of `base` with the working tree, or, when `target`
506// names a commit, of the two commits with each other: git then diffs the
507// pair, and nothing of the working tree (its untracked files, its edits)
508// counts.
509export const readChanges = async (
510  run: Run,
511  repo: string,
512  base: string,
513  target: string,
514): Promise<Changes> => {
515  const sides = target === '' ? [base] : [base, target]
516  const git = (argv: string[]) => run(['git', ...argv], { cwd: repo, timeoutMs: 60_000 })
517
518  if (isOutside(await git(['rev-parse', '--git-dir']))) {
519    return {
520      files: [],
521      changed: {},
522      stats: {},
523      branches: [],
524      head: '',
525      headHash: '',
526      dirty: [],
527      stashes: [],
528      worktrees: [],
529      history: [],
530      isPlain: true,
531    }
532  }
533
534  const [named, untracked, hunks, numstat, log, branches, head, headHash, dirty, stashes, trees, top, prefix] =
535    await Promise.all([
536      git(['diff', '--name-status', '--relative', ...sides]),
537      git(['ls-files', '--others', '--exclude-standard']),
538      git(['diff', '-U0', '--no-prefix', '--relative', ...sides]),
539      git(['diff', '--numstat', '--no-renames', '--relative', ...sides]),
540      // Children before parents, which the lane layout relies on.
541      git([
542        'log',
543        '--branches',
544        'HEAD',
545        '--topo-order',
546        '-n',
547        String(GRAPH_COMMITS),
548        '--pretty=format:%h%x01%p%x01%D%x01%s%x01%ar%x01%an',
549      ]),
550      git(['branch', '--format=%(refname:short)']),
551      // The branch checked out, or "HEAD" when detached; and its commit.
552      git(['rev-parse', '--abbrev-ref', 'HEAD']),
553      git(['rev-parse', '--short', 'HEAD']),
554      // What is edited but not committed, whatever the base is.
555      git(['diff', '--name-only', '--relative', 'HEAD']),
556      // Each stash with its parents (the first is the commit it was made on)
557      // and how long ago.
558      git(['stash', 'list', '--format=%gd%x01%gs%x01%p%x01%ar']),
559      // The repo's worktrees, and where the folder under review sits in its own.
560      git(['worktree', 'list', '--porcelain']),
561      git(['rev-parse', '--show-toplevel']),
562      git(['rev-parse', '--show-prefix']),
563    ])
564  // Each worktree is reviewed at the same folder of it as this one is.
565  const inside = prefix.stdout.trim().replace(/\/$/, '')
566  const worktrees = parseWorktrees(trees.stdout).map(one => ({
567    path: inside === '' ? one.path : `${one.path}/${inside}`,
568    branch: one.branch,
569    head: one.head,
570    isCurrent: one.path === top.stdout.trim(),
571  }))
572  // A worktree kept inside the repo is a checkout of its own, not new files
573  // of this one: git lists its folder as untracked, and it is left out.
574  const nested = parseWorktrees(trees.stdout)
575    .map(one => one.path)
576    .filter(path => path !== top.stdout.trim())
577  const newFiles = parseUntracked(target === '' ? untracked.stdout : '').filter(one => {
578    const whole = `${repo}/${one.path}`.replace(/\/$/, '')
579
580    return !nested.some(path => whole === path || whole.startsWith(`${path}/`))
581  })
582  // git counts lines only for files it tracks; a new file's are all added.
583  const counted =
584    newFiles.length === 0
585      ? { stdout: '' }
586      : await run(
587          [
588            'sh',
589            '-c',
590            'wc -l -- "$@" 2>/dev/null',
591            'sh',
592            ...newFiles.map(one => one.path).slice(0, FILE_LIMIT),
593          ],
594          { cwd: repo, timeoutMs: 60_000 },
595        )
596
597  return {
598    files: [...parseNameStatus(named.stdout), ...newFiles],
599    changed: parseChangedLines(hunks.stdout),
600    stats: { ...parseLineCounts(counted.stdout), ...parseNumstat(numstat.stdout) },
601    branches: branches.stdout.split('\n').filter(name => name !== '' && !name.startsWith('(')),
602    head: head.stdout.trim(),
603    headHash: headHash.stdout.trim(),
604    dirty: target === '' ? lines(dirty.stdout) : [],
605    stashes: lines(stashes.stdout).map(line => {
606      const [ref = '', subject = '', parents = '', when = ''] = line.split('\u0001')
607
608      return { ref, subject, base: parents.split(' ')[0] ?? '', when }
609    }),
610    worktrees,
611    history: layoutHistory(
612      parseCommits(log.stdout),
613      headHash.stdout.trim(),
614      // A working tree with nothing edited and nothing new has no row of its own.
615      lines(dirty.stdout).length > 0 ||
616        parseUntracked(untracked.stdout).some(one => {
617          const whole = `${repo}/${one.path}`.replace(/\/$/, '')
618
619          return !nested.some(path => whole === path || whole.startsWith(`${path}/`))
620        }),
621    ),
622    isPlain: false,
623    ...(named.exitCode !== 0 ? { refusal: tail(named.stderr) } : {}),
624  }
625}
626
627// Prints a commit holding a worktree's files as they stand: what it has
628// checked out, with its uncommitted edits and its untracked files. The
629// commit is built through an index of its own and belongs to no branch, so
630// nothing of the worktree changes: not its files, its index or its HEAD.
631// Worktrees kept inside it are left out, being checkouts of their own.
632const SNAPSHOT = [
633  'top=$(git rev-parse --show-toplevel) && cd "$top" || exit 1',
634  'head=$(git rev-parse HEAD) || exit 1',
635  'index=$(mktemp) || exit 1',
636  'git worktree list --porcelain | sed -n "s/^worktree //p" > "$index.trees"',
637  'set -- .',
638  'while IFS= read -r tree; do',
639  '  case "$tree" in "$top"/*) set -- "$@" ":(exclude)${tree#"$top"/}";; esac',
640  'done < "$index.trees"',
641  'rm -f "$index" "$index.trees"',
642  'export GIT_INDEX_FILE="$index"',
643  'git read-tree HEAD && git add -A -- "$@" && tree=$(git write-tree)',
644  'status=$?',
645  'rm -f "$index"',
646  'unset GIT_INDEX_FILE',
647  '[ "$status" -eq 0 ] || exit 1',
648  'git -c user.name=lens -c user.email=lens@localhost commit-tree "$tree" -p "$head" -m "lens: a worktree as it stands"',
649].join('\n')
650
651// A commit of a worktree's files as they stand (see SNAPSHOT), by its hash;
652// '' with git's reason where it could not be made.
653export const snapshotWorktree = async (
654  run: Run,
655  path: string,
656): Promise<{ hash: string; refusal: string }> => {
657  const made = await run(['sh', '-c', SNAPSHOT], { cwd: path, timeoutMs: 120_000 })
658  const hash = made.stdout.trim()
659
660  return made.exitCode === 0 && /^[0-9a-f]{40,}$/.test(hash)
661    ? { hash, refusal: '' }
662    : { hash: '', refusal: tail(made.stderr) || 'git made no snapshot' }
663}
664
665// The repo a folder's worktree belongs to, by the path of its main
666// checkout; the folder's own repo root when it is that one. '' outside a repo.
667export const mainRepoOf = async (run: Run, repo: string): Promise<string> => {
668  const asked = await run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], {
669    cwd: repo,
670    timeoutMs: 20_000,
671  })
672
673  return asked.exitCode === 0 ? asked.stdout.trim().replace(/\/\.git\/?$/, '') : ''
674}
675
676// What the branch checked out has changed since it forked from the branch
677// its request targets: the commit it forked at ('' when git cannot say),
678// the files, and their line counts.
679export const requestChanges = async (
680  run: Run,
681  repo: string,
682  baseRef: string,
683): Promise<{ base: string; files: ChangedFile[]; stats: Record<string, LineStat> }> => {
684  const git = (argv: string[]) => run(['git', ...argv], { cwd: repo, timeoutMs: 60_000 })
685  // The remote's copy of the target is the truer one; a local branch may lag.
686  const remote = await git(['merge-base', 'HEAD', `origin/${baseRef}`])
687  const forked = remote.exitCode === 0 ? remote : await git(['merge-base', 'HEAD', baseRef])
688  const base = forked.exitCode === 0 ? forked.stdout.trim() : ''
689
690  if (base === '') {
691    return { base, files: [], stats: {} }
692  }
693
694  const [named, numstat] = await Promise.all([
695    git(['diff', '--name-status', '--relative', base, 'HEAD']),
696    git(['diff', '--numstat', '--no-renames', '--relative', base, 'HEAD']),
697  ])
698
699  return { base, files: parseNameStatus(named.stdout), stats: parseNumstat(numstat.stdout) }
700}
701
702// A short mark of how the repo stands: what is checked out, what is edited,
703// staged or new, the stashes and the worktrees. It changes when any of them
704// does, whoever made the change; '' where git does not answer. A folder git
705// does not know is marked by its files: their names, sizes and times.
706export const repoMark = async (run: Run, repo: string): Promise<string> => {
707  const asked = await run(
708    [
709      'sh',
710      '-c',
711      `if git rev-parse --git-dir >/dev/null 2>&1; then { git rev-parse HEAD; git symbolic-ref -q HEAD; git status --porcelain; git diff --numstat HEAD; git stash list; git worktree list; } 2>/dev/null; else ${FIND_FILES} 2>/dev/null | head -n ${PLAIN_FILES} | tr '\\n' '\\0' | xargs -0 ls -ln 2>/dev/null; fi | cksum`,
712    ],
713    { cwd: repo, timeoutMs: 15_000 },
714  )
715
716  return asked.exitCode === 0 ? asked.stdout.trim() : ''
717}
718
719// The files git tracks in the repo, or only those matching the patterns.
720export const trackedFiles = async (
721  run: Run,
722  repo: string,
723  patterns: readonly string[] = [],
724): Promise<string[]> =>
725  lines(
726    (
727      await run(['git', 'ls-files', ...(patterns.length === 0 ? [] : ['--', ...patterns])], {
728        cwd: repo,
729        timeoutMs: 60_000,
730      })
731    ).stdout,
732  )
733
734// A ref's commit by its short hash, and in full; '' for a ref git does not know.
735export const shortHash = async (run: Run, repo: string, ref: string): Promise<string> =>
736  (await run(['git', 'rev-parse', '--short', ref], { cwd: repo, timeoutMs: 60_000 })).stdout.trim()
737
738export const fullHash = async (run: Run, repo: string, ref: string): Promise<string> =>
739  (await run(['git', 'rev-parse', ref], { cwd: repo, timeoutMs: 60_000 })).stdout.trim()
740
741// Whether a name is a branch, tag or commit here.
742export const isCommit = async (run: Run, repo: string, name: string): Promise<boolean> =>
743  (await run(['git', 'rev-parse', '--verify', '--quiet', `${name}^{commit}`], { cwd: repo }))
744    .exitCode === 0
745
746// A commit's files as a folder of their own, outside the repo: `dir` is its
747// real path, or '' with the reason in `refusal`. `short` names the folder;
748// the export of `keep` (the comparison's other side) is left in place, older
749// ones are removed.
750export const exportCommit = async (
751  run: Run,
752  repo: string,
753  ref: string,
754  short: string,
755  keep: string,
756): Promise<{ dir: string; refusal: string }> => {
757  const exported = await run(['sh', '-c', EXPORT_BASE, 'sh', ref, short, keep], {
758    cwd: repo,
759    timeoutMs: 120_000,
760  })
761  const dir = exported.stdout.trim()
762
763  return exported.exitCode !== 0 || dir === ''
764    ? { dir: '', refusal: tail(exported.stderr) || 'no export' }
765    : { dir, refusal: '' }
766}
767
768// A file as a commit left it; empty when the commit deleted it. A stash's
769// untracked files live in its third parent, so that is tried next.
770export const fileAt = async (
771  run: Run,
772  repo: string,
773  path: string,
774  commit: string,
775): Promise<string> => {
776  const shownAt = async (at: string): Promise<string | undefined> => {
777    const shown = await run(['git', 'show', `${at}:./${path}`], { cwd: repo })
778
779    return shown.exitCode === 0 ? shown.stdout : undefined
780  }
781
782  return (
783    (await shownAt(commit)) ??
784    (commit.startsWith('stash@') ? await shownAt(`${commit}^3`) : undefined) ??
785    ''
786  )
787}
788
789// What the diff view interleaves for one file: the lines the other side had
790// (`removed`), and, for a file read at a commit, the lines that commit's side
791// changed (the working tree's come with `readChanges`).
792//
793// The working tree's file (`commit` '') and a file read at the comparison's
794// own `target` are diffed against the base; at any other commit, against its
795// parent.
796export const fileDiff = async (
797  run: Run,
798  repo: string,
799  path: string,
800  commit: string,
801  base: string,
802  target: string,
803  // Whether the working tree's file wants its changed lines from this diff
804  // too: its base is then not the one the scan compared with.
805  isOwn = false,
806): Promise<{
807  removed: Record<number, string[]>
808  removedAt: Record<number, number>
809  changed: LineRange[] | undefined
810}> => {
811  const diff = await run(
812    commit === ''
813      ? ['git', 'diff', '-U0', '--no-prefix', '--relative', base, '--', path]
814      : commit === target
815        ? ['git', 'diff', '-U0', '--no-prefix', '--relative', base, commit, '--', path]
816        : [
817            'git',
818            'show',
819            '--format=',
820            '-U0',
821            '--no-prefix',
822            '--relative',
823            '--diff-merges=first-parent',
824            commit,
825            '--',
826            path,
827          ],
828    { cwd: repo },
829  )
830
831  return {
832    removed: parseRemoved(diff.stdout),
833    removedAt: parseRemovedAt(diff.stdout),
834    changed:
835      commit === '' && !isOwn ? undefined : (parseChangedLines(diff.stdout)[path] ?? []),
836  }
837}
838
839// What a commit or a stash (`stash@{0}`) holds: its message and the files it
840// changed, with their line counts.
841export const commitDetails = async (run: Run, repo: string, hash: string): Promise<Picked> => {
842  // A stash keeps its untracked files in a commit of their own, which only
843  // `git stash show` knows to include.
844  const show = (format: string) =>
845    run(
846      hash.startsWith('stash@')
847        ? ['git', 'stash', 'show', '--include-untracked', '--no-renames', '--relative', format, hash]
848        : [
849            'git',
850            'show',
851            '--format=',
852            '--no-renames',
853            '--relative',
854            '--diff-merges=first-parent',
855            format,
856            hash,
857          ],
858      { cwd: repo },
859    )
860  // The graph's row has room for the subject alone; the rest of the message
861  // is read here and shown when the commit is opened.
862  const [named, counted, message] = await Promise.all([
863    show('--name-status'),
864    show('--numstat'),
865    run(['git', 'log', '-1', '--format=%s%n%b', hash], { cwd: repo }),
866  ])
867  const [subject = '', ...rest] = message.stdout.split('\n')
868
869  return {
870    hash,
871    files: parseNameStatus(named.stdout),
872    stats: parseNumstat(counted.stdout),
873    subject: subject.trim(),
874    body: rest.join('\n').trim(),
875  }
876}
877
878// Who last changed a line: the commit's short hash ('' for a line not
879// committed yet), its author, how long ago, and its subject.
880export type Blamed = { hash: string; author: string; age: string; summary: string }
881
882// Who last changed each line of a file, as a commit left it or (`commit` '')
883// as the working tree has it. A file git has never had committed has no
884// history to blame: every line of it is new, which an empty list stands for.
885// `now` is asked for the time, in milliseconds, once git has answered.
886export const blame = async (
887  run: Run,
888  repo: string,
889  path: string,
890  commit: string,
891  now: () => Promise<number>,
892): Promise<{ lines: Blamed[] } | { refusal: string }> => {
893  const ran = await run(
894    ['git', 'blame', '--porcelain', ...(commit === '' ? [] : [commit]), '--', path],
895    { cwd: repo, timeoutMs: 60_000 },
896  )
897
898  if (ran.exitCode !== 0) {
899    return /no such path/i.test(ran.stderr) ? { lines: [] } : { refusal: tail(ran.stderr) }
900  }
901
902  const seconds = (await now()) / 1000
903
904  return {
905    lines: parseBlame(ran.stdout).map(line => ({
906      hash: /^0+$/.test(line.hash) ? '' : line.hash.slice(0, 7),
907      author: line.author,
908      age: ageOf(Math.max(0, seconds - line.time)),
909      summary: line.summary,
910    })),
911  }
912}
913
914// The remote branches that already hold the commit checked out: none when it
915// has not been pushed.
916export const remotesWithHead = async (run: Run, repo: string): Promise<string[]> =>
917  (await run(['git', 'branch', '-r', '--contains', 'HEAD'], { cwd: repo })).stdout
918    .split('\n')
919    .map(line => line.trim())
920    .filter(line => line !== '')
921
922// The commands that change the repo answer '' when git did it, and otherwise
923// why not, in words fit to show: git's own last ones.
924const act = async (run: Run, repo: string, argv: string[]): Promise<string> => {
925  const ran = await run(['git', ...argv], { cwd: repo, timeoutMs: 120_000 })
926
927  return ran.exitCode !== 0
928    ? `git ${argv[0] ?? ''} did not go through: ${tail(ran.stderr || ran.stdout)}`
929    : ''
930}
931
932// Commits the given files and nothing else: each is added first, so a new or
933// deleted file is taken too, and the commit names them, so anything staged
934// beside them stays staged and uncommitted.
935export const commit = async (
936  run: Run,
937  repo: string,
938  paths: readonly string[],
939  message: string,
940  body: string,
941): Promise<string> => {
942  const added = await run(['git', 'add', '--', ...paths], { cwd: repo })
943
944  if (added.exitCode !== 0) {
945    return `git add did not go through: ${tail(added.stderr)}`
946  }
947
948  // A second -m is the commit's body, set off from the subject by a blank line.
949  return act(run, repo, [
950    'commit',
951    '-m',
952    message.trim(),
953    ...(body.trim() === '' ? [] : ['-m', body.trim()]),
954    '--',
955    ...paths,
956  ])
957}
958
959// Stashes the given files, the untracked ones among them included.
960export const stash = (
961  run: Run,
962  repo: string,
963  paths: readonly string[],
964  label: string,
965): Promise<string> =>
966  act(run, repo, ['stash', 'push', '--include-untracked', '-m', label, '--', ...paths])
967
968// Brings a stash back, keeping it (apply) or removing it (pop).
969export const restoreStash = (run: Run, repo: string, ref: string, isPop: boolean): Promise<string> =>
970  act(run, repo, ['stash', isPop ? 'pop' : 'apply', ref])
971
972// Takes the last commit back and keeps what it changed, as uncommitted edits.
973export const undoLastCommit = (run: Run, repo: string): Promise<string> =>
974  act(run, repo, ['reset', '--soft', 'HEAD~1'])
975
976// Throws away the uncommitted changes in the given files, which cannot be
977// undone: `tracked` go back to the last commit, `staged` (added but never
978// committed) and `untracked` are deleted. It stops at the first step git
979// refuses.
980export const discard = async (
981  run: Run,
982  repo: string,
983  tracked: readonly string[],
984  staged: readonly string[],
985  untracked: readonly string[],
986): Promise<string> => {
987  const steps = [
988    tracked.length > 0
989      ? ['restore', '--staged', '--worktree', '--source=HEAD', '--', ...tracked]
990      : undefined,
991    staged.length > 0 ? ['rm', '-f', '--quiet', '--', ...staged] : undefined,
992    untracked.length > 0 ? ['clean', '-f', '--quiet', '--', ...untracked] : undefined,
993  ]
994  let refusal = ''
995
996  for (const argv of steps) {
997    if (argv === undefined || refusal !== '') {
998      continue
999    }
1000
1001    const ran = await run(['git', ...argv], { cwd: repo })
1002
1003    if (ran.exitCode !== 0) {
1004      refusal = `git ${argv[0] ?? ''} did not go through: ${tail(ran.stderr || ran.stdout)}`
1005    }
1006  }
1007
1008  return refusal
1009}
1010
1011// Switches the repo to a branch, or to a commit with HEAD detached. Never
1012// forced: where git refuses (local changes it would overwrite), the working
1013// tree is left as it was and the answer is git's own reason.
1014export const checkOut = async (
1015  run: Run,
1016  repo: string,
1017  target: string,
1018  isBranch: boolean,
1019): Promise<string> => {
1020  const ran = await run(['git', 'switch', ...(isBranch ? [] : ['--detach']), target], { cwd: repo })
1021
1022  return ran.exitCode !== 0 ? tail(ran.stderr) || 'git refused' : ''
1023}
1024
hooks/lists.ts 164 lines
1// What the language server answered, as the pane keeps it: lists of places
2// for the list screen (uses of a name, callers, implementations, names that
3// match), and the card of a looked-up name.
4
5import type { Comment } from './review'
6import type { Listing, ListRow, Lookup } from '../types'
7import type { LspSymbol } from './lsp'
8import type { CallNode, Place, PlaceLine, SymbolHit } from './lsp-types'
9import { ISSUES_SENT } from './prompt'
10import { groupPlaces, placesList, semanticColor } from './semantic'
11
12// The most rows the list screen draws, and so the most a list holds.
13export const LIST_ROWS = 300
14
15// The colour a kind of name has in the code, for a list of names: an outline
16// or a search names kinds as a symbol's, the colours are keyed by a token's.
17const KIND_TOKEN = new Map([
18  ['constant', 'variable'],
19  ['field', 'property'],
20  ['constructor', 'method'],
21  ['module', 'namespace'],
22])
23
24export const kindColor = (kind: string): string =>
25  semanticColor(KIND_TOKEN.get(kind) ?? kind, kind === 'constant' ? ['readonly'] : [])
26
27// Where a list entry points, as a row: an indented line that reads
28// "12: the line's text" under its file's heading.
29const placeRows = (places: readonly PlaceLine[], current: string): ListRow[] =>
30  groupPlaces(places, current).files.flatMap(group => [
31    { label: `${group.path}  (${group.places.length})`, path: '', line: 0 },
32    ...group.places.map(place => ({
33      label: `  ${String(place.line).padStart(4)}: ${place.text}`,
34      path: place.path,
35      line: place.line,
36    })),
37  ])
38
39// Everywhere a name is used, the file it was asked about first; this list
40// also has a form for the prompt.
41export const usesList = (name: string, file: string, places: readonly PlaceLine[]): Listing => ({
42  title: `${places.length} uses of ${name}`,
43  rows: placeRows(places, file),
44  prompt: placesList(name, places, ISSUES_SENT),
45})
46
47// Who calls a function, or what it calls.
48export const callsList = (
49  name: string,
50  direction: 'incoming' | 'outgoing',
51  calls: readonly CallNode[],
52): Listing => ({
53  title: direction === 'incoming' ? `What calls ${name}` : `What ${name} calls`,
54  rows: calls.map(call => ({
55    label: `${call.name}  ${call.place.path.split('/').slice(-2).join('/')}:${call.place.line}  ${call.detail}`,
56    path: call.place.path,
57    line: call.place.line,
58  })),
59  prompt: '',
60})
61
62// What implements an interface, abstract method or protocol.
63export const implementationsList = (name: string, places: readonly Place[]): Listing => ({
64  title: `What implements ${name}`,
65  rows: places.map(place => ({
66    label: `${place.path}:${place.line}`,
67    path: place.path,
68    line: place.line,
69  })),
70  prompt: '',
71})
72
73// Names anywhere in the project that match what was typed, each with its
74// kind's mark and colour.
75export const namesList = (query: string, hits: readonly SymbolHit[]): Listing => ({
76  title: `Names matching "${query}"`,
77  rows: hits.map(hit => ({
78    label: hit.name,
79    mark: '›',
80    path: hit.place.path,
81    line: hit.place.line,
82    color: kindColor(hit.kind),
83    tail: `${hit.kind}${hit.container === '' ? '' : ` in ${hit.container}`} · ${hit.place.path.split('/').slice(-2).join('/')}`,
84  })),
85  prompt: '',
86})
87
88// What the server said of the name at a place in a file, as the file screen
89// shows it: its type and docs, where it is defined, and the call it sits in.
90export const lookupOf = (
91  file: string,
92  name: string,
93  line: number,
94  col: number,
95  answer: LspSymbol,
96): Lookup => ({
97  file,
98  name,
99  at: line,
100  col,
101  text: answer.text.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, ''),
102  path: answer.definition?.path ?? '',
103  line: answer.definition?.line ?? 0,
104  typePath: answer.typeDefinition?.path ?? '',
105  typeLine: answer.typeDefinition?.line ?? 0,
106  hasImplementations: (answer.implementations?.length ?? 0) > 0,
107  // The call the name sits in, with the argument being given marked.
108  signature:
109    answer.signature === undefined
110      ? ''
111      : answer.signature.parameters.length === 0
112        ? answer.signature.label
113        : `(${answer.signature.parameters.map((one, index) => (index === answer.signature?.active ? `[${one}]` : one)).join(', ')})`,
114})
115
116// A review comment in one line, for a list: where, who, and how it starts.
117const threadLine = (one: Comment, replies: number): string =>
118  `${one.path === '' ? '' : `${one.path}${one.line > 0 ? `:${one.line}` : ''}  `}${one.author}: ${one.body.trim().replace(/\s+/g, ' ').slice(0, 90)}${replies > 0 ? `  (+${replies})` : ''}`
119
120// Every thread of a pull or merge request: the open ones first, then the
121// resolved, then what was said of the request as a whole. A thread is its
122// first comment; its replies are counted. The form for the prompt is the open
123// threads in full, replies and all: what is still to be answered.
124export const threadsList = (request: string, comments: readonly Comment[]): Listing => {
125  const roots = comments.filter(one => one.replyTo === undefined)
126  const repliesTo = (root: Comment): Comment[] => comments.filter(one => one.replyTo === root.id)
127  const placed = roots.filter(one => one.path !== '')
128  const open = placed.filter(one => one.isResolved !== true)
129  const settled = placed.filter(one => one.isResolved === true)
130  const general = roots.filter(one => one.path === '')
131  const rowsOf = (threads: readonly Comment[], mark: string): ListRow[] =>
132    threads.map(one => ({
133      label: `${mark}${threadLine(one, repliesTo(one).length)}`,
134      path: one.path,
135      line: Math.max(1, one.line),
136    }))
137
138  return {
139    title: `${request === '' ? 'Review' : request}: ${open.length} open, ${settled.length} resolved`,
140    rows: [
141      ...(open.length > 0 ? [{ label: `Open (${open.length})`, path: '', line: 0 }] : []),
142      ...rowsOf(open, ''),
143      ...(settled.length > 0 ? [{ label: `Resolved (${settled.length})`, path: '', line: 0 }] : []),
144      ...rowsOf(settled, '✓ '),
145      ...(general.length > 0
146        ? [{ label: `On the request as a whole (${general.length})`, path: '', line: 0 }]
147        : []),
148      ...general.map(one => ({ label: `  ${threadLine(one, 0)}`, path: '', line: 0 })),
149    ],
150    prompt:
151      open.length === 0
152        ? ''
153        : [
154            `Open review comments${request === '' ? '' : ` in ${request}`} (${open.length}):`,
155            ...open.flatMap(one => [
156              `- ${one.path}${one.line > 0 ? `:${one.line}` : ''} ${one.author}: ${one.body.trim().replace(/\s*\n\s*/g, ' ')}`,
157              ...repliesTo(one).map(
158                reply => `  - ${reply.author}: ${reply.body.trim().replace(/\s*\n\s*/g, ' ')}`,
159              ),
160            ]),
161          ].join('\n'),
162  }
163}
164
hooks/lsp.ts 841 lines
1// Diagnostics, symbol lookups and the other things an editor asks of its
2// language server (references, callers, outline, semantic tokens, a search by
3// name, inlay hints), from long-running language servers, through
4// the bridge in lsp-bridge.ts. Nothing here touches the engine: the caller hands in `run`
5// (its `$.process.run`), and every call is one short-lived command. The first
6// call writes the bridge script to a temp folder; the script's client mode
7// starts the daemon when it is not running, and the daemon keeps one server
8// per language and project until it has been idle for half an hour.
9import type { Diag, Severity } from '../types'
10import { LSP_BRIDGE_PY } from './lsp-bridge'
11import type {
12  CallNode,
13  InlayHint,
14  OutlineItem,
15  Place,
16  PlaceLine,
17  SemanticToken,
18  Signature,
19  SymbolHit,
20} from './lsp-types'
21
22export type Run = (
23  argv: string[],
24  init?: { cwd?: string; stdin?: string; timeoutMs?: number },
25) => Promise<{ exitCode: number; stdout: string; stderr: string }>
26
27export type LspOptions = {
28  // Where a project's virtualenv and node_modules are looked for when `repo`
29  // has none: the working tree, when `repo` is an export of a commit. The
30  // project's folder is the same path under it.
31  envRoot?: string
32  // How long the servers may take to answer, in milliseconds (two minutes).
33  timeoutMs?: number
34}
35
36export type LspResult = {
37  diags: Diag[]
38  // The files a server answered for; the rest still need another checker.
39  covered: string[]
40  // Why a language's server could not be used, one line each.
41  notes: string[]
42}
43
44// A diagnostic as the Language Server Protocol spells it: 0-based positions,
45// the end exclusive.
46export type LspDiagnostic = {
47  range?: {
48    start?: { line?: number; character?: number }
49    end?: { line?: number; character?: number }
50  }
51  severity?: number
52  code?: string | number
53  message?: string
54  // 1 is DiagnosticTag.Unnecessary: code that is never used.
55  tags?: number[]
56}
57
58type BridgeAnswer = {
59  ok?: boolean
60  error?: string
61  files?: Record<string, { tool?: string; diagnostics?: LspDiagnostic[] }>
62  notes?: string[]
63}
64
65// The files the bridge has a server for whatever else is installed: Python,
66// TypeScript and Terraform. `isServed` adds what its table of servers reads.
67export const LSP_FILE = /\.(pyi?|[cm]?tsx?|tf|tfvars)$/i
68
69// One server of the bridge's table (the built-in ones, and the person's own
70// from ~/.claude/lens/servers.json), as its `served` answer lists them.
71export type ServedBy = {
72  // Also the tool its diagnostics carry.
73  name: string
74  // What a person calls the language, for a note.
75  language: string
76  // In lower case, each with its dot.
77  extensions: string[]
78  // Whole file names, `*` and `?` standing for anything.
79  filenames: string[]
80  isInstalled: boolean
81  // How to get the server; '' when the table does not say.
82  install: string
83}
84
85// The table as the bridge last listed it, in the order a file is matched.
86// The screens ask about a file as they draw, with nothing to await, so the
87// answer is kept here and a scan asks again (`lspServed`). Empty until the
88// first answer: `LSP_FILE` alone is then what is served, as it was before
89// there was a table.
90let table: { server: ServedBy; names: RegExp[] }[] = []
91
92// A whole file name with `*` and `?` in it, as the bridge reads one.
93const namePattern = (name: string): RegExp =>
94  new RegExp(
95    `^${name
96      .replace(/[.+^$()|[\]{}\\]/g, '\\$&')
97      .replace(/\*/g, '.*')
98      .replace(/\?/g, '.')}$`,
99  )
100
101// The server that reads a file, as the bridge picks it: one that is installed
102// before one that is not, a file's whole name before its extension.
103const serverOf = (path: string): ServedBy | undefined => {
104  const name = path.slice(path.lastIndexOf('/') + 1)
105  const lower = name.toLowerCase()
106
107  for (const group of [table.filter(one => one.server.isInstalled), table]) {
108    const found =
109      group.find(one => one.names.some(pattern => pattern.test(name))) ??
110      group.find(one => one.server.extensions.some(extension => lower.endsWith(extension)))
111
112    if (found !== undefined) {
113      return found.server
114    }
115  }
116
117  return undefined
118}
119
120// Whether a file that is not Python, TypeScript or Terraform is read by a
121// server of the table that is installed.
122export const isOtherServed = (path: string): boolean =>
123  !LSP_FILE.test(path) && serverOf(path)?.isInstalled === true
124
125// Whether the bridge has a server for a file.
126export const isServed = (path: string): boolean => LSP_FILE.test(path) || isOtherServed(path)
127
128// The names of the table's installed servers: the tools their diagnostics carry.
129export const servedTools = (): string[] =>
130  table.filter(one => one.server.isInstalled).map(one => one.server.name)
131
132// For the files a server of the table would read were it installed: one line
133// for each such server, saying what to install.
134export const unservedNotes = (paths: readonly string[]): string[] => {
135  const notes = new Set<string>()
136
137  for (const path of paths) {
138    const server = LSP_FILE.test(path) ? undefined : serverOf(path)
139
140    if (server !== undefined && !server.isInstalled) {
141      notes.add(
142        `${server.language} is not checked: ${server.name} is not installed${server.install === '' ? '' : ` (${server.install})`}`,
143      )
144    }
145  }
146
147  return [...notes]
148}
149
150// DiagnosticTag.Unnecessary.
151const UNNECESSARY = 1
152
153const SEVERITY: Record<number, Severity> = { 1: 'error', 2: 'warning', 3: 'info', 4: 'info' }
154
155// One protocol diagnostic of `path`, as the pane keeps them: 1-based, and
156// `endCol` only when the range ends on the line it starts on.
157export const toDiag = (path: string, tool: string, item: LspDiagnostic): Diag => {
158  const start = item.range?.start
159  const end = item.range?.end
160  const line = start?.line ?? 0
161
162  const diag: Diag = {
163    path,
164    line: line + 1,
165    col: (start?.character ?? 0) + 1,
166    endCol: end?.line === line && end.character !== undefined ? end.character + 1 : 0,
167    severity: SEVERITY[item.severity ?? 1] ?? 'info',
168    tool,
169    rule: item.code === undefined ? '' : String(item.code),
170    message: item.message ?? '',
171  }
172
173  if (Array.isArray(item.tags) && item.tags.includes(UNNECESSARY)) {
174    diag.isUnused = true
175  }
176
177  return diag
178}
179
180const byPlace = (a: Diag, b: Diag): number =>
181  a.path < b.path ? -1 : a.path > b.path ? 1 : a.line - b.line || a.col - b.col
182
183const failed = (why: string): LspResult => ({
184  diags: [],
185  covered: [],
186  notes: [`language servers did not answer: ${why}`],
187})
188
189const lastLine = (text: string): string => text.trim().split('\n').pop()?.slice(0, 200) ?? ''
190
191// What the bridge's client printed, as diagnostics. Anything but its JSON
192// answer (the command failed, or its output was cut) covers no file and says
193// why in a note, so every file falls back to the other checkers.
194export const parseBridge = (stdout: string, stderr = ''): LspResult => {
195  let answer: BridgeAnswer | undefined
196
197  try {
198    answer = JSON.parse(stdout) as BridgeAnswer
199  } catch {
200    answer = undefined
201  }
202
203  if (answer === undefined || answer === null || typeof answer !== 'object') {
204    return failed(lastLine(stderr) || lastLine(stdout) || 'no output')
205  }
206
207  if (answer.ok !== true) {
208    return failed(answer.error ?? 'no reason given')
209  }
210
211  const diags: Diag[] = []
212  const covered: string[] = []
213
214  for (const [path, file] of Object.entries(answer.files ?? {})) {
215    covered.push(path)
216
217    for (const item of file.diagnostics ?? []) {
218      diags.push(toDiag(path, file.tool ?? '', item))
219    }
220  }
221
222  return {
223    diags: diags.sort(byPlace),
224    covered: covered.sort(),
225    notes: (answer.notes ?? []).map(String),
226  }
227}
228
229// Writes the script on stdin to this user's bridge folder (the socket, lock
230// and log live beside it) and prints its path. Written under another name
231// first, so a client never reads half a script.
232const INSTALL = [
233  'd="/tmp/lens-lsp-$(id -u)"',
234  'mkdir -p -m 700 "$d" && [ -O "$d" ] || exit 1',
235  'cat > "$d/bridge.py.$$" && mv "$d/bridge.py.$$" "$d/bridge.py" && printf %s "$d/bridge.py"',
236].join('\n')
237
238// uv picks a Python whatever the folder pins; the system's is the fallback.
239const PYTHON =
240  'command -v uv >/dev/null 2>&1 && exec uv run --no-project python "$@"; exec python3 "$@"'
241
242// The script's path, per `run` it was written with: a caller that keeps one
243// `run` writes the script once per load of the module, and one that makes a
244// new `run` each time writes it each time (a few milliseconds). A script that
245// differs from the one a running daemon was started from makes the client
246// replace that daemon, so an update takes effect on the next call.
247const installed = new WeakMap<Run, Promise<string>>()
248
249const install = (run: Run): Promise<string> => {
250  const known = installed.get(run)
251
252  if (known !== undefined) {
253    return known
254  }
255
256  const writing = run(['sh', '-c', INSTALL], { stdin: LSP_BRIDGE_PY, timeoutMs: 10_000 }).then(
257    ran => {
258      const path = ran.stdout.trim()
259
260      if (ran.exitCode !== 0 || !path.endsWith('/bridge.py')) {
261        throw new Error(`could not write the bridge script: ${lastLine(ran.stderr) || 'no output'}`)
262      }
263
264      return path
265    },
266  )
267  installed.set(run, writing)
268  // A failure is not remembered: the next call tries again.
269  writing.catch(() => {
270    installed.delete(run)
271  })
272
273  return writing
274}
275
276const bridge = async (
277  run: Run,
278  mode: 'query' | 'symbol' | 'ask' | 'served' | 'stop',
279  request: object,
280  timeoutMs: number,
281): Promise<{ exitCode: number; stdout: string; stderr: string }> => {
282  const script = await install(run)
283
284  return run(['sh', '-c', PYTHON, 'sh', script, mode], {
285    cwd: script.slice(0, script.lastIndexOf('/')),
286    stdin: JSON.stringify(request),
287    timeoutMs,
288  })
289}
290
291// Diagnostics for `files` (paths relative to `repo`, an absolute real path)
292// from the language servers that cover them. Never rejects: a bridge that
293// cannot run covers nothing and says why in `notes`.
294export const lspDiagnostics = async (
295  run: Run,
296  repo: string,
297  files: readonly string[],
298  options: LspOptions = {},
299): Promise<LspResult> => {
300  const wanted = files.filter(isServed)
301
302  if (wanted.length === 0) {
303    return { diags: [], covered: [], notes: [] }
304  }
305
306  const timeoutMs = options.timeoutMs ?? 120_000
307
308  try {
309    const ran = await bridge(
310      run,
311      'query',
312      { repo, files: wanted, envRoot: options.envRoot, timeout: timeoutMs / 1000 },
313      // The client gives the daemon a little longer than the servers get.
314      Math.min(timeoutMs + 45_000, 600_000),
315    )
316
317    return parseBridge(ran.stdout, ran.stderr)
318  } catch (error) {
319    return failed(error instanceof Error ? error.message : String(error))
320  }
321}
322
323const stringsOf = (value: unknown): string[] =>
324  Array.isArray(value) ? value.filter((one): one is string => typeof one === 'string') : []
325
326// What the bridge's client printed for `served`: its table and its notes, or
327// undefined for anything but its JSON answer.
328export const parseServed = (stdout: string): { servers: ServedBy[]; notes: string[] } | undefined => {
329  let answer: { ok?: unknown; servers?: unknown; notes?: unknown } | null | undefined
330
331  try {
332    answer = JSON.parse(stdout) as typeof answer
333  } catch {
334    answer = undefined
335  }
336
337  if (answer === undefined || answer === null || answer.ok !== true || !Array.isArray(answer.servers)) {
338    return undefined
339  }
340
341  const servers: ServedBy[] = []
342
343  for (const one of answer.servers as Partial<Record<keyof ServedBy, unknown>>[]) {
344    if (one !== null && typeof one === 'object' && typeof one.name === 'string' && one.name !== '') {
345      servers.push({
346        name: one.name,
347        language: typeof one.language === 'string' && one.language !== '' ? one.language : one.name,
348        extensions: stringsOf(one.extensions).map(extension => extension.toLowerCase()),
349        filenames: stringsOf(one.filenames),
350        isInstalled: one.isInstalled === true,
351        install: typeof one.install === 'string' ? one.install : '',
352      })
353    }
354  }
355
356  return { servers, notes: stringsOf(answer.notes) }
357}
358
359// Asks the bridge for its table of servers and keeps it, for `isServed` and
360// the rest above to answer from. Resolves with what is wrong with the
361// person's config file, one line for each entry left out. Never rejects: a
362// bridge that cannot answer leaves the table as it was, and says nothing
363// (the next thing asked of it says why).
364export const lspServed = async (run: Run): Promise<string[]> => {
365  try {
366    const answer = parseServed((await bridge(run, 'served', {}, 20_000)).stdout)
367
368    if (answer === undefined) {
369      return []
370    }
371
372    table = answer.servers.map(server => ({ server, names: server.filenames.map(namePattern) }))
373
374    return answer.notes
375  } catch {
376    return []
377  }
378}
379
380// Whether the servers' keeper is already up: one that is not has to start,
381// and its servers with it, before the first answer comes.
382export const lspIsRunning = async (run: Run): Promise<boolean> =>
383  run(['sh', '-c', 'test -S "/tmp/lens-lsp-$(id -u)/bridge.sock"'], { timeoutMs: 5000 }).then(
384    ran => ran.exitCode === 0,
385    () => false,
386  )
387
388// Stops the servers of the projects at or under `root` (an export that is
389// about to be deleted), or, with no root, the daemon and every server. A
390// daemon that is not running is left that way.
391export const stopLsp = async (run: Run, root?: string): Promise<void> => {
392  try {
393    await bridge(run, 'stop', root === undefined ? {} : { root }, 40_000)
394  } catch {
395    // Nothing to stop, or nothing to stop it with.
396  }
397}
398
399// What a language server knows about the symbol at one place.
400export type LspSymbol = {
401  // Plain text: the signature or type as the server writes it, then a blank
402  // line and the docs when there are any. '' when the server has nothing.
403  text: string
404  // Where the symbol is declared, when the server can say: 1-based, and
405  // `path` relative to the repo when it is inside it, else absolute.
406  definition?: { path: string; line: number; col: number; isInRepo: boolean }
407  // The call the place is inside the arguments of, when it is in one.
408  signature?: Signature
409  // Where the symbol's type is declared, when that is not `definition`.
410  typeDefinition?: Place
411  // What implements it, for an interface, an abstract method or a protocol
412  // (at most 50). Left out when the server knows of none.
413  implementations?: Place[]
414  // Why nothing came back: no server for the language, not installed, timed
415  // out. Empty when the server answered, even with nothing (no symbol there).
416  notes: string[]
417}
418
419type SymbolAnswer = {
420  ok?: boolean
421  error?: string
422  text?: unknown
423  definition?: { path?: unknown; line?: unknown; col?: unknown; isInRepo?: unknown }
424  signature?: unknown
425  typeDefinition?: unknown
426  implementations?: unknown
427  notes?: unknown[]
428}
429
430const noSymbol = (why: string): LspSymbol => ({
431  text: '',
432  notes: [`language server did not answer: ${why}`],
433})
434
435const isPlace = (value: unknown): value is number =>
436  typeof value === 'number' && Number.isInteger(value) && value >= 1
437
438const fields = (value: unknown): Record<string, unknown> | undefined =>
439  value !== null && typeof value === 'object' && !Array.isArray(value)
440    ? (value as Record<string, unknown>)
441    : undefined
442
443const listOf = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
444
445const textOf = (value: unknown): string => (typeof value === 'string' ? value : '')
446
447// A whole place of an answer, or undefined when a part of it is missing.
448const toPlace = (value: unknown): Place | undefined => {
449  const at = fields(value)
450
451  if (
452    at === undefined ||
453    typeof at.path !== 'string' ||
454    at.path === '' ||
455    !isPlace(at.line) ||
456    !isPlace(at.col)
457  ) {
458    return undefined
459  }
460
461  return { path: at.path, line: at.line, col: at.col, isInRepo: at.isInRepo === true }
462}
463
464const toSignature = (value: unknown): Signature | undefined => {
465  const found = fields(value)
466
467  if (found === undefined || typeof found.label !== 'string') {
468    return undefined
469  }
470
471  const parameters = listOf(found.parameters).map(textOf)
472  const active = found.active
473
474  return {
475    label: found.label,
476    parameters,
477    active:
478      typeof active === 'number' && Number.isInteger(active) && active < parameters.length
479        ? Math.max(active, -1)
480        : -1,
481    docs: textOf(found.docs),
482  }
483}
484
485// What the bridge's client printed for a symbol request. Anything but its JSON
486// answer has no text and says why in one note.
487export const parseSymbol = (stdout: string, stderr = ''): LspSymbol => {
488  let answer: SymbolAnswer | undefined
489
490  try {
491    answer = JSON.parse(stdout) as SymbolAnswer
492  } catch {
493    answer = undefined
494  }
495
496  if (answer === undefined || answer === null || typeof answer !== 'object') {
497    return noSymbol(lastLine(stderr) || lastLine(stdout) || 'no output')
498  }
499
500  if (answer.ok !== true) {
501    return noSymbol(answer.error ?? 'no reason given')
502  }
503
504  const found: LspSymbol = {
505    text: typeof answer.text === 'string' ? answer.text : '',
506    notes: (answer.notes ?? []).map(String),
507  }
508  const at = answer.definition
509
510  if (
511    at !== undefined &&
512    at !== null &&
513    typeof at.path === 'string' &&
514    at.path !== '' &&
515    isPlace(at.line) &&
516    isPlace(at.col)
517  ) {
518    found.definition = { path: at.path, line: at.line, col: at.col, isInRepo: at.isInRepo === true }
519  }
520
521  const signature = toSignature(answer.signature)
522  const typeDefinition = toPlace(answer.typeDefinition)
523  const implementations: Place[] = []
524
525  for (const item of listOf(answer.implementations)) {
526    const place = toPlace(item)
527
528    if (place !== undefined) {
529      implementations.push(place)
530    }
531  }
532
533  if (signature !== undefined) {
534    found.signature = signature
535  }
536
537  if (typeDefinition !== undefined) {
538    found.typeDefinition = typeDefinition
539  }
540
541  if (implementations.length > 0) {
542    found.implementations = implementations
543  }
544
545  return found
546}
547
548// What the language server knows about the symbol at a position: 1-based line
549// and column in `file`, a path relative to `repo` (an absolute real path). The
550// column counts the line's own characters as a string index does (UTF-16 code
551// units; a tab is one). Uses the daemon and servers the diagnostics use, and
552// opens the file in its server when it is not open yet. Never rejects: any
553// failure is `text: ''` and one note. `options.timeoutMs` is how long the
554// server may take (30 seconds when not given). Inside a call's arguments the
555// answer has that call's `signature`; `typeDefinition` and `implementations`
556// are there when the server has them (pyright has no implementations).
557export const lspSymbol = async (
558  run: Run,
559  repo: string,
560  file: string,
561  line: number,
562  col: number,
563  options: LspOptions = {},
564): Promise<LspSymbol> => {
565  if (!isServed(file)) {
566    return { text: '', notes: ['no language server for this kind of file'] }
567  }
568
569  const timeoutMs = options.timeoutMs ?? 30_000
570
571  try {
572    const ran = await bridge(
573      run,
574      'symbol',
575      { repo, file, line, col, envRoot: options.envRoot, timeout: timeoutMs / 1000 },
576      Math.min(timeoutMs + 45_000, 600_000),
577    )
578
579    return parseSymbol(ran.stdout, ran.stderr)
580  } catch (error) {
581    return noSymbol(error instanceof Error ? error.message : String(error))
582  }
583}
584
585// What the bridge's client printed for one of the lookups below: its answer's
586// fields and notes. Anything but its JSON answer is no fields and one note.
587type Asked = { answer: Record<string, unknown>; notes: string[] }
588
589const unanswered = (why: string): Asked => ({
590  answer: {},
591  notes: [`language server did not answer: ${why}`],
592})
593
594const parseAsked = (stdout: string, stderr: string): Asked => {
595  let parsed: unknown
596
597  try {
598    parsed = JSON.parse(stdout)
599  } catch {
600    parsed = undefined
601  }
602
603  const answer = fields(parsed)
604
605  if (answer === undefined) {
606    return unanswered(lastLine(stderr) || lastLine(stdout) || 'no output')
607  }
608
609  if (answer.ok !== true) {
610    return unanswered(typeof answer.error === 'string' ? answer.error : 'no reason given')
611  }
612
613  return { answer, notes: listOf(answer.notes).map(String) }
614}
615
616// One lookup in the server of `file`, with the daemon and servers everything
617// else here uses. Never rejects. The server may take `options.timeoutMs` (30
618// seconds when not given).
619const ask = async (
620  run: Run,
621  what: 'references' | 'calls' | 'outline' | 'tokens' | 'symbols' | 'hints',
622  file: string,
623  request: object,
624  options: LspOptions,
625): Promise<Asked> => {
626  if (!isServed(file)) {
627    return { answer: {}, notes: ['no language server for this kind of file'] }
628  }
629
630  const timeoutMs = options.timeoutMs ?? 30_000
631
632  try {
633    const ran = await bridge(
634      run,
635      'ask',
636      { what, ...request, envRoot: options.envRoot, timeout: timeoutMs / 1000 },
637      Math.min(timeoutMs + 45_000, 600_000),
638    )
639
640    return parseAsked(ran.stdout, ran.stderr)
641  } catch (error) {
642    return unanswered(error instanceof Error ? error.message : String(error))
643  }
644}
645
646const isCount = (value: unknown): value is number =>
647  typeof value === 'number' && Number.isInteger(value) && value >= 0
648
649// Everywhere the symbol at a place is used, its declaration included, each
650// with the text of its line: the project's own files first, then installed
651// packages, each in path and line order. At most 1,000 (a note says how many
652// there were). The place is 1-based, as for `lspSymbol`. A place with no symbol
653// is no places and no note.
654export const lspReferences = async (
655  run: Run,
656  repo: string,
657  file: string,
658  line: number,
659  col: number,
660  options: LspOptions = {},
661): Promise<{ places: PlaceLine[]; notes: string[] }> => {
662  const { answer, notes } = await ask(run, 'references', file, { repo, file, line, col }, options)
663  const places: PlaceLine[] = []
664
665  for (const item of listOf(answer.places)) {
666    const place = toPlace(item)
667
668    if (place !== undefined) {
669      places.push({ ...place, text: textOf(fields(item)?.text) })
670    }
671  }
672
673  return { places, notes }
674}
675
676// Who calls the function at a place ('incoming') or what it calls
677// ('outgoing'), one level. A node's place is where that caller or callee is
678// declared (its name), not the line of the call. At most 500.
679export const lspCalls = async (
680  run: Run,
681  repo: string,
682  file: string,
683  line: number,
684  col: number,
685  direction: 'incoming' | 'outgoing',
686  options: LspOptions = {},
687): Promise<{ calls: CallNode[]; notes: string[] }> => {
688  const request = { repo, file, line, col, direction }
689  const { answer, notes } = await ask(run, 'calls', file, request, options)
690  const calls: CallNode[] = []
691
692  for (const item of listOf(answer.calls)) {
693    const node = fields(item)
694    const place = toPlace(node?.place)
695
696    if (node !== undefined && place !== undefined) {
697      calls.push({
698        name: textOf(node.name),
699        kind: textOf(node.kind),
700        place,
701        detail: textOf(node.detail),
702      })
703    }
704  }
705
706  return { calls, notes }
707}
708
709// The file's functions, classes, methods, variables and so on, in the file's
710// order, a parent before its children. `line`..`endLine` is all an entry
711// spans (a decorator above it included); `col` is its name's column when the
712// name is on `line`, else where the span starts. At most 5,000.
713export const lspOutline = async (
714  run: Run,
715  repo: string,
716  file: string,
717  options: LspOptions = {},
718): Promise<{ items: OutlineItem[]; notes: string[] }> => {
719  const { answer, notes } = await ask(run, 'outline', file, { repo, file }, options)
720  const items: OutlineItem[] = []
721
722  for (const item of listOf(answer.items)) {
723    const entry = fields(item)
724
725    if (
726      entry !== undefined &&
727      isPlace(entry.line) &&
728      isPlace(entry.endLine) &&
729      isPlace(entry.col) &&
730      isCount(entry.depth)
731    ) {
732      items.push({
733        name: textOf(entry.name),
734        kind: textOf(entry.kind),
735        line: entry.line,
736        endLine: entry.endLine,
737        col: entry.col,
738        depth: entry.depth,
739      })
740    }
741  }
742
743  return { items, notes }
744}
745
746// What every name in the file is, in the file's order. The bridge sends each
747// token as [line, col, length, type, modifier bits] against a legend, which
748// keeps a large file's answer small; at most 100,000 tokens (a note says so).
749export const lspSemanticTokens = async (
750  run: Run,
751  repo: string,
752  file: string,
753  options: LspOptions = {},
754): Promise<{ tokens: SemanticToken[]; notes: string[] }> => {
755  const { answer, notes } = await ask(run, 'tokens', file, { repo, file }, options)
756  const types = listOf(answer.types).map(textOf)
757  const names = listOf(answer.modifiers).map(textOf)
758  const tokens: SemanticToken[] = []
759
760  for (const row of listOf(answer.rows)) {
761    const [line, col, length, type, bits] = listOf(row)
762    const name = isCount(type) ? types[type] : undefined
763
764    if (isPlace(line) && isPlace(col) && isCount(length) && isCount(bits) && name) {
765      tokens.push({
766        line,
767        col,
768        length,
769        type: name,
770        modifiers: names.filter((modifier, index) => modifier !== '' && (bits & (1 << index)) !== 0),
771      })
772    }
773  }
774
775  return { tokens, notes }
776}
777
778// Symbols anywhere in the project whose name matches `query`, the closest
779// matches and the project's own files first. `near` is a file of the project
780// (relative to `repo`): it picks the server and the project. At most
781// `options.limit` hits (50 when not given, never more than 500).
782export const lspWorkspaceSymbols = async (
783  run: Run,
784  repo: string,
785  query: string,
786  near: string,
787  options: LspOptions & { limit?: number } = {},
788): Promise<{ hits: SymbolHit[]; notes: string[] }> => {
789  const request = { repo, near, query, limit: options.limit ?? 50 }
790  const { answer, notes } = await ask(run, 'symbols', near, request, options)
791  const hits: SymbolHit[] = []
792
793  for (const item of listOf(answer.hits)) {
794    const hit = fields(item)
795    const place = toPlace(hit?.place)
796
797    if (hit !== undefined && place !== undefined) {
798      hits.push({
799        name: textOf(hit.name),
800        kind: textOf(hit.kind),
801        container: textOf(hit.container),
802        place,
803      })
804    }
805  }
806
807  return { hits, notes }
808}
809
810// The inferred types and parameter names the server would draw inside lines
811// `fromLine`..`toLine` (1-based, both included), in the file's order. A label
812// carries the space it is drawn with ('amount: ' before an argument, ': int'
813// after a name). At most 5,000.
814export const lspInlayHints = async (
815  run: Run,
816  repo: string,
817  file: string,
818  fromLine: number,
819  toLine: number,
820  options: LspOptions = {},
821): Promise<{ hints: InlayHint[]; notes: string[] }> => {
822  const request = { repo, file, fromLine, toLine }
823  const { answer, notes } = await ask(run, 'hints', file, request, options)
824  const hints: InlayHint[] = []
825
826  for (const item of listOf(answer.hints)) {
827    const hint = fields(item)
828
829    if (hint !== undefined && isPlace(hint.line) && isPlace(hint.col)) {
830      hints.push({
831        line: hint.line,
832        col: hint.col,
833        label: textOf(hint.label),
834        kind: hint.kind === 'type' || hint.kind === 'parameter' ? hint.kind : 'other',
835      })
836    }
837  }
838
839  return { hints, notes }
840}
841
hooks/lsp-types.ts 61 lines
1// What the language-server bridge answers with, beyond diagnostics: the shapes
2// the bridge (lsp.ts) produces and the pane's helpers (semantic.ts) and screens
3// consume. Lines and columns are 1-based throughout; a column is a JS string
4// index + 1 on the file's own text (a tab is one character).
5
6// A position in a file. `path` is relative to the folder under review when the
7// file is inside it (`isInRepo`), else absolute.
8export type Place = { path: string; line: number; col: number; isInRepo: boolean }
9
10// A place with the text of its line, trimmed, for a list a person reads.
11export type PlaceLine = Place & { text: string }
12
13// One entry of a file's outline: a function, class, method, variable and so
14// on. `kind` is the LSP SymbolKind's name in lower case ('function', 'class',
15// 'method', 'property', 'variable', 'constant', 'interface', 'enum', ...).
16// `line`..`endLine` is everything it spans (its fold); `depth` is how deeply
17// it is nested, 0 at the top. Entries come in the file's order, a parent
18// before its children.
19export type OutlineItem = {
20  name: string
21  kind: string
22  line: number
23  endLine: number
24  col: number
25  depth: number
26}
27
28// What a name is, as the server understands it: `type` and `modifiers` are the
29// LSP semantic token names ('parameter', 'property', 'variable', 'function',
30// 'method', 'class', 'type', 'namespace', 'enumMember', 'typeParameter', ...;
31// 'readonly', 'declaration', 'defaultLibrary', 'async', ...). A token never
32// spans lines.
33export type SemanticToken = {
34  line: number
35  col: number
36  length: number
37  type: string
38  modifiers: string[]
39}
40
41// A hint the server would draw inside the code: an inferred type after a name
42// (': int'), or a parameter's name before an argument ('amount='). It sits
43// before the character at `col`.
44export type InlayHint = {
45  line: number
46  col: number
47  label: string
48  kind: 'type' | 'parameter' | 'other'
49}
50
51// One caller or callee of a function: its name and kind, where it is, and what
52// the server says of it besides (its container or signature).
53export type CallNode = { name: string; kind: string; place: Place; detail: string }
54
55// A match of a project-wide search for a name.
56export type SymbolHit = { name: string; kind: string; container: string; place: Place }
57
58// The call the cursor is inside: its whole label, each parameter's own text,
59// which one is active (0-based, -1 for none), and its docs.
60export type Signature = { label: string; parameters: string[]; active: number; docs: string }
61
hooks/prompt.ts 89 lines
1// What the pane hands the prompt, as text: a list of issues, a block of
2// code with its place, a line's diagnostics with the line.
3
4import type { Diag } from '../types'
5
6// How many issues, or places, one press sends to the prompt.
7export const ISSUES_SENT = 40
8
9// Diagnostics as one list for the prompt, a line each, the worst first.
10export const issueList = (diags: readonly Diag[], limit: number): string => {
11  const ranked = [...diags].sort(
12    (a, b) =>
13      Number(b.severity === 'error') - Number(a.severity === 'error') ||
14      a.path.localeCompare(b.path) ||
15      a.line - b.line,
16  )
17  const lines = ranked
18    .slice(0, limit)
19    .map(
20      diag =>
21        `- ${diag.path}:${diag.line}:${diag.col} ${diag.severity} ${diag.tool}${diag.rule === '' ? '' : ` ${diag.rule}`}: ${diag.message.replace(/\s+/g, ' ')}`,
22    )
23
24  return [...lines, ...(ranked.length > limit ? [`- … and ${ranked.length - limit} more`] : [])].join(
25    '\n',
26  )
27}
28
29const FENCES: [pattern: RegExp, language: string][] = [
30  [/\.pyi?$/, 'python'],
31  [/\.[cm]?tsx$/, 'tsx'],
32  [/\.[cm]?ts$/, 'ts'],
33  [/\.[cm]?jsx$/, 'jsx'],
34  [/\.[cm]?js$/, 'js'],
35]
36
37const fence = (path: string, body: string): string =>
38  `\`\`\`${FENCES.find(([pattern]) => pattern.test(path))?.[1] ?? ''}\n${body}\n\`\`\``
39
40// Lines `from` to `to` of a file as the prompt takes them: where they are,
41// then the code.
42export const codeBlock = (
43  path: string,
44  from: number,
45  to: number,
46  texts: readonly string[],
47): string =>
48  `${path}:${from === to ? from : `${from}-${to}`}\n${fence(path, texts.slice(from - 1, to).join('\n'))}`
49
50export const quoteBlock = (path: string, text: string): string =>
51  `From ${path}:\n${fence(path, text.replace(/\s+$/, ''))}`
52
53// A review thread as the prompt takes it: who said what on which line (the
54// replies under the comment they answer), then the code it is about, lines
55// `from` to `to`. `request` names the pull or merge request it is on ("PR #12",
56// "MR !34"), '' when that is not known.
57export const talkBlock = (
58  request: string,
59  path: string,
60  line: number,
61  thread: readonly { author: string; body: string; isResolved?: boolean }[],
62  from: number,
63  to: number,
64  texts: readonly string[],
65): string =>
66  [
67    `Review comment${request === '' ? '' : ` in ${request}`} on ${path}:${line}${thread.some(one => one.isResolved === true) ? ' (resolved)' : ''}:`,
68    ...thread.map(
69      (one, at) => `${at === 0 ? '-' : '  -'} ${one.author}: ${one.body.trim().replace(/\s*\n\s*/g, ' ')}`,
70    ),
71    codeBlock(path, from, to, texts),
72  ].join('\n')
73
74// A line's diagnostics as the prompt takes them: each message with its tool
75// and rule, then the line they point at.
76export const diagBlock = (
77  path: string,
78  line: number,
79  diags: readonly Diag[],
80  texts: readonly string[],
81): string =>
82  [
83    ...diags.map(
84      diag =>
85        `${path}:${line}:${diag.col} ${diag.isNew === undefined ? '' : diag.isNew ? 'new ' : 'pre-existing '}${diag.severity} ${diag.tool}${diag.rule === '' ? '' : ` ${diag.rule}`}: ${diag.message.replace(/\s+/g, ' ')}`,
86    ),
87    fence(path, texts[line - 1] ?? ''),
88  ].join('\n')
89
hooks/recents.ts 126 lines
1// What the mod keeps between sessions, and what it leaves on the machine.
2//
3// Kept: the repos reviewed lately, each with the comparison and layout it
4// was left in, so /lens picks one up where it was and has a list to offer
5// when it is run outside any repo. Left behind by a session: the exports of
6// commits the checkers ran over, the refs a pull request was fetched under,
7// and the language servers' keeper; `cleanUp` removes all three.
8
9import type { Recent, View } from '../types'
10import type { Run } from './run'
11
12// How many repos the list holds.
13export const RECENTS = 12
14
15// A review as the list keeps it.
16export const recentOf = (now: View, at: number, home = ''): Recent => ({
17  repo: now.repo,
18  // A comparison with another worktree is with a snapshot that does not last.
19  base: (now.baseWorktree ?? '') === '' ? now.base : 'HEAD',
20  target: now.target ?? '',
21  request: (now.target ?? '') === '' ? '' : (now.request ?? ''),
22  requestTyped: (now.target ?? '') === '' ? '' : (now.requestTyped ?? ''),
23  layout: now.layout ?? 'tree',
24  isBrowsing: now.isBrowsing ?? false,
25  at,
26  home,
27})
28
29// The list with a review put first, in place of what it held of that repo.
30export const remember = (list: readonly Recent[], one: Recent): Recent[] =>
31  [one, ...list.filter(other => other.repo !== one.repo)].slice(0, RECENTS)
32
33// The list as the store gave it back: whatever is not a review is dropped,
34// so a store written by another version, or by hand, cannot break a reader.
35export const settledRecents = (stored: unknown): Recent[] =>
36  (Array.isArray(stored) ? stored : []).flatMap((one: unknown): Recent[] => {
37    if (typeof one !== 'object' || one === null) {
38      return []
39    }
40
41    const held = one as Partial<Record<keyof Recent, unknown>>
42    const text = (value: unknown, fallback = ''): string =>
43      typeof value === 'string' ? value : fallback
44
45    return typeof held.repo === 'string' && held.repo.startsWith('/')
46      ? [
47          {
48            repo: held.repo,
49            base: text(held.base, 'HEAD') || 'HEAD',
50            target: text(held.target),
51            request: text(held.request),
52            requestTyped: text(held.requestTyped),
53            layout: held.layout === 'list' ? 'list' : 'tree',
54            isBrowsing: held.isBrowsing === true,
55            at: typeof held.at === 'number' ? held.at : 0,
56            home: text(held.home),
57          },
58        ]
59      : []
60  })
61
62// The list as the recents screen shows it: the worktrees of one repo
63// together, under the repo they belong to, each group where its latest
64// review sits in the list.
65export const groupRecents = (list: readonly Recent[]): { home: string; reviews: Recent[] }[] => {
66  const groups = new Map<string, Recent[]>()
67
68  for (const one of list) {
69    const home = one.home === '' ? one.repo : one.home
70
71    groups.set(home, [...(groups.get(home) ?? []), one])
72  }
73
74  return [...groups].map(([home, reviews]) => ({ home, reviews }))
75}
76
77// What a review was comparing, in a few words, for the list.
78export const comparisonLabel = (one: Recent): string =>
79  one.request !== ''
80    ? one.request
81    : one.target !== ''
82      ? `${one.target} vs ${one.base}`
83      : one.base === 'HEAD'
84        ? 'uncommitted changes'
85        : `working tree vs ${one.base}`
86
87// How long ago, in a word or two.
88export const agoOf = (at: number, now: number): string => {
89  const minutes = Math.max(0, Math.round((now - at) / 60_000))
90
91  return at === 0
92    ? ''
93    : minutes < 1
94      ? 'just now'
95      : minutes < 60
96        ? `${minutes} min ago`
97        : minutes < 60 * 24
98          ? `${Math.round(minutes / 60)} h ago`
99          : `${Math.round(minutes / (60 * 24))} d ago`
100}
101
102// Removes what sessions leave on the machine. It is started and let go of,
103// so a session's end does not wait for it: the servers' keeper is asked to
104// stop, the exports of commits are deleted, and in each repo given the refs
105// pull requests were fetched under are deleted (nothing else of a repo is
106// touched). A review picked up again exports and fetches what it needs.
107const CLEAN_UP = [
108  '(',
109  '  d="/tmp/lens-lsp-$(id -u)"',
110  '  if [ -S "$d/bridge.sock" ] && cd "$d"; then',
111  '    if command -v uv >/dev/null 2>&1; then echo "{}" | uv run --no-project python bridge.py stop',
112  '    else echo "{}" | python3 bridge.py stop; fi',
113  '  fi',
114  '  rm -rf "${TMPDIR:-/tmp}/lens-base"',
115  '  for repo in "$@"; do',
116  '    git -C "$repo" for-each-ref --format="delete %(refname)" refs/lens |',
117  '      git -C "$repo" update-ref --stdin',
118  '  done',
119  ') >/dev/null 2>&1 </dev/null &',
120].join('\n')
121
122export const cleanUp = (run: Run, repos: readonly string[]): Promise<unknown> =>
123  run(['sh', '-c', CLEAN_UP, 'sh', ...new Set(repos.filter(repo => repo.startsWith('/')))], {
124    timeoutMs: 1000,
125  })
126
hooks/ledger.ts 93 lines
1// The ledger mod's review findings as the pane's review comments, so each
2// shows on its line the way a request's thread does. Lens works without the
3// ledger: with no run there are none.
4
5import type { LedgerRunSeen } from '../types/ledger'
6import type { Comment } from './review'
7
8const PREFIX = 'ledger-'
9
10// Whether a comment is a ledger finding: it has no thread on a forge to answer
11// or resolve.
12export const isFinding = (comment: Comment): boolean => comment.id.startsWith(PREFIX)
13
14// A path with its `.` and `..` parts folded.
15const folded = (path: string): string => {
16  const parts: string[] = []
17
18  for (const part of path.split('/')) {
19    if (part === '..') {
20      parts.pop()
21    } else if (part !== '.' && part !== '') {
22      parts.push(part)
23    }
24  }
25
26  return `${path.startsWith('/') ? '/' : ''}${parts.join('/')}`
27}
28
29// A path another mod names, made absolute: as it is when it starts at the
30// root, else from `root`, the session's folder.
31export const placeOf = (path: string, root: string): string =>
32  folded(path.startsWith('/') ? path : `${root}/${path}`)
33
34// Where a finding's file is under the folder being reviewed, or undefined when
35// it is not there. An agent writes the path from the session's folder, which
36// may be the folder under review, one above it, or one inside it; failing
37// those, a changed file whose path ends with the finding's is the one meant.
38const placed = (path: string, repo: string, root: string, files: readonly string[]): string | undefined => {
39  const full = folded(path.startsWith('/') ? path : `${root}/${path}`)
40  const under = full.startsWith(`${repo}/`) ? full.slice(repo.length + 1) : undefined
41  const tail = folded(path).replace(/^\//, '')
42
43  if (under !== undefined && (path.startsWith('/') || files.includes(under))) {
44    return under
45  }
46
47  // A path written from a folder above the one under review starts with
48  // that folder's own last parts (`skills/lens/hooks/a.ts` for a review of
49  // `…/skills/lens`), whatever the session's folder is by now.
50  const parts = tail.split('/')
51
52  for (let at = parts.length - 1; at >= 1; at -= 1) {
53    if (repo.endsWith(`/${parts.slice(0, at).join('/')}`)) {
54      return parts.slice(at).join('/')
55    }
56  }
57
58  if (under !== undefined) {
59    return under
60  }
61
62
63  return files.find(one => one === tail || one.endsWith(`/${tail}`) || tail.endsWith(`/${one}`))
64}
65
66// The run's findings as comments on the files of `repo`, the folder under
67// review. `root` is the session's folder and `files` the changed files' paths.
68// A fixed finding is a resolved thread; one with no line is on the file as a
69// whole.
70export const findingComments = (
71  run: LedgerRunSeen | null | undefined,
72  repo: string,
73  root: string,
74  files: readonly string[],
75): Comment[] =>
76  (run?.findings ?? []).flatMap(one => {
77    const path = placed(one.path, repo, root, files)
78
79    return path === undefined
80      ? []
81      : [
82          {
83            id: `${PREFIX}${one.id}`,
84            path,
85            line: one.line ?? 0,
86            author: `ledger ${one.severity}${one.task === undefined ? '' : ` · ${one.task}`}`,
87            body: one.summary,
88            when: new Date(one.at).toISOString(),
89            ...(one.status === 'fixed' ? { isResolved: true } : {}),
90          },
91        ]
92  })
93
hooks/media.ts 215 lines
1// What a description or a comment links to that a terminal cannot draw in
2// place: pictures, videos and documents. They are found in the markdown and
3// listed under it, each a link that opens where it can be seen.
4
5export type Media = { kind: 'image' | 'video' | 'file'; url: string; label: string }
6
7const VIDEO = /\.(?:mp4|mov|webm|m4v|avi|mkv)(?:[?#]|$)/i
8const IMAGE = /\.(?:png|jpe?g|gif|webp|svg|bmp|avif|heic)(?:[?#]|$)/i
9const FILE = /\.(?:pdf|docx?|xlsx?|pptx?|csv|txt|log|zip|gz|tar|json|ya?ml|md|key|numbers|pages)(?:[?#]|$)/i
10// What a forge serves an upload from, whatever its name ends with.
11const UPLOAD = /\/user-attachments\/|\/uploads\/[0-9a-f]{16,}\/|\/files\/\d+\//
12
13// The last part of a link's path, as a name to show; the link itself when
14// it has none.
15const nameOf = (url: string): string => {
16  const last = (url.split(/[?#]/)[0] ?? '').split('/').filter(part => part !== '').pop() ?? ''
17
18  try {
19    return decodeURIComponent(last) || url
20  } catch {
21    return last || url
22  }
23}
24
25const kindOf = (url: string, written: Media['kind'] | undefined): Media['kind'] | undefined =>
26  VIDEO.test(url)
27    ? 'video'
28    : IMAGE.test(url)
29      ? 'image'
30      : FILE.test(url)
31        ? 'file'
32        : (written ?? (UPLOAD.test(url) ? 'file' : undefined))
33
34// The pictures, videos and documents a piece of markdown holds, in the order
35// they come, each once. A picture is one written as a picture (`![]()`, an
36// `<img>`); a video an `<video>` or a link to a video file; a document a
37// link to an upload or to a file of a kind people attach. A bare link to a
38// forge's upload counts too: that is how GitHub writes a dropped video.
39//
40// The text is whoever wrote the request's, so it is read as untrusted: only
41// its first `SCANNED` characters are looked at, every pattern's repeats are
42// bounded (none can be made to try the same stretch over and over), no more
43// than `MEDIA_KEPT` are kept, and a label is plain printable text of a
44// length a row can hold.
45export const SCANNED = 60_000
46export const MEDIA_KEPT = 100
47const LABEL = 120
48
49// Text with nothing a terminal would act on: control characters go, and
50// runs of space become one.
51export const plain = (text: string): string =>
52  text
53    .replace(new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069]', 'g'), ' ')
54    .replace(/\s+/g, ' ')
55    .trim()
56
57// Whether a character is one a terminal acts on or that reorders the text
58// round it, by its code point: the control characters, the zero-width and
59// the direction marks.
60const isActedOn = (code: number): boolean =>
61  code < 32 ||
62  (code >= 127 && code <= 159) ||
63  (code >= 0x200b && code <= 0x200f) ||
64  (code >= 0x2028 && code <= 0x202e) ||
65  (code >= 0x2066 && code <= 0x2069)
66
67// A block of text (a description, a comment) with those characters taken
68// out, its lines and its tabs kept: what is handed on to be drawn.
69export const plainBlock = (text: string): string =>
70  Array.from(text)
71    .filter(char => {
72      const code = char.codePointAt(0) ?? 0
73
74      return code === 9 || code === 10 || !isActedOn(code)
75    })
76    .join('')
77
78export const mediaOf = (markdown: string): Media[] => {
79  const text = markdown.slice(0, SCANNED)
80  const found = new Map<string, Media>()
81  const take = (url: string, written: Media['kind'] | undefined, label: string) => {
82    // A link is http or https, of printable characters with no space in it.
83    const kind = /^https?:\/\/[\x21-\x7e]{1,2000}$/.test(url) ? kindOf(url, written) : undefined
84
85    if (kind !== undefined && !found.has(url) && found.size < MEDIA_KEPT) {
86      found.set(url, { kind, url, label: (plain(label) || plain(nameOf(url))).slice(0, LABEL) })
87    }
88  }
89  // Each kind of mention is looked for with where it starts, so the list
90  // comes out in the order of the text.
91  const mentions: { at: number; url: string; written: Media['kind'] | undefined; label: string }[] = []
92  const scan = (pattern: RegExp, read: (hit: RegExpExecArray) => Omit<(typeof mentions)[number], 'at'>) => {
93    for (const hit of text.matchAll(pattern)) {
94      mentions.push({ at: hit.index, ...read(hit as RegExpExecArray) })
95    }
96  }
97
98  scan(/!\[([^\]\n]{0,300})\]\(([^\s)]{1,2000})(?: "[^"\n]{0,300}")?\)/g, hit => ({
99    url: hit[2] ?? '',
100    written: 'image',
101    label: hit[1] ?? '',
102  }))
103  scan(/<img\b([^>]{0,1000})>/gi, hit => ({
104    url: /\bsrc=["']([^"'\s]{1,2000})["']/i.exec(hit[1] ?? '')?.[1] ?? '',
105    written: 'image',
106    label: /\balt=["']([^"'\n]{0,300})["']/i.exec(hit[1] ?? '')?.[1] ?? '',
107  }))
108  scan(/<(?:video|source)\b([^>]{0,1000})>/gi, hit => ({
109    url: /\bsrc=["']([^"'\s]{1,2000})["']/i.exec(hit[1] ?? '')?.[1] ?? '',
110    written: 'video',
111    label: '',
112  }))
113  scan(/(?<!!)\[([^\]\n]{1,300})\]\(([^\s)]{1,2000})(?: "[^"\n]{0,300}")?\)/g, hit => ({
114    url: hit[2] ?? '',
115    written: undefined,
116    label: hit[1] ?? '',
117  }))
118  scan(/(?<![("'=\]])\bhttps?:\/\/[^\s<>)"']{1,2000}/g, hit => ({ url: hit[0], written: undefined, label: '' }))
119
120  for (const one of mentions.sort((a, b) => a.at - b.at)) {
121    take(one.url, one.written, one.label)
122  }
123
124  return [...found.values()]
125}
126
127// The first few lines of a description, to show what it says at a glance:
128// its text without the marks markdown is written with (a heading's `#`, a
129// list's bullet, emphasis, a link's address, a picture, a tag), each line
130// held to `width` and no more than `count` of them. Empty for a description
131// that says nothing. What it is cut from is bounded, as in `mediaOf`.
132export const sampleOf = (markdown: string, count: number, width: number): string[] => {
133  const lines: string[] = []
134  let isCode = false
135
136  for (const raw of plainBlock(markdown.slice(0, SCANNED)).split('\n')) {
137    if (/^\s*(```|~~~)/.test(raw)) {
138      isCode = !isCode
139      continue
140    }
141
142    const line = isCode
143      ? raw.trim()
144      : plain(
145          raw
146            .replace(/<!--[^>]{0,2000}-->/g, ' ')
147            .replace(/!\[[^\]\n]{0,300}\]\([^)\s]{0,2000}\)/g, ' ')
148            .replace(/\[([^\]\n]{1,300})\]\([^)\s]{0,2000}\)/g, '$1')
149            .replace(/<[^>\n]{0,1000}>/g, ' ')
150            .replace(/^\s{0,3}(?:#{1,6}\s+|[-*+]\s+(?:\[[ xX]\]\s+)?|\d{1,4}[.)]\s+|>\s?)+/, '')
151            .replace(/(\*\*|__|\*|_|`|~~)/g, ''),
152        )
153
154    // A rule, a table's dashes or a line the marks were all of is no line.
155    if (line === '' || /^[-=|:\s]+$/.test(line)) {
156      continue
157    }
158
159    lines.push(line.length > width ? `${line.slice(0, Math.max(1, width - 1))}…` : line)
160
161    if (lines.length >= count) {
162      break
163    }
164  }
165
166  return lines
167}
168
169// The site a link goes to, to say beside whatever it is called: a name is
170// the writer's to choose, where it leads is not.
171export const hostOf = (url: string): string => /^https?:\/\/([^/?#\s]{1,200})/i.exec(url)?.[1]?.toLowerCase() ?? ''
172
173// Markdown with every link that opens a page elsewhere marked as one: `mark`
174// (the sign of such a link) is put after its words, so a link reads as
175// something to press and not as coloured text. A picture written into the
176// text is no picture in a terminal, so it becomes a link to itself, marked
177// the same. Code is left as it is, fenced or between backticks, and so is a
178// picture that is itself the words of a link.
179const LINKED = new RegExp('(?<![\\[!])(!?)\\[([^\\[\\]\\n]{1,300})\\]\\((https?://[^\\s)]{1,2000})(?:\\s+"[^"\\n]{0,200}")?\\)', 'g')
180
181export const markLinks = (markdown: string, mark: string): string => {
182  let fence = ''
183
184  return markdown
185    .split('\n')
186    .map(line => {
187      const opened = /^\s{0,3}(```|~~~)/.exec(line)?.[1] ?? ''
188
189      if (fence !== '') {
190        fence = opened === fence ? '' : fence
191
192        return line
193      }
194
195      if (opened !== '') {
196        fence = opened
197
198        return line
199      }
200
201      // Every other piece of a line cut at its backticks is code.
202      return line
203        .split(/(`[^`]*`)/)
204        .map((piece, at) =>
205          at % 2 === 1
206            ? piece
207            : piece.replace(LINKED, (_whole, _bang: string, label: string, url: string) =>
208                label.endsWith(mark) ? `[${label}](${url})` : `[${label} ${mark}](${url})`,
209              ),
210        )
211        .join('')
212    })
213    .join('\n')
214}
215
hooks/pictures.ts 293 lines
1// The pictures of a request's description, drawn in place where the terminal
2// can draw one. A picture is a link in someone else's text, so which ones
3// are fetched at all is decided here, and each is fetched by a fixed command
4// with its address as an argument: only https, only from the forge's own
5// hosts, a bounded size, a bounded time. What comes back is made a PNG file
6// the terminal reads itself; anything else stays the link it was.
7
8import type { Run } from './run'
9
10// A picture ready to draw: the PNG file holding it, and its size in pixels.
11export type Picture = { file: string; width: number; height: number }
12
13// The most a picture may weigh to be fetched, and the widest and tallest one
14// that is drawn.
15export const PICTURE_BYTES = 2 * 1024 * 1024
16const PICTURE_PIXELS = 4096
17// How many of a description's pictures are drawn; the rest stay links.
18export const PICTURES_SHOWN = 6
19// How many times a picture's address may point on to another.
20const REDIRECTS = 4
21
22// The hosts a forge serves its own pictures from, beside the forge itself:
23// what people drop into a description, and a file of a repository.
24const GITHUB_HOSTS = [
25  'github.com',
26  'raw.githubusercontent.com',
27  'user-images.githubusercontent.com',
28  'private-user-images.githubusercontent.com',
29  'objects.githubusercontent.com',
30  'camo.githubusercontent.com',
31  'avatars.githubusercontent.com',
32]
33
34// Whether a picture's address is one lens fetches: https, with no name and
35// password in it, on the forge's own host or (for GitHub) one of the hosts
36// it serves pictures from. `forge` is the host of the repository's remote.
37export const isFetched = (url: string, forge: string): boolean => {
38  const parts = /^https:\/\/([^/?#@\s:]{1,200})(?::443)?(?:[/?#][\x21-\x7e]{0,2000})?$/.exec(url)
39  const host = parts?.[1]?.toLowerCase() ?? ''
40  const home = forge.toLowerCase()
41
42  return host !== '' && home !== '' && (host === home || (home === 'github.com' && GITHUB_HOSTS.includes(host)))
43}
44
45// How many cells a picture takes when it is drawn `columns` wide at most: as
46// wide as it is, where it is narrower, and as tall as keeps its shape (a
47// cell is about twice as tall as it is wide), within `rows`.
48export const cellsOf = (
49  picture: Pick<Picture, 'width' | 'height'>,
50  columns: number,
51  rows: number,
52): { columns: number; rows: number } => {
53  const wide = Math.max(1, Math.min(columns, 255, Math.round(picture.width / 8)))
54  const tall = Math.max(1, Math.round((wide * picture.height) / picture.width / 2))
55
56  return tall <= rows
57    ? { columns: wide, rows: tall }
58    : { columns: Math.max(1, Math.round((rows * 2 * picture.width) / picture.height)), rows: Math.max(1, rows) }
59}
60
61// The most pixels a picture may say it has before any tool is let open it.
62const PIXELS_OPENED = 40_000_000
63
64// A small file can say it is a picture of enormous size, and opening it
65// would take all the memory there is. So before one is made a PNG, its size
66// is read from its header alone (no pixel is opened for that), and one over
67// the bound, or whose size cannot be read, is refused. A tool that runs away
68// all the same is stopped by the bound on processor time.
69const FITS = [
70  'ulimit -t 30 2>/dev/null',
71  'fits() {',
72  '  if command -v sips >/dev/null 2>&1; then',
73  '    wide=$(sips -g pixelWidth "$1" 2>/dev/null | awk "/pixelWidth/ {print \\$2}")',
74  '    tall=$(sips -g pixelHeight "$1" 2>/dev/null | awk "/pixelHeight/ {print \\$2}")',
75  '  elif command -v magick >/dev/null 2>&1; then',
76  '    wide=$(magick identify -ping -format "%w" "$1[0]" 2>/dev/null)',
77  '    tall=$(magick identify -ping -format "%h" "$1[0]" 2>/dev/null)',
78  '  elif command -v identify >/dev/null 2>&1; then',
79  '    wide=$(identify -ping -format "%w" "$1[0]" 2>/dev/null)',
80  '    tall=$(identify -ping -format "%h" "$1[0]" 2>/dev/null)',
81  // With no tool here nothing is opened either: a PNG is only copied.
82  '  else return 0; fi',
83  '  case "$wide$tall" in ""|*[!0-9]*) return 1 ;; esac',
84  '  [ -n "$wide" ] && [ -n "$tall" ] && [ "${#wide}" -le 5 ] && [ "${#tall}" -le 5 ] || return 1',
85  `  [ "$((wide * tall))" -ge 1 ] && [ "$((wide * tall))" -le ${PIXELS_OPENED} ]`,
86  '}',
87]
88
89// Fetches one address into a folder that is the person's alone, makes what
90// came a PNG, and prints the file and its size. $1 the address, $2 the most
91// bytes, $3 the address the picture was first asked for by (its name). The folder is in the person's own cache, never the shared /tmp, and
92// is refused where it is a link or someone else's. The file is named by the
93// SHA-256 of the address, worked out here, so two addresses never share one.
94// The address is taken as it is written (no braces or brackets are spread
95// into many), and the picture is told by its first bytes, never by its name;
96// what is no picture, or one no tool here can make a PNG, fails.
97const FETCH = [
98  'umask 077',
99  ...FITS,
100  'base="${XDG_CACHE_HOME:-${HOME:+$HOME/.cache}}"',
101  '[ -n "$base" ] || exit 1',
102  'dir="$base/lens-pictures"',
103  'mkdir -p "$dir" || exit 1',
104  '[ -d "$dir" ] && [ ! -L "$dir" ] && [ -O "$dir" ] || exit 1',
105  'chmod 700 "$dir" || exit 1',
106  'if command -v shasum >/dev/null 2>&1; then name=$(printf %s "$3" | shasum -a 256 | cut -c1-64)',
107  'elif command -v sha256sum >/dev/null 2>&1; then name=$(printf %s "$3" | sha256sum | cut -c1-64)',
108  'else exit 1; fi',
109  '[ "${#name}" -eq 64 ] || exit 1',
110  'case "$name" in *[!0-9a-f]*) exit 1 ;; esac',
111  // Pictures not looked at for two weeks go, so the folder does not grow.
112  'find "$dir" -type f -mtime +14 -delete 2>/dev/null',
113  'raw="$dir/$name.$$.raw"; made="$dir/$name.$$.png"; png="$dir/$name.png"',
114  'if [ ! -s "$png" ] || [ -L "$png" ]; then',
115  '  rm -f "$png"',
116  // No redirect is followed here: where the answer is one, the address it
117  // points at is printed, for the caller to hold to the same hosts first.
118  '  said=$(curl -sS --globoff --proto "=https" --max-redirs 0 --max-time 20 --max-filesize "$2" -o "$raw" -w "%{http_code} %{redirect_url}" -- "$1") || { rm -f "$raw"; exit 1; }',
119  '  case "$said" in',
120  '    3??\\ https://*) rm -f "$raw"; printf "to %s\\n" "${said#* }"; exit 0 ;;',
121  '    200\\ *) ;;',
122  '    *) rm -f "$raw"; exit 1 ;;',
123  '  esac',
124  '  [ "$(wc -c < "$raw" | tr -d " ")" -le "$2" ] || { rm -f "$raw"; exit 1; }',
125  '  magic=$(od -An -tx1 -N12 "$raw" | tr -d " \\n")',
126  '  case "$magic" in',
127  '    89504e470d0a1a0a*) mv -f "$raw" "$png" ;;',
128  '    ffd8ff*|474946383?61*|52494646????????57454250)',
129  '      fits "$raw" || { rm -f "$raw"; exit 1; }',
130  '      if command -v sips >/dev/null 2>&1; then sips -s format png "$raw" --out "$made" >/dev/null 2>&1',
131  '      elif command -v magick >/dev/null 2>&1; then magick "$raw[0]" "png:$made" >/dev/null 2>&1',
132  '      elif command -v convert >/dev/null 2>&1; then convert "$raw[0]" "png:$made" >/dev/null 2>&1',
133  '      fi',
134  '      rm -f "$raw"',
135  '      [ -s "$made" ] && mv -f "$made" "$png" || { rm -f "$made"; exit 1; } ;;',
136  '    *) rm -f "$raw"; exit 1 ;;',
137  '  esac',
138  'fi',
139  '[ -s "$png" ] || exit 1',
140  // A PNG says its size in its first chunk: four bytes each, big end first.
141  'set -- $(od -An -tu1 -j16 -N8 "$png")',
142  '[ "$#" -eq 8 ] || exit 1',
143  'printf "%s\\n%s %s\\n" "$png" "$(( (($1 * 256 + $2) * 256 + $3) * 256 + $4 ))" "$(( (($5 * 256 + $6) * 256 + $7) * 256 + $8 ))"',
144].join('\n')
145
146// Fetches a picture and answers where it is and how big, or undefined where
147// it is not one lens fetches, could not be fetched, or is no picture to
148// draw.
149export const fetchPicture = async (run: Run, url: string, forge: string): Promise<Picture | undefined> => {
150  if (!isFetched(url, forge)) {
151    return undefined
152  }
153
154  // A forge answers some pictures with another address. Each one it points
155  // at is held to the same hosts before it is asked, a few times at most, so
156  // a redirect cannot lead the fetch anywhere the first address could not go.
157  let from = url
158  let ran = await run(['sh', '-c', FETCH, 'sh', from, String(PICTURE_BYTES), url], { timeoutMs: 40_000 })
159
160  for (let hop = 0; hop < REDIRECTS && ran.exitCode === 0 && ran.stdout.startsWith('to '); hop++) {
161    from = ran.stdout.slice(3).trim()
162
163    if (!isFetched(from, forge)) {
164      return undefined
165    }
166
167    ran = await run(['sh', '-c', FETCH, 'sh', from, String(PICTURE_BYTES), url], { timeoutMs: 40_000 })
168  }
169
170  const [file = '', size = ''] = ran.stdout.trim().split('\n')
171  const [width = 0, height = 0] = size.split(' ').map(Number)
172
173  return ran.exitCode === 0 &&
174    /^\/[\x20-\x7e]{1,900}\/lens-pictures\/[0-9a-f]{64}\.png$/.test(file) &&
175    Number.isInteger(width) &&
176    Number.isInteger(height) &&
177    width >= 1 &&
178    height >= 1 &&
179    width <= PICTURE_PIXELS &&
180    height <= PICTURE_PIXELS
181    ? { file, width, height }
182    : undefined
183}
184
185// The most a picture of the folder under review may weigh to be drawn, and
186// the side one is brought down to where it is larger.
187export const LOCAL_BYTES = 16 * 1024 * 1024
188const LOCAL_SIDE = 2048
189
190// Whether a file is a picture the code view draws, by its name: the kinds
191// told by their first bytes below. (An SVG is text, and is read as code.)
192export const isPictureFile = (path: string): boolean => /\.(png|jpe?g|gif|webp)$/i.test(path)
193
194// Makes a picture of the folder under review a PNG in the same private
195// folder, and prints the file and its size. $1 the folder, $2 the file's
196// path in it, $3 the commit to read it at (- for the file as it stands),
197// $4 the most bytes, $5 the longest side. The file is named by the SHA-256
198// of what it holds, so a picture that changes is made again. A link is not
199// followed: only a file of the folder itself is read.
200const LOCAL = [
201  'umask 077',
202  ...FITS,
203  'base="${XDG_CACHE_HOME:-${HOME:+$HOME/.cache}}"',
204  '[ -n "$base" ] || exit 1',
205  'dir="$base/lens-pictures"',
206  'mkdir -p "$dir" || exit 1',
207  '[ -d "$dir" ] && [ ! -L "$dir" ] && [ -O "$dir" ] || exit 1',
208  'chmod 700 "$dir" || exit 1',
209  'find "$dir" -type f -mtime +14 -delete 2>/dev/null',
210  'raw="$dir/local.$$.raw"',
211  'if [ "$3" != "-" ]; then',
212  '  cd "$1" || exit 1',
213  '  size=$(git cat-file -s "$3:./$2" 2>/dev/null) || exit 1',
214  '  [ "$size" -le "$4" ] || exit 1',
215  '  git cat-file blob "$3:./$2" > "$raw" 2>/dev/null || { rm -f "$raw"; exit 1; }',
216  'else',
217  '  src="$1/$2"',
218  '  [ -f "$src" ] && [ ! -L "$src" ] || exit 1',
219  '  [ "$(wc -c < "$src" | tr -d " ")" -le "$4" ] || exit 1',
220  '  cp "$src" "$raw" || exit 1',
221  'fi',
222  'if command -v shasum >/dev/null 2>&1; then name=$(shasum -a 256 < "$raw" | cut -c1-64)',
223  'elif command -v sha256sum >/dev/null 2>&1; then name=$(sha256sum < "$raw" | cut -c1-64)',
224  'else rm -f "$raw"; exit 1; fi',
225  '[ "${#name}" -eq 64 ] || { rm -f "$raw"; exit 1; }',
226  'case "$name" in *[!0-9a-f]*) rm -f "$raw"; exit 1 ;; esac',
227  'made="$dir/$name.$$.png"; png="$dir/$name.png"',
228  'if [ ! -s "$png" ] || [ -L "$png" ]; then',
229  '  rm -f "$png"',
230  '  magic=$(od -An -tx1 -N12 "$raw" | tr -d " \\n")',
231  '  case "$magic" in',
232  '    89504e470d0a1a0a*|ffd8ff*|474946383?61*|52494646????????57454250)',
233  '      fits "$raw" || { rm -f "$raw"; exit 1; }',
234  // Brought down to a side the terminal draws, and made a PNG, in one go
235  // where a tool for it is here; a PNG is kept as it is where none is.
236  // (sips makes a small picture larger when asked for a side, so it is
237  // asked only where the picture is over it.)
238  '      if command -v sips >/dev/null 2>&1; then',
239  '        sips -s format png "$raw" --out "$made" >/dev/null 2>&1',
240  '        wide=$(sips -g pixelWidth "$made" 2>/dev/null | awk "/pixelWidth/ {print \\$2}")',
241  '        tall=$(sips -g pixelHeight "$made" 2>/dev/null | awk "/pixelHeight/ {print \\$2}")',
242  '        if [ "${wide:-0}" -gt "$5" ] || [ "${tall:-0}" -gt "$5" ]; then sips -Z "$5" "$made" >/dev/null 2>&1; fi',
243  '      elif command -v magick >/dev/null 2>&1; then magick "$raw[0]" -resize "$5x$5>" "png:$made" >/dev/null 2>&1',
244  '      elif command -v convert >/dev/null 2>&1; then convert "$raw[0]" -resize "$5x$5>" "png:$made" >/dev/null 2>&1',
245  '      else case "$magic" in 89504e470d0a1a0a*) cp "$raw" "$made" ;; esac; fi',
246  '      rm -f "$raw"',
247  '      [ -s "$made" ] && mv -f "$made" "$png" || { rm -f "$made"; exit 1; } ;;',
248  '    *) rm -f "$raw"; exit 1 ;;',
249  '  esac',
250  'else',
251  '  rm -f "$raw"; touch "$png"',
252  'fi',
253  '[ -s "$png" ] || exit 1',
254  'set -- $(od -An -tu1 -j16 -N8 "$png")',
255  '[ "$#" -eq 8 ] || exit 1',
256  'printf "%s\\n%s %s\\n" "$png" "$(( (($1 * 256 + $2) * 256 + $3) * 256 + $4 ))" "$(( (($5 * 256 + $6) * 256 + $7) * 256 + $8 ))"',
257].join('\n')
258
259// A picture of the folder under review, ready to draw: the file as it
260// stands, or as `commit` left it. Undefined where the path is not a plain
261// one inside the folder, the commit is not a plain name, or what is there is
262// no picture a tool here can make a PNG.
263export const localPicture = async (
264  run: Run,
265  repo: string,
266  path: string,
267  commit = '',
268): Promise<Picture | undefined> => {
269  const isInside = !path.startsWith('/') && !path.split('/').includes('..') && !/[\x00-\x1f\x7f]/.test(path)
270  const isNamed = commit === '' || /^[0-9A-Za-z_][0-9A-Za-z._/@{}^~-]{0,200}$/.test(commit)
271
272  if (!repo.startsWith('/') || !isInside || !isNamed || !isPictureFile(path)) {
273    return undefined
274  }
275
276  const ran = await run(['sh', '-c', LOCAL, 'sh', repo, path, commit === '' ? '-' : commit, String(LOCAL_BYTES), String(LOCAL_SIDE)], {
277    timeoutMs: 40_000,
278  })
279  const [file = '', size = ''] = ran.stdout.trim().split('\n')
280  const [width = 0, height = 0] = size.split(' ').map(Number)
281
282  return ran.exitCode === 0 &&
283    /^\/[\x20-\x7e]{1,900}\/lens-pictures\/[0-9a-f]{64}\.png$/.test(file) &&
284    Number.isInteger(width) &&
285    Number.isInteger(height) &&
286    width >= 1 &&
287    height >= 1 &&
288    width <= PICTURE_PIXELS &&
289    height <= PICTURE_PIXELS
290    ? { file, width, height }
291    : undefined
292}
293