@carlosstenzel/opencode-git-sidebar 0.1.1 → 0.1.3

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.
@@ -0,0 +1,99 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800" viewBox="0 0 1200 800" role="img" aria-label="Mock da aba Arquivos com agrupamento, seleção e estatísticas">
2
+ <defs>
3
+ <linearGradient id="bg2" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#0f172a"/>
5
+ <stop offset="1" stop-color="#1e293b"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect width="1200" height="800" fill="url(#bg2)"/>
9
+ <text x="48" y="64" fill="#e2e8f0" font-family="system-ui, sans-serif" font-size="30" font-weight="700">Aba Arquivos — seleção e commit</text>
10
+ <text x="48" y="94" fill="#94a3b8" font-family="system-ui, sans-serif" font-size="16">Nomes de arquivo e branches fictícios · dados mascarados</text>
11
+
12
+ <rect x="48" y="126" width="472" height="612" rx="16" fill="#111827" stroke="#334155"/>
13
+ <text x="72" y="164" fill="#f8fafc" font-family="system-ui, sans-serif" font-size="16" font-weight="700">Alterações</text>
14
+ <text x="72" y="190" fill="#94a3b8" font-family="system-ui, sans-serif" font-size="13">8 arquivos · +42 −17</text>
15
+
16
+ <g font-family="system-ui, sans-serif" font-size="12">
17
+ <rect x="72" y="212" width="424" height="32" rx="7" fill="#1f2937" stroke="#475569"/>
18
+ <text x="86" y="233" fill="#fca5a5" font-weight="700">Conflitos</text>
19
+ <text x="430" y="233" fill="#cbd5e1">1</text>
20
+
21
+ <rect x="72" y="256" width="424" height="32" rx="7" fill="#1f2937" stroke="#475569"/>
22
+ <text x="86" y="277" fill="#fdba74" font-weight="700">Modificados</text>
23
+ <text x="430" y="277" fill="#cbd5e1">3</text>
24
+
25
+ <rect x="72" y="300" width="424" height="32" rx="7" fill="#1f2937" stroke="#475569"/>
26
+ <text x="86" y="321" fill="#86efac" font-weight="700">Adicionados</text>
27
+ <text x="430" y="321" fill="#cbd5e1">2</text>
28
+
29
+ <rect x="72" y="344" width="424" height="32" rx="7" fill="#1f2937" stroke="#475569"/>
30
+ <text x="86" y="365" fill="#f9a8d4" font-weight="700">Não rastreados</text>
31
+ <text x="430" y="365" fill="#cbd5e1">2</text>
32
+
33
+ <rect x="72" y="392" width="424" height="62" rx="9" fill="#1f2937" stroke="#7c3aed"/>
34
+ <rect x="84" y="406" width="16" height="16" rx="4" fill="#7c3aed"/>
35
+ <text x="110" y="420" fill="#64748b" font-size="11">src/components/</text>
36
+ <text x="110" y="440" fill="#f8fafc" font-size="13" font-weight="700">Hero.tsx</text>
37
+ <rect x="392" y="408" width="42" height="18" rx="6" fill="#065f46"/>
38
+ <text x="400" y="422" fill="#d1fae5" font-size="11">+12 −4</text>
39
+ <text x="450" y="422" fill="#fbbf24" font-size="14">M</text>
40
+
41
+ <rect x="72" y="464" width="424" height="62" rx="9" fill="#1f2937" stroke="#7c3aed"/>
42
+ <rect x="84" y="478" width="16" height="16" rx="4" fill="#7c3aed"/>
43
+ <text x="110" y="492" fill="#64748b" font-size="11">src/styles/</text>
44
+ <text x="110" y="512" fill="#f8fafc" font-size="13" font-weight="700">global.css</text>
45
+ <rect x="398" y="480" width="36" height="18" rx="6" fill="#065f46"/>
46
+ <text x="406" y="494" fill="#d1fae5" font-size="11">+3 −1</text>
47
+ <text x="450" y="496" fill="#fbbf24" font-size="14">M</text>
48
+
49
+ <rect x="72" y="536" width="424" height="62" rx="9" fill="#1f2937" stroke="#475569"/>
50
+ <rect x="84" y="550" width="16" height="16" rx="4" fill="none" stroke="#64748b"/>
51
+ <text x="110" y="564" fill="#64748b" font-size="11">docs/</text>
52
+ <text x="110" y="584" fill="#f8fafc" font-size="13" font-weight="700">CHANGELOG.md</text>
53
+ <rect x="398" y="552" width="36" height="18" rx="6" fill="#065f46"/>
54
+ <text x="406" y="566" fill="#d1fae5" font-size="11">+8 −0</text>
55
+ <text x="450" y="568" fill="#60a5fa" font-size="14">A</text>
56
+
57
+ <rect x="72" y="676" width="424" height="42" rx="9" fill="#7c3aed"/>
58
+ <text x="176" y="703" fill="#fff" font-weight="700">Commit selecionados (2)</text>
59
+ </g>
60
+
61
+ <rect x="556" y="126" width="596" height="612" rx="16" fill="#111827" stroke="#334155"/>
62
+ <g font-family="system-ui, sans-serif">
63
+ <text x="584" y="164" fill="#f8fafc" font-size="16" font-weight="700">2 de 8 selecionados</text>
64
+ <text x="584" y="190" fill="#94a3b8" font-size="13">+15 −5 · 2 arquivos</text>
65
+
66
+ <rect x="584" y="216" width="540" height="484" rx="10" fill="#0b1220" stroke="#334155"/>
67
+ <text x="610" y="252" fill="#a78bfa" font-family="monospace" font-size="13">src/components/Hero.tsx</text>
68
+ <rect x="610" y="268" width="488" height="1" fill="#334155"/>
69
+
70
+ <text x="610" y="300" fill="#64748b" font-family="monospace" font-size="12">12</text>
71
+ <text x="650" y="300" fill="#64748b" font-family="monospace" font-size="12">12</text>
72
+ <text x="690" y="300" fill="#94a3b8" font-family="monospace" font-size="12"> export function Hero() {</text>
73
+ <text x="610" y="324" fill="#64748b" font-family="monospace" font-size="12">13</text>
74
+ <text x="650" y="324" fill="#64748b" font-family="monospace" font-size="12">13</text>
75
+ <text x="690" y="324" fill="#94a3b8" font-family="monospace" font-size="12"> return (</text>
76
+ <rect x="602" y="336" width="486" height="22" fill="#064e3b" opacity="0.45"/>
77
+ <text x="610" y="352" fill="#64748b" font-family="monospace" font-size="12">14</text>
78
+ <text x="650" y="352" fill="#34d399" font-family="monospace" font-size="12">14</text>
79
+ <text x="690" y="352" fill="#d1fae5" font-family="monospace" font-size="12">+ &lt;section className=&quot;hero&quot;&gt;</text>
80
+ <rect x="602" y="360" width="486" height="22" fill="#7f1d1d" opacity="0.35"/>
81
+ <text x="610" y="376" fill="#64748b" font-family="monospace" font-size="12">15</text>
82
+ <text x="650" y="376" fill="#f87171" font-family="monospace" font-size="12">15</text>
83
+ <text x="690" y="376" fill="#fecaca" font-family="monospace" font-size="12">- &lt;div className=&quot;banner&quot;&gt;</text>
84
+ <text x="610" y="400" fill="#64748b" font-family="monospace" font-size="12">16</text>
85
+ <text x="650" y="400" fill="#34d399" font-family="monospace" font-size="12">16</text>
86
+ <text x="690" y="400" fill="#d1fae5" font-family="monospace" font-size="12">+ &lt;h1&gt;Nova home&lt;/h1&gt;</text>
87
+ <text x="610" y="424" fill="#64748b" font-family="monospace" font-size="12">17</text>
88
+ <text x="650" y="424" fill="#64748b" font-family="monospace" font-size="12">17</text>
89
+ <text x="690" y="424" fill="#94a3b8" font-family="monospace" font-size="12"> )</text>
90
+ <text x="610" y="448" fill="#64748b" font-family="monospace" font-size="12">18</text>
91
+ <text x="650" y="448" fill="#64748b" font-family="monospace" font-size="12">18</text>
92
+ <text x="690" y="448" fill="#94a3b8" font-family="monospace" font-size="12"> }</text>
93
+
94
+ <rect x="584" y="712" width="128" height="26" rx="7" fill="#1f2937" stroke="#475569"/>
95
+ <text x="606" y="730" fill="#cbd5e1" font-size="12">1 de 2 · K / J</text>
96
+ <rect x="934" y="712" width="190" height="26" rx="7" fill="#1f2937" stroke="#475569"/>
97
+ <text x="950" y="730" fill="#cbd5e1" font-size="12">Incluir no commit ✓</text>
98
+ </g>
99
+ </svg>
@@ -0,0 +1,79 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800" viewBox="0 0 1200 800" role="img" aria-label="Mock do painel lateral Git no OpenCode Desktop">
2
+ <defs>
3
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#0f172a"/>
5
+ <stop offset="1" stop-color="#1e293b"/>
6
+ </linearGradient>
7
+ <linearGradient id="card" x1="0" y1="0" x2="0" y2="1">
8
+ <stop offset="0" stop-color="#ffffff" stop-opacity="0.10"/>
9
+ <stop offset="1" stop-color="#ffffff" stop-opacity="0.04"/>
10
+ </linearGradient>
11
+ </defs>
12
+ <rect width="1200" height="800" fill="url(#bg)"/>
13
+ <text x="48" y="66" fill="#e2e8f0" font-family="system-ui, sans-serif" font-size="30" font-weight="700">Git sidebar — visão geral</text>
14
+ <text x="48" y="96" fill="#94a3b8" font-family="system-ui, sans-serif" font-size="16">Mock com dados fictícios · OpenCode Desktop (Electron)</text>
15
+
16
+ <rect x="48" y="130" width="1104" height="610" rx="16" fill="#0b1220" stroke="#334155"/>
17
+ <circle cx="80" cy="162" r="6" fill="#f87171"/>
18
+ <circle cx="100" cy="162" r="6" fill="#fbbf24"/>
19
+ <circle cx="120" cy="162" r="6" fill="#34d399"/>
20
+ <text x="150" y="168" fill="#64748b" font-family="system-ui, sans-serif" font-size="13">meu-projeto — OpenCode</text>
21
+
22
+ <rect x="872" y="130" width="280" height="610" fill="#111827" stroke="#334155"/>
23
+ <rect x="884" y="150" width="256" height="580" rx="10" fill="url(#card)" stroke="#334155"/>
24
+
25
+ <rect x="900" y="168" width="224" height="74" rx="9" fill="#1f2937" stroke="#475569"/>
26
+ <text x="916" y="194" fill="#f8fafc" font-family="system-ui, sans-serif" font-size="14" font-weight="700">meu-projeto</text>
27
+ <rect x="916" y="204" width="126" height="20" rx="10" fill="#7c3aed"/>
28
+ <text x="924" y="218" fill="#fff" font-family="system-ui, sans-serif" font-size="11">feature/nova-home</text>
29
+ <rect x="1050" y="204" width="58" height="20" rx="10" fill="#334155"/>
30
+ <text x="1059" y="218" fill="#e2e8f0" font-family="system-ui, sans-serif" font-size="11">↑ 2 ↓ 1</text>
31
+
32
+ <g font-family="system-ui, sans-serif" font-size="12">
33
+ <rect x="900" y="254" width="106" height="30" rx="7" fill="#7c3aed"/>
34
+ <text x="928" y="274" fill="#fff" font-weight="700">Branches</text>
35
+ <rect x="1012" y="254" width="94" height="30" rx="7" fill="#1f2937"/>
36
+ <text x="1032" y="274" fill="#cbd5e1">Commits</text>
37
+ <rect x="1112" y="254" width="76" height="30" rx="7" fill="#1f2937"/>
38
+ <text x="1130" y="274" fill="#cbd5e1">PRs</text>
39
+
40
+ <rect x="900" y="298" width="224" height="34" rx="8" fill="#1f2937" stroke="#475569"/>
41
+ <text x="912" y="320" fill="#94a3b8">Filtrar branches</text>
42
+
43
+ <rect x="900" y="342" width="224" height="54" rx="8" fill="#1f2937" stroke="#475569"/>
44
+ <circle cx="918" cy="358" r="4" fill="#34d399"/>
45
+ <text x="930" y="362" fill="#f8fafc" font-weight="700">main</text>
46
+ <text x="930" y="382" fill="#94a3b8">atual · ahead 2</text>
47
+
48
+ <rect x="900" y="404" width="224" height="54" rx="8" fill="#1f2937" stroke="#475569"/>
49
+ <circle cx="918" cy="420" r="4" fill="#60a5fa"/>
50
+ <text x="930" y="424" fill="#f8fafc">feature/nova-home</text>
51
+ <text x="930" y="444" fill="#94a3b8">a1b2c3d · Ajusta hero</text>
52
+
53
+ <rect x="900" y="466" width="224" height="54" rx="8" fill="#1f2937" stroke="#475569"/>
54
+ <circle cx="918" cy="482" r="4" fill="#fbbf24"/>
55
+ <text x="930" y="486" fill="#f8fafc">bugfix/menu-mobile</text>
56
+ <text x="930" y="506" fill="#94a3b8">9f8e7d6 · Corrige overlay</text>
57
+
58
+ <rect x="900" y="530" width="224" height="54" rx="8" fill="#1f2937" stroke="#475569"/>
59
+ <circle cx="918" cy="546" r="4" fill="#f472b6"/>
60
+ <text x="930" y="550" fill="#f8fafc">docs/readme</text>
61
+ <text x="930" y="570" fill="#94a3b8">4c5d6e7 · Atualiza docs</text>
62
+
63
+ <rect x="900" y="634" width="224" height="44" rx="9" fill="#7c3aed"/>
64
+ <text x="966" y="661" fill="#fff" font-weight="700">Commit selecionados</text>
65
+ </g>
66
+
67
+ <g font-family="system-ui, sans-serif" fill="#94a3b8" font-size="14">
68
+ <text x="92" y="220">Área de trabalho</text>
69
+ <rect x="92" y="240" width="724" height="360" rx="10" fill="#111827" stroke="#334155"/>
70
+ <text x="120" y="284" fill="#e2e8f0" font-size="18" font-weight="700">Selecione arquivos e revise o diff antes de commitar</text>
71
+ <text x="120" y="320">O painel acompanha a sessão atual e agrupa as alterações por tipo.</text>
72
+ <rect x="120" y="352" width="668" height="52" rx="8" fill="#1f2937" stroke="#475569"/>
73
+ <text x="140" y="385" fill="#cbd5e1">src/components/Hero.tsx +12 −4</text>
74
+ <rect x="120" y="416" width="668" height="52" rx="8" fill="#1f2937" stroke="#475569"/>
75
+ <text x="140" y="449" fill="#cbd5e1">src/styles/global.css +3 −1</text>
76
+ <rect x="120" y="480" width="668" height="52" rx="8" fill="#1f2937" stroke="#475569"/>
77
+ <text x="140" y="513" fill="#cbd5e1">docs/CHANGELOG.md +8 −0</text>
78
+ </g>
79
+ </svg>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@carlosstenzel/opencode-git-sidebar",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Git and PR sidebar for OpenCode Desktop: branches, commits, grouped files with inline diff, selective commits, pull requests and issues.",
5
5
  "license": "MIT",
6
6
  "author": "Carlos Stenzel",
@@ -14,13 +14,18 @@
14
14
  "files": [
15
15
  "src",
16
16
  "dist",
17
+ "docs/images",
17
18
  "README.md",
19
+ "README-pt-br.md",
18
20
  "LICENSE"
19
21
  ],
20
22
  "scripts": {
21
23
  "build": "vite build",
22
24
  "dev": "vite build --watch",
23
25
  "typecheck": "tsc --noEmit",
26
+ "test": "vitest run",
27
+ "verify:package": "node scripts/verify-package.mjs",
28
+ "verify:release": "node scripts/verify-release.mjs",
24
29
  "prepack": "npm run typecheck && npm run build"
25
30
  },
26
31
  "keywords": [
@@ -58,6 +63,7 @@
58
63
  "solid-js": "^1.9.0",
59
64
  "typescript": "^5.8.0",
60
65
  "vite": "^7.0.0",
61
- "vite-plugin-solid": "^2.11.0"
66
+ "vite-plugin-solid": "^2.11.0",
67
+ "vitest": "^5.1.2"
62
68
  }
63
69
  }
@@ -0,0 +1,165 @@
1
+ import { parseStatus, type Change } from "./git-parse.js"
2
+ import { errorMessage, repoRoot, run, runRaw, safePath } from "./git-exec.js"
3
+ import { lstat, readdir } from "node:fs/promises"
4
+ import { join } from "node:path"
5
+
6
+ export type CommitSelectionPlan = {
7
+ root: string
8
+ commitPaths: string[]
9
+ intentPaths: string[]
10
+ }
11
+
12
+ // Filtra os selecionados com `safePath`, mantém a ordem e acrescenta o `from` de um rename
13
+ // logo após o respectivo caminho novo. `from` só entra quando o status contém `R` (rename),
14
+ // nunca para `C` (copy). Duplicatas são removidas.
15
+ export function commitPathsForSelection(selected: string[], changes: Change[]): string[] {
16
+ const result: string[] = []
17
+ const seen = new Set<string>()
18
+ const add = (path: string) => {
19
+ if (!safePath(path)) return
20
+ if (!seen.has(path)) {
21
+ seen.add(path)
22
+ result.push(path)
23
+ }
24
+ }
25
+ for (const path of selected) {
26
+ add(path)
27
+ const change = changes.find((c) => c.path === path && c.status.includes("R"))
28
+ if (change?.from) {
29
+ add(change.from)
30
+ }
31
+ }
32
+ return result
33
+ }
34
+
35
+ export async function planCommitSelected(
36
+ directory: string,
37
+ selected: string[],
38
+ signal?: AbortSignal,
39
+ ): Promise<CommitSelectionPlan> {
40
+ const root = await repoRoot(directory, signal)
41
+ const raw = await runRaw("git", ["status", "--porcelain", "-z"], directory, { signal })
42
+ const changes = parseStatus(raw)
43
+
44
+ const initialPaths = commitPathsForSelection(selected, changes)
45
+
46
+ // Os selecionados que aparecem como untracked (`??`) no status.
47
+ const untrackedPaths = new Set(changes.filter((c) => c.status === "??").map((c) => c.path))
48
+
49
+ const commitPaths: string[] = []
50
+ const seenCommit = new Set<string>()
51
+ // Paths mantidos como estão porque não há nada a commitar neles (ex.: diretório untracked vazio).
52
+ // Nunca recebem intent-to-add.
53
+ const keepAsIs = new Set<string>()
54
+ const addCommit = (path: string) => {
55
+ if (!seenCommit.has(path)) {
56
+ seenCommit.add(path)
57
+ commitPaths.push(path)
58
+ }
59
+ }
60
+ for (const path of initialPaths) addCommit(path)
61
+
62
+ // Expande diretórios untracked nos arquivos concretos que o git lista.
63
+ for (const path of initialPaths) {
64
+ if (!untrackedPaths.has(path)) continue
65
+ const listed = await runRaw(
66
+ "git",
67
+ ["ls-files", "--others", "--exclude-standard", "-z", "--", `:(literal)${path}`],
68
+ root,
69
+ { signal },
70
+ )
71
+ const files = listed.split("\0").filter(Boolean)
72
+ if (files.length === 0) {
73
+ // Diretório vazio: mantém o path original e não cria intent-to-add.
74
+ keepAsIs.add(path)
75
+ continue
76
+ }
77
+ const isDirectory = files.some((file) => file !== path)
78
+ if (isDirectory) {
79
+ const idx = commitPaths.indexOf(path)
80
+ if (idx !== -1) {
81
+ commitPaths.splice(idx, 1)
82
+ for (const file of files) addCommit(file)
83
+ }
84
+ }
85
+ // Senão é um arquivo untracked único: já está na lista de commit.
86
+ }
87
+
88
+ // intentPaths: arquivos da lista de commit sem entrada no index E presentes no working tree
89
+ // como untracked (--others). Arquivos já deletados/renomeados (não existem no working tree
90
+ // nem no index) não são candidatos a intent-to-add.
91
+ let indexedRaw = ""
92
+ let othersRaw = ""
93
+ if (commitPaths.length) {
94
+ const [indexedResult, othersResult] = await Promise.all([
95
+ runRaw("git", ["ls-files", "-z", "--", ...commitPaths.map((p) => `:(literal)${p}`)], root, { signal }),
96
+ runRaw(
97
+ "git",
98
+ ["ls-files", "--others", "--exclude-standard", "-z", "--", ...commitPaths.map((p) => `:(literal)${p}`)],
99
+ root,
100
+ { signal },
101
+ ),
102
+ ])
103
+ indexedRaw = indexedResult
104
+ othersRaw = othersResult
105
+ }
106
+ const indexed = new Set(indexedRaw.split("\0").filter(Boolean))
107
+ const others = new Set(othersRaw.split("\0").filter(Boolean))
108
+ const intentPaths = commitPaths.filter((p) => !indexed.has(p) && others.has(p) && !keepAsIs.has(p))
109
+
110
+ // Exclui paths de diretório vazio untracked: não há nada para commitar e
111
+ // `git commit --only -- <dir-vazio>` falharia. `keepAsIs` já cobre o caso
112
+ // detectado via `ls-files --others` vazio; este filtro cobre diretórios
113
+ // vazios que o `git status` não lista (não aparecem como `??`).
114
+ const finalCommitPaths: string[] = []
115
+ for (const p of commitPaths) {
116
+ if (keepAsIs.has(p)) continue
117
+ try {
118
+ const stat = await lstat(join(root, p))
119
+ if (stat.isDirectory()) {
120
+ const entries = await readdir(join(root, p))
121
+ if (entries.length === 0) continue
122
+ }
123
+ } catch {
124
+ // Se não dá para statar, mantém o path (deixa o commit reportar o erro).
125
+ }
126
+ finalCommitPaths.push(p)
127
+ }
128
+
129
+ return {
130
+ root,
131
+ commitPaths: finalCommitPaths.filter(safePath),
132
+ intentPaths: intentPaths.filter(safePath),
133
+ }
134
+ }
135
+
136
+ export async function commitSelectedPaths(
137
+ directory: string,
138
+ message: string,
139
+ files: string[],
140
+ signal?: AbortSignal,
141
+ ): Promise<{ ok: boolean; text: string }> {
142
+ const { root, commitPaths, intentPaths } = await planCommitSelected(directory, files, signal)
143
+ if (!commitPaths.length) {
144
+ return { ok: false, text: "Nenhum arquivo válido selecionado" }
145
+ }
146
+
147
+ const intentArgs = intentPaths.map((p) => `:(literal)${p}`)
148
+ const commitArgs = commitPaths.map((p) => `:(literal)${p}`)
149
+
150
+ try {
151
+ if (intentPaths.length) {
152
+ await run("git", ["add", "-N", "--", ...intentArgs], root, { signal })
153
+ }
154
+ const text = await run("git", ["commit", "--only", "-m", message, "--", ...commitArgs], root, {
155
+ signal,
156
+ })
157
+ return { ok: true, text: text || "commit criado" }
158
+ } catch (error) {
159
+ // Desfaz o intent-to-add criado quando o commit falha (ex.: hook rejeitado).
160
+ if (intentPaths.length) {
161
+ await run("git", ["reset", "-q", "--", ...intentArgs], root, { signal }).catch(() => {})
162
+ }
163
+ return { ok: false, text: errorMessage(error) }
164
+ }
165
+ }
@@ -0,0 +1,105 @@
1
+ import { execFile } from "node:child_process"
2
+ import { promisify } from "node:util"
3
+
4
+ const exec = promisify(execFile)
5
+
6
+ const MAX_BUFFER = 10 * 1024 * 1024
7
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
8
+
9
+ export type RunOptions = { signal?: AbortSignal; env?: NodeJS.ProcessEnv }
10
+
11
+ export function errorMessage(error: unknown): string {
12
+ return error instanceof Error ? error.message : String(error)
13
+ }
14
+
15
+ function execOptions(directory: string, options?: RunOptions) {
16
+ return {
17
+ cwd: directory,
18
+ maxBuffer: MAX_BUFFER,
19
+ signal: options?.signal,
20
+ env: { ...process.env, ...options?.env },
21
+ }
22
+ }
23
+
24
+ export async function run(
25
+ command: string,
26
+ args: string[],
27
+ directory: string,
28
+ options?: RunOptions,
29
+ ): Promise<string> {
30
+ const { stdout } = await exec(command, args, execOptions(directory, options))
31
+ return stdout.trim()
32
+ }
33
+
34
+ export async function runOptional(
35
+ command: string,
36
+ args: string[],
37
+ directory: string,
38
+ options?: RunOptions,
39
+ ): Promise<string> {
40
+ try {
41
+ return await run(command, args, directory, options)
42
+ } catch {
43
+ return ""
44
+ }
45
+ }
46
+
47
+ // Like `run`, but keeps stdout as git wrote it (no trim) and returns what was printed even when the command exits
48
+ // non-zero, as `git diff --no-index` does when the files differ.
49
+ export async function runRaw(
50
+ command: string,
51
+ args: string[],
52
+ directory: string,
53
+ options?: RunOptions,
54
+ ): Promise<string> {
55
+ try {
56
+ const { stdout } = await exec(command, args, execOptions(directory, options))
57
+ return stdout
58
+ } catch (error: any) {
59
+ return String(error?.stdout ?? "")
60
+ }
61
+ }
62
+
63
+ // Writes `input` to stdin and returns stdout exactly as the command wrote it (no trim).
64
+ export async function runInput(
65
+ command: string,
66
+ args: string[],
67
+ directory: string,
68
+ input: string,
69
+ options?: RunOptions,
70
+ ): Promise<string> {
71
+ return await new Promise((resolve, reject) => {
72
+ const child = execFile(command, args, execOptions(directory, options), (error, stdout) => {
73
+ if (error) reject(error)
74
+ else resolve(stdout)
75
+ })
76
+ child.stdin?.on("error", () => {})
77
+ child.stdin?.end(input)
78
+ })
79
+ }
80
+
81
+ // `git status --porcelain` paths are relative to the repository root, so path commands run from there.
82
+ export async function repoRoot(directory: string, signal?: AbortSignal): Promise<string> {
83
+ return (await runOptional("git", ["rev-parse", "--show-toplevel"], directory, { signal })) || directory
84
+ }
85
+
86
+ // What the working tree is compared against: HEAD, or the empty tree in a repository without commits.
87
+ export async function diffBase(root: string, signal?: AbortSignal): Promise<string> {
88
+ if (await runOptional("git", ["rev-parse", "--verify", "--quiet", "HEAD"], root, { signal })) return "HEAD"
89
+ return (await runOptional("git", ["hash-object", "-t", "tree", "/dev/null"], root, { signal })) || EMPTY_TREE
90
+ }
91
+
92
+ export function safeRef(name: string): boolean {
93
+ return /^[A-Za-z0-9._/-]+$/.test(name) && !name.startsWith("-") && !name.includes("..")
94
+ }
95
+
96
+ export function safePath(path: string): boolean {
97
+ return (
98
+ !!path &&
99
+ !path.startsWith("/") &&
100
+ !path.startsWith("-") &&
101
+ !path.includes("\n") &&
102
+ !path.includes("\r") &&
103
+ !path.split("/").includes("..")
104
+ )
105
+ }
@@ -0,0 +1,121 @@
1
+ export type Stat = { additions: number; deletions: number; binary: boolean }
2
+ export type Change = { status: string; path: string; from?: string } & Partial<Stat>
3
+ export type CommitRecord = {
4
+ hash: string
5
+ short: string
6
+ subject: string
7
+ author: string
8
+ date: string
9
+ parents: string[]
10
+ refs: string[]
11
+ }
12
+
13
+ // Parses `git status --porcelain -z`: `XY path\0`, with the original path as an extra field after a rename or copy.
14
+ export function parseStatus(raw: string): Change[] {
15
+ const fields = raw.split("\0")
16
+ const changes: Change[] = []
17
+ for (let index = 0; index < fields.length; index++) {
18
+ const field = fields[index]
19
+ if (field.length < 4) continue
20
+ const code = field.slice(0, 2)
21
+ const change: Change = { status: code.trim(), path: field.slice(3) }
22
+ if (code.includes("R") || code.includes("C")) {
23
+ const from = fields[++index]
24
+ if (from) change.from = from
25
+ }
26
+ changes.push(change)
27
+ }
28
+ return changes
29
+ }
30
+
31
+ // Parses `git diff --numstat -z`: `added\tdeleted\tpath\0`, or `added\tdeleted\t\0old\0new\0` for a rename.
32
+ export function parseNumstat(raw: string): Map<string, Stat> {
33
+ const stats = new Map<string, Stat>()
34
+ const fields = raw.split("\0")
35
+ for (let index = 0; index < fields.length; index++) {
36
+ const match = /^(-|\d+)\t(-|\d+)\t([\s\S]*)$/.exec(fields[index])
37
+ if (!match) continue
38
+ let path = match[3]
39
+ if (!path) {
40
+ index += 2
41
+ path = fields[index] ?? ""
42
+ }
43
+ if (!path) continue
44
+ const binary = match[1] === "-" || match[2] === "-"
45
+ stats.set(path, {
46
+ additions: binary ? 0 : Number(match[1]) || 0,
47
+ deletions: binary ? 0 : Number(match[2]) || 0,
48
+ binary,
49
+ })
50
+ }
51
+ return stats
52
+ }
53
+
54
+ // Parses the `%(upstream:track)` marker of `git for-each-ref` under `LC_ALL=C`, i.e. the
55
+ // `[ahead N, behind M]` decoration: missing/`gone` counts as zero.
56
+ export function parseTrack(raw: string): { ahead: number; behind: number } {
57
+ const ahead = /ahead (\d+)/.exec(raw)
58
+ const behind = /behind (\d+)/.exec(raw)
59
+ return {
60
+ ahead: ahead ? Number(ahead[1]) : 0,
61
+ behind: behind ? Number(behind[1]) : 0,
62
+ }
63
+ }
64
+
65
+ export function splitRecord(line: string): CommitRecord {
66
+ const parts = line.split("\x1f")
67
+ return {
68
+ hash: parts[0] ?? "",
69
+ short: parts[1] ?? "",
70
+ subject: parts[2] ?? "",
71
+ author: parts[3] ?? "",
72
+ date: parts[4] ?? "",
73
+ // `%P`: parent hashes separated by a space; `%D`: decorations separated by ", ".
74
+ parents: (parts[5] ?? "").split(" ").filter(Boolean),
75
+ refs: (parts[6] ?? "").split(", ").filter(Boolean),
76
+ }
77
+ }
78
+
79
+ export function parseCommitLog(raw: string): CommitRecord[] {
80
+ const commits: CommitRecord[] = []
81
+ for (const line of raw.split("\n")) {
82
+ if (!line) continue
83
+ const record = splitRecord(line)
84
+ if (!record.hash) continue
85
+ commits.push(record)
86
+ }
87
+ return commits
88
+ }
89
+
90
+ // Parses `git diff-tree --stdin -r -z --name-only --pretty=format:%H%x00`:
91
+ // `<hash>\0\n<path>\0<path>\0\0<hash>\0\n<path>\0...`
92
+ // Only the framing newline before the first path of a commit is dropped; newlines that belong to
93
+ // filenames are kept, empty path lists are omitted, and path fields are never read as hashes.
94
+ export function parseDiffTreeNames(raw: string): Map<string, string[]> {
95
+ const commits = new Map<string, string[]>()
96
+ if (!raw) return commits
97
+ const fields = raw.split("\0")
98
+ let index = 0
99
+ while (index < fields.length) {
100
+ const hash = fields[index]
101
+ if (!hash) {
102
+ index++
103
+ continue
104
+ }
105
+ index++
106
+ const paths: string[] = []
107
+ let first = true
108
+ while (index < fields.length && fields[index] !== "") {
109
+ let path = fields[index]
110
+ if (first) {
111
+ if (path.startsWith("\n")) path = path.slice(1)
112
+ first = false
113
+ }
114
+ paths.push(path)
115
+ index++
116
+ }
117
+ if (paths.length) commits.set(hash, paths)
118
+ while (index < fields.length && fields[index] === "") index++
119
+ }
120
+ return commits
121
+ }