@carlosstenzel/opencode-git-sidebar 0.0.0-stage → 0.1.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/src/index.ts ADDED
@@ -0,0 +1,561 @@
1
+ import { execFile } from "node:child_process"
2
+ import { lstat, readFile } from "node:fs/promises"
3
+ import { basename, join } from "node:path"
4
+ import { promisify } from "node:util"
5
+ import { Plugin } from "@opencode/plugin"
6
+ import { Git } from "./rpc.js"
7
+
8
+ const exec = promisify(execFile)
9
+
10
+ type DirectoryInput = { directory: string }
11
+ type LimitInput = { directory: string; limit?: number }
12
+ type PrInput = { directory: string; title?: string }
13
+ type BranchActionInput = { directory: string; action: "checkout" | "create" | "delete" | "merge"; name: string }
14
+ type CommitInput = { directory: string; message: string }
15
+ type CommitSelectedInput = { directory: string; message: string; files: string[] }
16
+ type DiffInput = { directory: string; path: string; from?: string }
17
+
18
+ type Status = {
19
+ repo: string
20
+ branch: string
21
+ dirty: boolean
22
+ changes: number
23
+ ahead: number
24
+ behind: number
25
+ upstream: string
26
+ }
27
+ type Branch = {
28
+ name: string
29
+ current: boolean
30
+ upstream: string
31
+ ahead: number
32
+ behind: number
33
+ hash: string
34
+ subject: string
35
+ date: string
36
+ }
37
+ type Commit = {
38
+ hash: string
39
+ short: string
40
+ subject: string
41
+ author: string
42
+ date: string
43
+ files: string[]
44
+ }
45
+ type Stat = { additions: number; deletions: number; binary: boolean }
46
+ type Change = { status: string; path: string; from?: string } & Partial<Stat>
47
+ type Pull = {
48
+ number: number
49
+ title: string
50
+ url: string
51
+ branch: string
52
+ checks: "success" | "failure" | "none"
53
+ }
54
+ type Issue = {
55
+ number: number
56
+ title: string
57
+ url: string
58
+ author: string
59
+ labels: string[]
60
+ comments: number
61
+ date: string
62
+ }
63
+ type Result = { ok: boolean; text: string }
64
+
65
+ async function run(command: string, args: string[], directory: string, signal?: AbortSignal) {
66
+ const { stdout } = await exec(command, args, {
67
+ cwd: directory,
68
+ maxBuffer: 10 * 1024 * 1024,
69
+ signal,
70
+ })
71
+ return stdout.trim()
72
+ }
73
+
74
+ async function runOptional(command: string, args: string[], directory: string, signal?: AbortSignal) {
75
+ try {
76
+ return await run(command, args, directory, signal)
77
+ } catch {
78
+ return ""
79
+ }
80
+ }
81
+
82
+ // Like `run`, but keeps stdout as git wrote it (no trim) and returns what was printed even when the command exits
83
+ // non-zero, as `git diff --no-index` does when the files differ.
84
+ async function runRaw(command: string, args: string[], directory: string, signal?: AbortSignal) {
85
+ try {
86
+ const { stdout } = await exec(command, args, {
87
+ cwd: directory,
88
+ maxBuffer: 10 * 1024 * 1024,
89
+ signal,
90
+ })
91
+ return stdout
92
+ } catch (error: any) {
93
+ return String(error?.stdout ?? "")
94
+ }
95
+ }
96
+
97
+ const DIFF_ARGS = ["-c", "core.quotePath=false", "diff", "--no-color", "--no-ext-diff"]
98
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
99
+ const UNTRACKED_STAT_FILES = 400
100
+ const UNTRACKED_STAT_BYTES = 512 * 1024
101
+ const UNTRACKED_DIFF_FILES = 100
102
+
103
+ // `git status --porcelain` paths are relative to the repository root, so path commands run from there.
104
+ async function repoRoot(directory: string, signal?: AbortSignal) {
105
+ return (await runOptional("git", ["rev-parse", "--show-toplevel"], directory, signal)) || directory
106
+ }
107
+
108
+ // What the working tree is compared against: HEAD, or the empty tree in a repository without commits.
109
+ async function diffBase(directory: string, signal?: AbortSignal) {
110
+ if (await runOptional("git", ["rev-parse", "--verify", "--quiet", "HEAD"], directory, signal)) return "HEAD"
111
+ return (await runOptional("git", ["hash-object", "-t", "tree", "/dev/null"], directory, signal)) || EMPTY_TREE
112
+ }
113
+
114
+ // Parses `git status --porcelain -z`: `XY path\0`, with the original path as an extra field after a rename or copy.
115
+ function parseStatus(raw: string) {
116
+ const fields = raw.split("\0")
117
+ const changes: Change[] = []
118
+ for (let index = 0; index < fields.length; index++) {
119
+ const field = fields[index]
120
+ if (field.length < 4) continue
121
+ const code = field.slice(0, 2)
122
+ const change: Change = { status: code.trim(), path: field.slice(3) }
123
+ if (code.includes("R") || code.includes("C")) {
124
+ const from = fields[++index]
125
+ if (from) change.from = from
126
+ }
127
+ changes.push(change)
128
+ }
129
+ return changes
130
+ }
131
+
132
+ // Parses `git diff --numstat -z`: `added\tdeleted\tpath\0`, or `added\tdeleted\t\0old\0new\0` for a rename.
133
+ function parseNumstat(raw: string) {
134
+ const stats = new Map<string, Stat>()
135
+ const fields = raw.split("\0")
136
+ for (let index = 0; index < fields.length; index++) {
137
+ const match = /^(-|\d+)\t(-|\d+)\t([\s\S]*)$/.exec(fields[index])
138
+ if (!match) continue
139
+ let path = match[3]
140
+ if (!path) {
141
+ index += 2
142
+ path = fields[index] ?? ""
143
+ }
144
+ if (!path) continue
145
+ const binary = match[1] === "-" || match[2] === "-"
146
+ stats.set(path, {
147
+ additions: binary ? 0 : Number(match[1]) || 0,
148
+ deletions: binary ? 0 : Number(match[2]) || 0,
149
+ binary,
150
+ })
151
+ }
152
+ return stats
153
+ }
154
+
155
+ // Lines an untracked file would add. Undefined when it is not a regular file or is too large to count cheaply.
156
+ async function untrackedStat(file: string): Promise<Stat | undefined> {
157
+ try {
158
+ const info = await lstat(file)
159
+ if (!info.isFile() || info.size > UNTRACKED_STAT_BYTES) return undefined
160
+ const bytes = await readFile(file)
161
+ if (bytes.subarray(0, 8000).includes(0)) return { additions: 0, deletions: 0, binary: true }
162
+ let lines = 0
163
+ for (const byte of bytes) if (byte === 10) lines++
164
+ if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) lines++
165
+ return { additions: lines, deletions: 0, binary: false }
166
+ } catch {
167
+ return undefined
168
+ }
169
+ }
170
+
171
+ // Stats of the untracked entries of `git status`: a file, or a directory git lists as one entry (`dir/`).
172
+ async function untrackedStats(entries: Change[], root: string, signal?: AbortSignal) {
173
+ const stats = new Map<string, Stat>()
174
+ if (!entries.length) return stats
175
+ const raw = await runRaw("git", ["ls-files", "--others", "--exclude-standard", "-z"], root, signal)
176
+ const files = raw.split("\0").filter(Boolean)
177
+ if (files.length > UNTRACKED_STAT_FILES) return stats
178
+ const counted = new Map<string, Stat | undefined>()
179
+ for (let start = 0; start < files.length; start += 16) {
180
+ const batch = files.slice(start, start + 16)
181
+ const results = await Promise.all(batch.map((file) => untrackedStat(join(root, file))))
182
+ batch.forEach((file, index) => counted.set(file, results[index]))
183
+ }
184
+ for (const entry of entries) {
185
+ const inside = entry.path.endsWith("/") ? files.filter((file) => file.startsWith(entry.path)) : [entry.path]
186
+ const parts = inside.map((file) => counted.get(file))
187
+ if (!parts.length || parts.some((part) => !part)) continue
188
+ const known = parts as Stat[]
189
+ stats.set(entry.path, {
190
+ additions: known.reduce((sum, part) => sum + part.additions, 0),
191
+ deletions: 0,
192
+ binary: known.every((part) => part.binary),
193
+ })
194
+ }
195
+ return stats
196
+ }
197
+
198
+ function errorMessage(error: unknown) {
199
+ return error instanceof Error ? error.message : String(error)
200
+ }
201
+
202
+ function parseChecks(rollup: unknown): Pull["checks"] {
203
+ const checks = Array.isArray(rollup) ? rollup : []
204
+ if (!checks.length) return "none"
205
+ const failed = checks.some((check: any) => {
206
+ const state = String(check?.conclusion ?? check?.state ?? "").toUpperCase()
207
+ return state.includes("FAIL") || state.includes("ERROR") || state.includes("TIMED_OUT")
208
+ })
209
+ if (failed) return "failure"
210
+ const success = checks.every((check: any) => {
211
+ const state = String(check?.conclusion ?? check?.state ?? "").toUpperCase()
212
+ return state.includes("SUCCESS") || state.includes("NEUTRAL") || state.includes("SKIPPED")
213
+ })
214
+ return success ? "success" : "none"
215
+ }
216
+
217
+ function safeRef(name: string) {
218
+ return /^[A-Za-z0-9._/-]+$/.test(name) && !name.startsWith("-") && !name.includes("..")
219
+ }
220
+
221
+ function safePath(path: string) {
222
+ return (
223
+ !!path &&
224
+ !path.startsWith("/") &&
225
+ !path.startsWith("-") &&
226
+ !path.includes("\n") &&
227
+ !path.includes("\r") &&
228
+ !path.split("/").includes("..")
229
+ )
230
+ }
231
+
232
+ async function counts(upstream: string, ref: string, directory: string, signal?: AbortSignal) {
233
+ const raw = await runOptional(
234
+ "git",
235
+ ["rev-list", "--left-right", "--count", `${upstream}...${ref}`],
236
+ directory,
237
+ signal,
238
+ )
239
+ const [behind, ahead] = raw.split(/\s+/).map((value) => Number(value) || 0)
240
+ return { ahead, behind }
241
+ }
242
+
243
+ function splitRecord(line: string) {
244
+ const parts = line.split("\x1f")
245
+ return {
246
+ hash: parts[0] ?? "",
247
+ short: parts[1] ?? "",
248
+ subject: parts[2] ?? "",
249
+ author: parts[3] ?? "",
250
+ date: parts[4] ?? "",
251
+ }
252
+ }
253
+
254
+ export default Plugin.define({
255
+ id: "git-sidebar",
256
+ async setup(ctx) {
257
+ await ctx.rpc.register(Git, {
258
+ status: async (input, context) => {
259
+ const { directory } = input as DirectoryInput
260
+ const branch =
261
+ (await runOptional("git", ["rev-parse", "--abbrev-ref", "HEAD"], directory, context.signal)) ||
262
+ "(desanexado)"
263
+ const root = await runOptional("git", ["rev-parse", "--show-toplevel"], directory, context.signal)
264
+ const porcelain = await runOptional("git", ["status", "--porcelain"], directory, context.signal)
265
+ const changes = porcelain ? porcelain.split("\n").filter(Boolean).length : 0
266
+ const upstream = await runOptional(
267
+ "git",
268
+ ["rev-parse", "--abbrev-ref", "@{upstream}"],
269
+ directory,
270
+ context.signal,
271
+ )
272
+ const { ahead, behind } = upstream ? await counts(upstream, "HEAD", directory, context.signal) : { ahead: 0, behind: 0 }
273
+ return {
274
+ repo: root ? basename(root) : basename(directory),
275
+ branch,
276
+ dirty: changes > 0,
277
+ changes,
278
+ ahead,
279
+ behind,
280
+ upstream,
281
+ } satisfies Status
282
+ },
283
+
284
+ pulls: async (input, context) => {
285
+ const { directory } = input as DirectoryInput
286
+ try {
287
+ const raw = await run(
288
+ "gh",
289
+ [
290
+ "pr",
291
+ "list",
292
+ "--state",
293
+ "open",
294
+ "--json",
295
+ "number,title,url,headRefName,statusCheckRollup",
296
+ ],
297
+ directory,
298
+ context.signal,
299
+ )
300
+ const pulls = JSON.parse(raw || "[]")
301
+ return (Array.isArray(pulls) ? pulls : []).map((pull: any): Pull => ({
302
+ number: Number(pull.number) || 0,
303
+ title: String(pull.title ?? ""),
304
+ url: String(pull.url ?? ""),
305
+ branch: String(pull.headRefName ?? ""),
306
+ checks: parseChecks(pull.statusCheckRollup),
307
+ }))
308
+ } catch {
309
+ return [] as Pull[]
310
+ }
311
+ },
312
+
313
+ issues: async (input, context) => {
314
+ const { directory } = input as DirectoryInput
315
+ try {
316
+ const raw = await run(
317
+ "gh",
318
+ [
319
+ "issue",
320
+ "list",
321
+ "--state",
322
+ "open",
323
+ "--limit",
324
+ "30",
325
+ "--json",
326
+ "number,title,url,author,labels,comments,createdAt",
327
+ ],
328
+ directory,
329
+ context.signal,
330
+ )
331
+ const issues = JSON.parse(raw || "[]")
332
+ return (Array.isArray(issues) ? issues : []).map((issue: any): Issue => ({
333
+ number: Number(issue.number) || 0,
334
+ title: String(issue.title ?? ""),
335
+ url: String(issue.url ?? ""),
336
+ author: String(issue.author?.login ?? ""),
337
+ labels: (Array.isArray(issue.labels) ? issue.labels : []).map((label: any) =>
338
+ String(label?.name ?? ""),
339
+ ).filter(Boolean),
340
+ comments: Number(issue.comments) || 0,
341
+ date: String(issue.createdAt ?? ""),
342
+ }))
343
+ } catch {
344
+ return [] as Issue[]
345
+ }
346
+ },
347
+
348
+ branches: async (input, context) => {
349
+ const { directory, limit } = input as LimitInput
350
+ const current = await runOptional("git", ["rev-parse", "--abbrev-ref", "HEAD"], directory, context.signal)
351
+ const format = "%(refname:short)\t%(objectname:short)\t%(upstream:short)\t%(contents:subject)\t%(committerdate:iso-strict)"
352
+ const local = await runOptional(
353
+ "git",
354
+ ["for-each-ref", `--format=${format}`, "refs/heads"],
355
+ directory,
356
+ context.signal,
357
+ )
358
+ const remote = await runOptional(
359
+ "git",
360
+ ["for-each-ref", `--format=${format}`, "refs/remotes"],
361
+ directory,
362
+ context.signal,
363
+ )
364
+ const lines = [local, remote].filter(Boolean).join("\n").split("\n").filter(Boolean)
365
+ const result: Branch[] = []
366
+ for (const line of lines) {
367
+ const [name, hash, upstream, subject, date] = line.split("\t")
368
+ if (!name || name.endsWith("/HEAD")) continue
369
+ const position = await counts(upstream, name, directory, context.signal)
370
+ result.push({
371
+ name,
372
+ current: name === current,
373
+ upstream: upstream || "",
374
+ ahead: upstream ? position.ahead : 0,
375
+ behind: upstream ? position.behind : 0,
376
+ hash: hash || "",
377
+ subject: subject || "",
378
+ date: date || "",
379
+ })
380
+ if (result.length >= (limit || 60)) break
381
+ }
382
+ return result
383
+ },
384
+
385
+ commits: async (input, context) => {
386
+ const { directory, limit } = input as LimitInput
387
+ const raw = await runOptional(
388
+ "git",
389
+ [
390
+ "log",
391
+ `--max-count=${limit || 20}`,
392
+ "--date=iso-strict",
393
+ "--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%ad",
394
+ ],
395
+ directory,
396
+ context.signal,
397
+ )
398
+ const commits: Commit[] = []
399
+ for (const line of raw.split("\n").filter(Boolean)) {
400
+ const record = splitRecord(line)
401
+ if (!record.hash) continue
402
+ const filesRaw = await runOptional(
403
+ "git",
404
+ ["diff-tree", "--no-commit-id", "--name-only", "-r", record.hash],
405
+ directory,
406
+ context.signal,
407
+ )
408
+ commits.push({
409
+ ...record,
410
+ files: filesRaw.split("\n").filter(Boolean),
411
+ })
412
+ }
413
+ return commits
414
+ },
415
+
416
+ changes: async (input, context) => {
417
+ const { directory } = input as DirectoryInput
418
+ // `-z` keeps paths as they are (no quoting) and `runRaw` keeps the leading space of an unstaged ` M` entry.
419
+ const raw = await runRaw("git", ["status", "--porcelain", "-z"], directory, context.signal)
420
+ const changes = parseStatus(raw)
421
+ if (!changes.length) return changes
422
+ const root = await repoRoot(directory, context.signal)
423
+ const base = await diffBase(root, context.signal)
424
+ const [tracked, untracked] = await Promise.all([
425
+ runRaw("git", [...DIFF_ARGS, "--numstat", "-z", "-M", base, "--"], root, context.signal).then(parseNumstat),
426
+ untrackedStats(
427
+ changes.filter((change) => change.status === "??"),
428
+ root,
429
+ context.signal,
430
+ ),
431
+ ])
432
+ return changes.map((change): Change => ({
433
+ ...change,
434
+ ...(change.status === "??" ? untracked.get(change.path) : tracked.get(change.path)),
435
+ }))
436
+ },
437
+
438
+ branchAction: async (input, context) => {
439
+ const { directory, action, name } = input as BranchActionInput
440
+ if (!safeRef(name)) return { ok: false, text: "Nome de branch inválido" } satisfies Result
441
+ const commands: Record<BranchActionInput["action"], string[]> = {
442
+ checkout: ["checkout", name],
443
+ create: ["checkout", "-b", name],
444
+ delete: ["branch", "-d", name],
445
+ merge: ["merge", name, "--no-edit"],
446
+ }
447
+ try {
448
+ const text = await run("git", commands[action], directory, context.signal)
449
+ return { ok: true, text: text || `branch ${action} concluído` } satisfies Result
450
+ } catch (error) {
451
+ return { ok: false, text: errorMessage(error) } satisfies Result
452
+ }
453
+ },
454
+
455
+ pull: async (input, context) => {
456
+ const { directory } = input as DirectoryInput
457
+ try {
458
+ const text = await run("git", ["pull", "--ff-only"], directory, context.signal)
459
+ return { ok: true, text: text || "pull concluído" } satisfies Result
460
+ } catch (error) {
461
+ return { ok: false, text: errorMessage(error) } satisfies Result
462
+ }
463
+ },
464
+
465
+ push: async (input, context) => {
466
+ const { directory } = input as DirectoryInput
467
+ try {
468
+ const text = await run("git", ["push", "-u", "origin", "HEAD"], directory, context.signal)
469
+ return { ok: true, text: text || "push concluído" } satisfies Result
470
+ } catch (error) {
471
+ return { ok: false, text: errorMessage(error) } satisfies Result
472
+ }
473
+ },
474
+
475
+ commit: async (input, context) => {
476
+ const { directory, message } = input as CommitInput
477
+ if (!message.trim()) return { ok: false, text: "Mensagem vazia" } satisfies Result
478
+ try {
479
+ await run("git", ["add", "-A"], directory, context.signal)
480
+ const text = await run("git", ["commit", "-m", message], directory, context.signal)
481
+ return { ok: true, text: text || "commit criado" } satisfies Result
482
+ } catch (error) {
483
+ return { ok: false, text: errorMessage(error) } satisfies Result
484
+ }
485
+ },
486
+
487
+ commitSelected: async (input, context) => {
488
+ const { directory, message, files } = input as CommitSelectedInput
489
+ if (!message.trim()) return { ok: false, text: "Mensagem vazia" } satisfies Result
490
+ const clean = files.filter(safePath)
491
+ if (!clean.length) return { ok: false, text: "Nenhum arquivo válido selecionado" } satisfies Result
492
+ try {
493
+ // The paths come from `git status --porcelain`, which is relative to the repository root.
494
+ const root = await repoRoot(directory, context.signal)
495
+ const stagedDeleted = new Set(
496
+ (
497
+ await runOptional(
498
+ "git",
499
+ ["diff", "--cached", "--name-only", "--diff-filter=D", "-z", "--"],
500
+ root,
501
+ context.signal,
502
+ )
503
+ )
504
+ .split("\0")
505
+ .filter(Boolean),
506
+ )
507
+ const stageable = clean.filter((path) => !stagedDeleted.has(path))
508
+ if (stageable.length) {
509
+ await run("git", ["add", "-A", "--", ...stageable], root, context.signal)
510
+ }
511
+ const text = await run("git", ["commit", "-m", message], directory, context.signal)
512
+ return { ok: true, text: text || "commit criado" } satisfies Result
513
+ } catch (error) {
514
+ return { ok: false, text: errorMessage(error) } satisfies Result
515
+ }
516
+ },
517
+
518
+ fileDiff: async (input, context) => {
519
+ const { directory, path, from } = input as DiffInput
520
+ if (!safePath(path) || (from !== undefined && !safePath(from))) return { text: "Caminho inválido" }
521
+ const root = await repoRoot(directory, context.signal)
522
+ // Untracked: a file, or every file of a directory git lists as one entry.
523
+ const others = (
524
+ await runRaw("git", ["ls-files", "--others", "--exclude-standard", "-z", "--", path], root, context.signal)
525
+ )
526
+ .split("\0")
527
+ .filter(Boolean)
528
+ if (others.length) {
529
+ const shown = others.slice(0, UNTRACKED_DIFF_FILES)
530
+ const parts: string[] = []
531
+ for (const file of shown) {
532
+ parts.push(
533
+ await runRaw("git", [...DIFF_ARGS, "--no-index", "--", "/dev/null", file], root, context.signal),
534
+ )
535
+ }
536
+ const text = parts
537
+ .map((part) => part.replace(/\n+$/, ""))
538
+ .filter(Boolean)
539
+ .join("\n")
540
+ return others.length > shown.length ? { text, truncated: true } : { text }
541
+ }
542
+ const base = await diffBase(root, context.signal)
543
+ const paths = from && from !== path ? [from, path] : [path]
544
+ const text = await runRaw("git", [...DIFF_ARGS, "-M", base, "--", ...paths], root, context.signal)
545
+ return { text: text.replace(/\n+$/, "") }
546
+ },
547
+
548
+ pr: async (input, context) => {
549
+ const { directory, title } = input as PrInput
550
+ try {
551
+ const args = ["pr", "create", "--fill"]
552
+ if (title) args.push("--title", title)
553
+ const text = await run("gh", args, directory, context.signal)
554
+ return { ok: true, text: text || "PR criado" } satisfies Result
555
+ } catch (error) {
556
+ return { ok: false, text: errorMessage(error) } satisfies Result
557
+ }
558
+ },
559
+ })
560
+ },
561
+ })