|
| 1 | +import type { Denops } from "jsr:@denops/std@^7.3.0"; |
| 2 | +import * as fn from "jsr:@denops/std@^7.3.0/function"; |
| 3 | +import { TextLineStream } from "jsr:@std/streams@^1.0.0/text-line-stream"; |
| 4 | + |
| 5 | +import { type Curator, defineCurator } from "../../curator.ts"; |
| 6 | + |
| 7 | +type GrepDetail = { |
| 8 | + path: string; |
| 9 | + line: number; |
| 10 | + context: string; |
| 11 | +}; |
| 12 | + |
| 13 | +const pattern = new RegExp("^(.*?):(\\d+):(.*)$"); |
| 14 | + |
| 15 | +export function grep(): Curator<GrepDetail> { |
| 16 | + let root: string; |
| 17 | + return defineCurator<GrepDetail>( |
| 18 | + async function* (denops, { args, query }, { signal }) { |
| 19 | + root ??= await getAbsolutePathOf(denops, args[0] ?? ".", signal); |
| 20 | + const cmd = new Deno.Command("grep", { |
| 21 | + args: [ |
| 22 | + "--color=never", |
| 23 | + "--no-messages", |
| 24 | + "--recursive", |
| 25 | + "--line-number", |
| 26 | + query, |
| 27 | + "--", |
| 28 | + root, |
| 29 | + ], |
| 30 | + stdin: "null", |
| 31 | + stdout: "piped", |
| 32 | + stderr: "null", |
| 33 | + }); |
| 34 | + await using proc = cmd.spawn(); |
| 35 | + const stream = proc.stdout |
| 36 | + .pipeThrough(new TextDecoderStream()) |
| 37 | + .pipeThrough(new TextLineStream()); |
| 38 | + let id = 0; |
| 39 | + for await (const record of stream) { |
| 40 | + signal?.throwIfAborted(); |
| 41 | + const result = parse(record); |
| 42 | + if (!result) { |
| 43 | + continue; |
| 44 | + } |
| 45 | + const { path, line, context } = result; |
| 46 | + yield { |
| 47 | + id: id++, |
| 48 | + value: `${path}:${line}:${context}`, |
| 49 | + detail: { |
| 50 | + path: path, |
| 51 | + line, |
| 52 | + context, |
| 53 | + }, |
| 54 | + }; |
| 55 | + } |
| 56 | + }, |
| 57 | + ); |
| 58 | +} |
| 59 | + |
| 60 | +async function getAbsolutePathOf( |
| 61 | + denops: Denops, |
| 62 | + expr: string, |
| 63 | + signal?: AbortSignal, |
| 64 | +): Promise<string> { |
| 65 | + const path = await fn.expand(denops, expr) as string; |
| 66 | + signal?.throwIfAborted(); |
| 67 | + const abspath = await fn.fnamemodify(denops, path, ":p"); |
| 68 | + return abspath; |
| 69 | +} |
| 70 | + |
| 71 | +function parse(record: string) { |
| 72 | + const m = record.match(pattern); |
| 73 | + if (!m) return; |
| 74 | + const [, path, line, context] = m; |
| 75 | + return { |
| 76 | + path, |
| 77 | + line: Number(line), |
| 78 | + context, |
| 79 | + }; |
| 80 | +} |
0 commit comments