@carlosstenzel/opencode-git-sidebar 0.1.2 → 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,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
+ }
@@ -0,0 +1,225 @@
1
+ import { lstat, readFile } from "node:fs/promises"
2
+ import { basename, join } from "node:path"
3
+ import { diffBase, repoRoot, runOptional, runRaw } from "./git-exec.js"
4
+ import {
5
+ parseCommitLog,
6
+ parseDiffTreeNames,
7
+ parseNumstat,
8
+ parseStatus,
9
+ parseTrack,
10
+ type Change,
11
+ type CommitRecord,
12
+ type Stat,
13
+ } from "./git-parse.js"
14
+
15
+ export type Status = {
16
+ repo: string
17
+ branch: string
18
+ dirty: boolean
19
+ changes: number
20
+ ahead: number
21
+ behind: number
22
+ upstream: string
23
+ }
24
+ export type Branch = {
25
+ name: string
26
+ current: boolean
27
+ upstream: string
28
+ ahead: number
29
+ behind: number
30
+ hash: string
31
+ subject: string
32
+ date: string
33
+ }
34
+ export type Commit = CommitRecord & { files: string[] }
35
+
36
+ const DIFF_ARGS = ["-c", "core.quotePath=false", "diff", "--no-color", "--no-ext-diff"]
37
+ const UNTRACKED_STAT_FILES = 400
38
+ const UNTRACKED_STAT_BYTES = 512 * 1024
39
+
40
+ function emptyStatus(): Status {
41
+ return { repo: "", branch: "", dirty: false, changes: 0, ahead: 0, behind: 0, upstream: "" }
42
+ }
43
+
44
+ export async function counts(upstream: string, ref: string, directory: string, signal?: AbortSignal) {
45
+ const raw = await runOptional(
46
+ "git",
47
+ ["rev-list", "--left-right", "--count", `${upstream}...${ref}`],
48
+ directory,
49
+ { signal },
50
+ )
51
+ const [behind, ahead] = raw.split(/\s+/).map((value) => Number(value) || 0)
52
+ return { ahead, behind }
53
+ }
54
+
55
+ // Lines an untracked file would add. Undefined when it is not a regular file or is too large to count cheaply.
56
+ async function untrackedStat(file: string): Promise<Stat | undefined> {
57
+ try {
58
+ const info = await lstat(file)
59
+ if (!info.isFile() || info.size > UNTRACKED_STAT_BYTES) return undefined
60
+ const bytes = await readFile(file)
61
+ if (bytes.subarray(0, 8000).includes(0)) return { additions: 0, deletions: 0, binary: true }
62
+ let lines = 0
63
+ for (const byte of bytes) if (byte === 10) lines++
64
+ if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) lines++
65
+ return { additions: lines, deletions: 0, binary: false }
66
+ } catch {
67
+ return undefined
68
+ }
69
+ }
70
+
71
+ // Stats of the untracked entries of `git status`: a file, or a directory git lists as one entry (`dir/`).
72
+ async function untrackedStats(entries: Change[], root: string, signal?: AbortSignal) {
73
+ const stats = new Map<string, Stat>()
74
+ if (!entries.length) return stats
75
+ const raw = await runRaw("git", ["ls-files", "--others", "--exclude-standard", "-z"], root, { signal })
76
+ const files = raw.split("\0").filter(Boolean)
77
+ if (files.length > UNTRACKED_STAT_FILES) return stats
78
+ const counted = new Map<string, Stat | undefined>()
79
+ for (let start = 0; start < files.length; start += 16) {
80
+ const batch = files.slice(start, start + 16)
81
+ const results = await Promise.all(batch.map((file) => untrackedStat(join(root, file))))
82
+ batch.forEach((file, index) => counted.set(file, results[index]))
83
+ }
84
+ for (const entry of entries) {
85
+ const inside = entry.path.endsWith("/") ? files.filter((file) => file.startsWith(entry.path)) : [entry.path]
86
+ const parts = inside.map((file) => counted.get(file))
87
+ if (!parts.length || parts.some((part) => !part)) continue
88
+ const known = parts as Stat[]
89
+ stats.set(entry.path, {
90
+ additions: known.reduce((sum, part) => sum + part.additions, 0),
91
+ deletions: 0,
92
+ binary: known.every((part) => part.binary),
93
+ })
94
+ }
95
+ return stats
96
+ }
97
+
98
+ export async function readStatus(directory: string, signal?: AbortSignal): Promise<Status> {
99
+ const inside = await runOptional("git", ["rev-parse", "--is-inside-work-tree"], directory, { signal })
100
+ if (inside !== "true") return emptyStatus()
101
+
102
+ const root = await runOptional("git", ["rev-parse", "--show-toplevel"], directory, { signal })
103
+ const branch =
104
+ (await runOptional("git", ["symbolic-ref", "--short", "-q", "HEAD"], directory, { signal })) ||
105
+ "(desanexado)"
106
+ const porcelain = await runOptional("git", ["status", "--porcelain"], directory, { signal })
107
+ const changes = porcelain ? porcelain.split("\n").filter(Boolean).length : 0
108
+ const upstream = await runOptional(
109
+ "git",
110
+ ["rev-parse", "--abbrev-ref", "@{upstream}"],
111
+ directory,
112
+ { signal },
113
+ )
114
+ const { ahead, behind } = upstream
115
+ ? await counts(upstream, "HEAD", directory, signal)
116
+ : { ahead: 0, behind: 0 }
117
+ return {
118
+ repo: root ? basename(root) : basename(directory),
119
+ branch,
120
+ dirty: changes > 0,
121
+ changes,
122
+ ahead,
123
+ behind,
124
+ upstream,
125
+ }
126
+ }
127
+
128
+ export async function readChanges(directory: string, signal?: AbortSignal): Promise<Change[]> {
129
+ // `-z` keeps paths as they are (no quoting) and `runRaw` keeps the leading space of an unstaged ` M` entry.
130
+ const raw = await runRaw("git", ["status", "--porcelain", "-z"], directory, { signal })
131
+ const changes = parseStatus(raw)
132
+ if (!changes.length) return changes
133
+ const root = await repoRoot(directory, signal)
134
+ const base = await diffBase(root, signal)
135
+ const [tracked, untracked] = await Promise.all([
136
+ runRaw("git", [...DIFF_ARGS, "--numstat", "-z", "-M", base, "--"], root, { signal }).then(parseNumstat),
137
+ untrackedStats(
138
+ changes.filter((change) => change.status === "??"),
139
+ root,
140
+ signal,
141
+ ),
142
+ ])
143
+ return changes.map((change): Change => ({
144
+ ...change,
145
+ ...(change.status === "??" ? untracked.get(change.path) : tracked.get(change.path)),
146
+ }))
147
+ }
148
+
149
+ export async function readBranches(directory: string, limit?: number, signal?: AbortSignal): Promise<Branch[]> {
150
+ const current = await runOptional("git", ["rev-parse", "--abbrev-ref", "HEAD"], directory, { signal })
151
+ const format =
152
+ "%(refname:short)\t%(objectname:short)\t%(upstream:short)\t%(contents:subject)\t%(committerdate:iso-strict)\t%(upstream:track)"
153
+ const local = await runRaw(
154
+ "git",
155
+ ["for-each-ref", `--format=${format}`, "refs/heads"],
156
+ directory,
157
+ { signal, env: { LC_ALL: "C" } },
158
+ )
159
+ const remote = await runRaw(
160
+ "git",
161
+ ["for-each-ref", `--format=${format}`, "refs/remotes"],
162
+ directory,
163
+ { signal, env: { LC_ALL: "C" } },
164
+ )
165
+ const lines = [local, remote].filter(Boolean).join("\n").split("\n").filter(Boolean)
166
+ const result: Branch[] = []
167
+ for (const line of lines) {
168
+ const [name, hash, upstream, subject, date, track] = line.split("\t")
169
+ if (!name || name.endsWith("/HEAD")) continue
170
+ const { ahead, behind } = parseTrack(track ?? "")
171
+ result.push({
172
+ name,
173
+ current: name === current,
174
+ upstream: upstream || "",
175
+ ahead,
176
+ behind,
177
+ hash: hash || "",
178
+ subject: subject || "",
179
+ date: date || "",
180
+ })
181
+ if (result.length >= (limit || 60)) break
182
+ }
183
+ return result
184
+ }
185
+
186
+ export async function readCommits(
187
+ directory: string,
188
+ limit?: number,
189
+ signal?: AbortSignal,
190
+ all = false,
191
+ ): Promise<Commit[]> {
192
+ const maxCount = `--max-count=${limit || 20}`
193
+ // Topologia de branches: `--all` também arrastaria `refs/stash` e `refs/notes`.
194
+ const allArgs = all ? ["--branches", "--remotes", "--tags"] : []
195
+ const raw = await runOptional(
196
+ "git",
197
+ [
198
+ "log",
199
+ ...allArgs,
200
+ maxCount,
201
+ // Parents must never be listed before their children, whatever the
202
+ // committer dates say; the lane layout relies on that order.
203
+ "--topo-order",
204
+ "--date=iso-strict",
205
+ // `--decorate=short` vence `log.decorate` do usuário (não neutraliza `log.excludeDecoration`).
206
+ "--decorate=short",
207
+ "--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%ad%x1f%P%x1f%D",
208
+ ],
209
+ directory,
210
+ { signal },
211
+ )
212
+ const commits = parseCommitLog(raw)
213
+ if (!commits.length) return []
214
+ const filesRaw = await runOptional(
215
+ "git",
216
+ ["log", ...allArgs, maxCount, "--topo-order", "--name-only", "-z", "--pretty=format:%H%x00"],
217
+ directory,
218
+ { signal },
219
+ )
220
+ const filesByCommit = parseDiffTreeNames(filesRaw)
221
+ return commits.map((commit) => ({
222
+ ...commit,
223
+ files: filesByCommit.get(commit.hash) ?? [],
224
+ }))
225
+ }
@@ -0,0 +1,174 @@
1
+ import { createEffect, createMemo, createSignal, For, onCleanup, onMount, type JSX } from "solid-js"
2
+ import { buildEdges, FALLBACK_ROW_HEIGHT, type GraphCommit, type GraphRow } from "./graph.js"
3
+ import { laneColor, laneWidth, laneX } from "./graph-theme.js"
4
+
5
+ const NODE_RADIUS = 3.5
6
+ const STROKE = 2
7
+
8
+ type Measurement = {
9
+ centers: number[]
10
+ height: number
11
+ }
12
+
13
+ function sameCenters(a: number[], b: number[]): boolean {
14
+ return a.length === b.length && a.every((value, index) => Math.abs(value - b[index]) < 0.5)
15
+ }
16
+
17
+ /**
18
+ * Draws the whole graph as one SVG layered over the commit list.
19
+ *
20
+ * Dots sit on the measured centre of each `[data-graph-row]`, and every edge
21
+ * links a commit's dot to its parent's dot, so lanes are continuous curves
22
+ * instead of per-row rails. The SVG is absolutely positioned and ignores pointer
23
+ * events: measuring it can never change a row's height, which would otherwise
24
+ * feed the ResizeObserver back into a layout loop.
25
+ *
26
+ * Rows are re-measured on mount, whenever the row/commit list changes, on row
27
+ * or container resize, and on DOM mutations such as expanding a commit's files.
28
+ * The measured signal only updates when a centre actually moved, so the loop
29
+ * settles after one pass.
30
+ */
31
+ export function GraphCanvas(props: {
32
+ rows: () => GraphRow[]
33
+ commits: () => GraphCommit[]
34
+ lanes: () => number
35
+ target: () => HTMLElement | undefined
36
+ }): JSX.Element {
37
+ const width = () => laneWidth(props.lanes())
38
+ const fallback = (): Measurement => {
39
+ const count = props.rows().length
40
+ return {
41
+ centers: props.rows().map((_, index) => index * FALLBACK_ROW_HEIGHT + FALLBACK_ROW_HEIGHT / 2),
42
+ height: Math.max(count * FALLBACK_ROW_HEIGHT, FALLBACK_ROW_HEIGHT),
43
+ }
44
+ }
45
+ const [measurement, setMeasurement] = createSignal<Measurement>(fallback())
46
+ const edgeList = createMemo(() =>
47
+ buildEdges(props.rows(), props.commits(), measurement().centers, measurement().height),
48
+ )
49
+
50
+ let canvas: HTMLDivElement | undefined
51
+ let resize: ResizeObserver | undefined
52
+ let mutations: MutationObserver | undefined
53
+ let watched: HTMLElement[] = []
54
+
55
+ const centerAt = (index: number) =>
56
+ measurement().centers[index] ?? index * FALLBACK_ROW_HEIGHT + FALLBACK_ROW_HEIGHT / 2
57
+
58
+ const rowElements = (): HTMLElement[] => {
59
+ const target = props.target()
60
+ if (!target) return []
61
+ return Array.from(target.querySelectorAll<HTMLElement>("[data-graph-row]"))
62
+ }
63
+
64
+ const watch = (elements: HTMLElement[]) => {
65
+ if (!resize) return
66
+ if (watched.length === elements.length && watched.every((el, index) => el === elements[index])) return
67
+ for (const element of watched) resize.unobserve(element)
68
+ for (const element of elements) resize.observe(element)
69
+ watched = elements
70
+ }
71
+
72
+ const measure = () => {
73
+ // Without ResizeObserver (tests, exotic hosts) keep the synthetic 42px rows.
74
+ if (typeof ResizeObserver === "undefined") return
75
+ const elements = rowElements()
76
+ if (elements.length === 0) return
77
+
78
+ const centers = elements.map((element) => element.offsetTop + element.offsetHeight / 2)
79
+ const last = elements[elements.length - 1]
80
+ const height = last.offsetTop + last.offsetHeight
81
+ const current = measurement()
82
+ if (!sameCenters(current.centers, centers) || Math.abs(current.height - height) >= 0.5) {
83
+ setMeasurement({ centers, height })
84
+ }
85
+ watch(elements)
86
+ }
87
+
88
+ onMount(() => {
89
+ if (typeof ResizeObserver === "undefined") return
90
+ resize = new ResizeObserver(measure)
91
+ const target = props.target()
92
+ if (target) resize.observe(target)
93
+ measure()
94
+
95
+ // Expanding a commit inserts its file list as a sibling, which moves every
96
+ // row below without resizing any of them: only a mutation reveals it.
97
+ if (typeof MutationObserver !== "undefined" && target) {
98
+ mutations = new MutationObserver((records) => {
99
+ if (canvas && records.every((record) => canvas!.contains(record.target))) return
100
+ measure()
101
+ })
102
+ mutations.observe(target, { childList: true, subtree: true })
103
+ }
104
+ })
105
+
106
+ createEffect(() => {
107
+ // Track the list so new rows are measured once Solid has written the DOM.
108
+ props.rows()
109
+ props.commits()
110
+ props.lanes()
111
+ measure()
112
+ })
113
+
114
+ onCleanup(() => {
115
+ resize?.disconnect()
116
+ mutations?.disconnect()
117
+ watched = []
118
+ })
119
+
120
+ return (
121
+ <div
122
+ class="gs-graph"
123
+ ref={(element) => (canvas = element)}
124
+ style={{ width: `${width()}px`, height: `${measurement().height}px` }}
125
+ >
126
+ <svg
127
+ width={width()}
128
+ height={measurement().height}
129
+ viewBox={`0 0 ${width()} ${measurement().height}`}
130
+ aria-hidden="true"
131
+ fill="none"
132
+ stroke-linecap="round"
133
+ stroke-linejoin="round"
134
+ >
135
+ <defs>
136
+ <For each={edgeList()}>
137
+ {(edge) => (
138
+ <linearGradient
139
+ id={`gs-edge-${edge.hash}-${edge.parentLane}`}
140
+ gradientUnits="userSpaceOnUse"
141
+ x1={edge.from.x}
142
+ y1={edge.from.y}
143
+ x2={edge.to.x}
144
+ y2={edge.to.y}
145
+ >
146
+ <stop offset="0%" stop-color={laneColor(edge.lane)} />
147
+ <stop offset="100%" stop-color={laneColor(edge.parentLane)} />
148
+ </linearGradient>
149
+ )}
150
+ </For>
151
+ </defs>
152
+ <For each={edgeList()}>
153
+ {(edge) => (
154
+ <path
155
+ d={edge.d}
156
+ stroke={`url(#gs-edge-${edge.hash}-${edge.parentLane})`}
157
+ stroke-width={STROKE}
158
+ />
159
+ )}
160
+ </For>
161
+ <For each={props.rows()}>
162
+ {(row, index) => (
163
+ <circle
164
+ cx={laneX(row.lane)}
165
+ cy={centerAt(index())}
166
+ r={NODE_RADIUS}
167
+ fill={laneColor(row.lane)}
168
+ />
169
+ )}
170
+ </For>
171
+ </svg>
172
+ </div>
173
+ )
174
+ }
@@ -0,0 +1,27 @@
1
+ // One hue per lane so crossing lines stay readable; each falls back to a colour
2
+ // that works on light and dark panels, and a theme can override the variables.
3
+ // Shared by the legacy per-row gutter and the single graph canvas so both draw
4
+ // the same palette.
5
+ export const LANE_COLORS = [
6
+ "var(--gs-lane-0, #2563eb)",
7
+ "var(--gs-lane-1, #0d9488)",
8
+ "var(--gs-lane-2, #8b5cf6)",
9
+ "var(--gs-lane-3, #c2410c)",
10
+ "var(--gs-lane-4, #db2777)",
11
+ ]
12
+
13
+ export const MAX_LANES = 5
14
+ export const PITCH = 10
15
+
16
+ export function laneX(lane: number, pitch: number = PITCH): number {
17
+ return Math.min(lane, MAX_LANES - 1) * pitch + pitch / 2
18
+ }
19
+
20
+ export function laneColor(lane: number): string {
21
+ return LANE_COLORS[lane % LANE_COLORS.length]
22
+ }
23
+
24
+ /** Width reserved for the graph column, capped so a wild row cannot push the text away. */
25
+ export function laneWidth(lanes: number): number {
26
+ return Math.min(lanes, MAX_LANES) * PITCH
27
+ }