@nxxxsooo/opencode-annotate 0.17.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/review.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn, execFile } from "node:child_process"
2
2
  import { createHash, randomUUID } from "node:crypto"
3
- import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"
3
+ import { mkdtemp, mkdir, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises"
4
4
  import os from "node:os"
5
5
  import path from "node:path"
6
6
  import { promisify } from "node:util"
@@ -12,23 +12,61 @@ import { createInputSource } from "./input-source.mjs"
12
12
  import { resolveTuiBinary } from "./tui/binary.mjs"
13
13
 
14
14
  const execute = promisify(execFile)
15
- const documentExtensions = new Set([".md", ".mdx", ".markdown", ".txt"])
15
+ const markdownExtensions = new Set(["md", "mdx", "markdown"])
16
+ const documentLanguages = new Set([
17
+ "txt", "rst", "adoc", "org", "tex", "csv", "tsv", "log",
18
+ "json", "jsonc", "json5", "yaml", "yml", "toml", "ini", "cfg", "conf", "properties", "xml", "plist",
19
+ ])
20
+ const documentNames = new Map([
21
+ [".editorconfig", "ini"], [".gitignore", "text"], [".gitattributes", "text"],
22
+ [".dockerignore", "text"], ["dockerfile", "dockerfile"], ["makefile", "makefile"],
23
+ ])
24
+ const languageAliases = { txt: "text", log: "text", yml: "yaml", plist: "xml" }
16
25
  const maxDocumentBytes = 2 * 1024 * 1024
17
26
 
27
+ function documentLanguage(file) {
28
+ const name = path.basename(file).toLowerCase()
29
+ if (name.startsWith(".env") ||
30
+ /(?:^|[._-])(?:credentials?|secrets?|passwords?|private[._-]?keys?|id_(?:rsa|dsa|ecdsa|ed25519)|pem|key|p12|pfx|ppk)(?:[._-]|$)/.test(name)) return
31
+ const extension = path.extname(name).slice(1)
32
+ if (markdownExtensions.has(extension)) return "markdown"
33
+ if (documentLanguages.has(extension)) return languageAliases[extension] ?? extension
34
+ return documentNames.get(name)
35
+ }
36
+
37
+ async function sessionDirectory(client, sessionID, signal) {
38
+ const session = await client.session.get({ sessionID }, { signal })
39
+ const directory = session.location?.directory
40
+ if (!directory) throw new Error("Can't determine the current session's working directory.")
41
+ return directory
42
+ }
43
+
44
+ function documentSnapshot(text, language) {
45
+ if (language === "markdown") return text
46
+ // Let the Markdown reviewer display the source literally, even if it contains fences.
47
+ let length = 3
48
+ for (const run of text.matchAll(/`{3,}/g)) length = Math.max(length, run[0].length + 1)
49
+ const fence = "`".repeat(length)
50
+ return `${fence}${language}\n${text}${text.endsWith("\n") ? "" : "\n"}${fence}\n`
51
+ }
52
+
53
+ function withinDirectory(directory, file) {
54
+ const relative = path.relative(directory, file)
55
+ return relative && !path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`)
56
+ }
57
+
18
58
  async function documentSource(input, client, sessionID, signal) {
19
59
  let target = input.trim()
20
60
  if ((target.startsWith('"') && target.endsWith('"')) || (target.startsWith("'") && target.endsWith("'"))) {
21
61
  target = target.slice(1, -1)
22
62
  }
23
- if (!target || !documentExtensions.has(path.extname(target).toLowerCase())) {
24
- throw new Error("Choose a Markdown or plain-text file (.md, .mdx, .markdown, .txt).")
25
- }
63
+ const language = documentLanguage(target)
64
+ if (!language) throw new Error("Choose a supported text or config file. Credential files are excluded.")
26
65
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(target)) throw new Error("Use a local file path.")
27
66
  if (target.startsWith("~/")) target = path.join(os.homedir(), target.slice(2))
28
- const session = await client.session.get({ sessionID }, { signal })
29
- const directory = session.location?.directory
30
- if (!path.isAbsolute(target) && !directory) throw new Error("Can't determine the current session's working directory.")
31
- const filePath = path.isAbsolute(target) ? path.normalize(target) : path.resolve(directory, target)
67
+ const filePath = path.isAbsolute(target)
68
+ ? path.normalize(target)
69
+ : path.resolve(await sessionDirectory(client, sessionID, signal), target)
32
70
  try {
33
71
  const info = await stat(filePath)
34
72
  if (!info.isFile()) throw new Error("The target is not a file.")
@@ -43,7 +81,7 @@ async function documentSource(input, client, sessionID, signal) {
43
81
  throw new Error("Use a UTF-8 text file.")
44
82
  }
45
83
  return {
46
- text, filePath,
84
+ text: documentSnapshot(text, language), filePath,
47
85
  sourceHash: createHash("sha256").update(bytes).digest("hex"),
48
86
  snapshot: path.join("source", path.basename(filePath)),
49
87
  }
@@ -373,6 +411,32 @@ export function createReviewCommand(context, options = {}) {
373
411
  return texts.find(text => text.id === chosen)
374
412
  })
375
413
 
414
+ const file = (query = "") => start(async ({ sessionID, signal }) => {
415
+ const directory = await sessionDirectory(context.client, sessionID, signal)
416
+ const { location, data } = await context.client.file.find(
417
+ { query: query.trim(), type: "file", limit: 200, location: { directory } }, { signal },
418
+ )
419
+ if (signal.aborted) return
420
+ const options = data.flatMap(entry => {
421
+ if (entry.type !== "file" || path.isAbsolute(entry.path) || !documentLanguage(entry.path)) return []
422
+ const value = path.resolve(location.directory, entry.path)
423
+ if (!withinDirectory(directory, value)) return []
424
+ return [{ title: entry.path, value, description: path.dirname(entry.path) }]
425
+ })
426
+ if (!options.length) {
427
+ notice("No eligible text or config files found in this session's directory.")
428
+ return
429
+ }
430
+ const chosen = await context.ui.dialog.select({ title: "Annotate file", options })
431
+ if (chosen === undefined || signal.aborted) return
432
+ // The search result is a relative name, but a symlink can still leave the tree.
433
+ const [root, resolved] = await Promise.all([realpath(directory), realpath(chosen)])
434
+ if (!withinDirectory(root, resolved) || !documentLanguage(resolved)) {
435
+ throw new Error("Choose a supported text or config file inside this session's directory.")
436
+ }
437
+ return documentSource(chosen, context.client, sessionID, signal)
438
+ })
439
+
376
440
  const annotateSelection = () => start(async ({ sessionID, signal }) => {
377
441
  const selected = selection?.sessionID === sessionID ? selection.text : ""
378
442
  const needle = compact(selected)
@@ -385,7 +449,7 @@ export function createReviewCommand(context, options = {}) {
385
449
  })
386
450
 
387
451
  return {
388
- run, auto, pick, selection: annotateSelection, webReady: web.ready,
452
+ run, auto, pick, file, selection: annotateSelection, webReady: web.ready,
389
453
  dispose() {
390
454
  context.renderer.off("selection", remember)
391
455
  disposed = true
Binary file
Binary file
Binary file
Binary file
Binary file
package/tui.ts CHANGED
@@ -49,6 +49,14 @@ export default Plugin.define({
49
49
  palette: true,
50
50
  slash: { name: "annotate", arguments: true },
51
51
  run: review.run,
52
+ }, {
53
+ id: "opencode-annotate.annotate-file",
54
+ title: "Annotate a file (TUI)",
55
+ description: "Choose a text or config file in this session's directory",
56
+ group: "Annotate",
57
+ palette: true,
58
+ slash: { name: "annotate-file", arguments: true },
59
+ run: review.file,
52
60
  }, {
53
61
  id: "opencode-annotate.annotate-pick",
54
62
  title: "Annotate earlier text (TUI)",