ostia 0.2.12 → 0.3.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.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -358
  3. package/docs/agent-protocol.md +210 -0
  4. package/docs/cli.md +1196 -0
  5. package/docs/config.md +233 -0
  6. package/docs/document-schema.md +224 -0
  7. package/docs/library.md +421 -0
  8. package/docs/preload-recipes.md +169 -0
  9. package/docs/statistics.md +218 -0
  10. package/index.d.ts +894 -677
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +474 -0
  13. package/src/ab/index.ts +1086 -0
  14. package/src/baseline/index.ts +75 -0
  15. package/src/bench/index.ts +462 -0
  16. package/src/bench/projects.ts +39 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +424 -0
  19. package/src/bench/run-tasks.ts +176 -0
  20. package/src/bench/run.ts +51 -0
  21. package/src/bench/runner.ts +147 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +39 -0
  24. package/src/cache/fingerprint.ts +59 -0
  25. package/src/cache/store.ts +28 -0
  26. package/src/capture/bunflags.ts +91 -0
  27. package/src/capture/cpu-parse.ts +119 -0
  28. package/src/capture/cpu.ts +44 -0
  29. package/src/capture/frames.ts +54 -0
  30. package/src/capture/heap-parse.ts +86 -0
  31. package/src/capture/heap.ts +32 -0
  32. package/src/capture/inspector.ts +46 -0
  33. package/src/capture/jsc-parse.ts +167 -0
  34. package/src/capture/jsc.ts +35 -0
  35. package/src/capture/sampling.ts +5 -0
  36. package/src/ci/index.ts +416 -0
  37. package/src/cli/flags.ts +264 -0
  38. package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +185 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +617 -0
  43. package/src/config/index.ts +275 -0
  44. package/src/config/validate.ts +267 -0
  45. package/src/errors.ts +8 -0
  46. package/src/format.ts +36 -0
  47. package/src/glob.ts +48 -0
  48. package/src/index.ts +62 -0
  49. package/src/ir/cpu.ts +10 -0
  50. package/src/ir/document.ts +471 -0
  51. package/src/ir/fp.ts +31 -0
  52. package/src/ir/git.ts +36 -0
  53. package/src/ir/types.ts +615 -0
  54. package/src/measure/alloc.ts +57 -0
  55. package/src/measure/cpu.ts +99 -0
  56. package/src/measure/environment.ts +41 -0
  57. package/src/measure/inprocess.ts +191 -0
  58. package/src/measure/instructions.ts +133 -0
  59. package/src/measure/loop.ts +57 -0
  60. package/src/measure/noise.ts +55 -0
  61. package/src/measure/paired.ts +312 -0
  62. package/src/measure/peak.ts +202 -0
  63. package/src/measure/timing.ts +263 -0
  64. package/src/profile.ts +109 -0
  65. package/src/renderers/collapsed.ts +35 -0
  66. package/src/renderers/cpu-tree.ts +183 -0
  67. package/src/renderers/cpuprofile.ts +43 -0
  68. package/src/renderers/format.ts +142 -0
  69. package/src/renderers/index.ts +27 -0
  70. package/src/renderers/json.ts +10 -0
  71. package/src/renderers/jsonl.ts +15 -0
  72. package/src/renderers/markdown.ts +525 -0
  73. package/src/renderers/mermaid.ts +78 -0
  74. package/src/renderers/minimal.ts +602 -0
  75. package/src/renderers/paired.ts +229 -0
  76. package/src/renderers/relative.ts +64 -0
  77. package/src/renderers/select.ts +286 -0
  78. package/src/renderers/speedscope.ts +69 -0
  79. package/src/renderers/terminal.ts +466 -0
  80. package/src/renderers/types.ts +27 -0
  81. package/src/spawn/index.ts +396 -0
  82. package/src/stats/bootstrap.ts +153 -0
  83. package/src/stats/index.ts +140 -0
  84. package/src/stats/mannwhitney.ts +81 -0
  85. package/src/time.ts +325 -0
  86. package/src/version.ts +3 -0
  87. package/ab-runner.ts +0 -8
  88. package/chunk-05jfst35.js +0 -28
  89. package/chunk-1g1x9zz2.js +0 -15
  90. package/chunk-23g2rwrn.js +0 -3
  91. package/chunk-468h5412.js +0 -25
  92. package/chunk-4esjfc2m.js +0 -2
  93. package/chunk-ct2xsezd.js +0 -14
  94. package/cli.js +0 -3
  95. package/index.js +0 -2
  96. package/runner.ts +0 -7
package/src/ir/cpu.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { CpuEvidence } from "./types.ts";
2
+
3
+ /** The sample stream's length when the capture kept one, else the summed
4
+ * per-frame self counts. */
5
+ export function cpuSampleCount(cpu: CpuEvidence): number {
6
+ return (
7
+ cpu.samples?.nodeIds.length ??
8
+ cpu.totals.reduce((sum, t) => sum + t.samples, 0)
9
+ );
10
+ }
@@ -0,0 +1,471 @@
1
+ import { rename, rm } from "node:fs/promises";
2
+ import { isAbsolute, relative } from "node:path";
3
+
4
+ import { errorMessage } from "../errors.ts";
5
+ import {
6
+ assertReusableTimeSource,
7
+ prepareArgv,
8
+ type PrepareHook,
9
+ type TimeSource,
10
+ timeSourceSpec,
11
+ } from "../spawn/index.ts";
12
+ import { computeTimingStats } from "../stats/index.ts";
13
+ import { TOOL_VERSION } from "../version.ts";
14
+ import { canonicalJSON, fp } from "./fp.ts";
15
+ import { captureGitMetadata } from "./git.ts";
16
+ import type {
17
+ ArtifactRef,
18
+ CpuEvidence,
19
+ Environment,
20
+ HeapEvidence,
21
+ InstructionStats,
22
+ JitTierBreakdown,
23
+ Measurement,
24
+ MemoryEvidence,
25
+ PairedEvidence,
26
+ Phase,
27
+ ProfileDocument,
28
+ TimingStats,
29
+ Trial,
30
+ Warning,
31
+ Workload,
32
+ } from "./types.ts";
33
+
34
+ function definedFields<T extends object>(fields: T): Partial<T> {
35
+ return Object.fromEntries(
36
+ Object.entries(fields).filter(([, v]) => v !== undefined),
37
+ ) as Partial<T>;
38
+ }
39
+
40
+ function measurementId(
41
+ workloadId: string,
42
+ phase: Phase,
43
+ configFingerprint: string,
44
+ ): string {
45
+ return fp(
46
+ "run",
47
+ workloadId,
48
+ phase,
49
+ configFingerprint,
50
+ Bun.version,
51
+ TOOL_VERSION,
52
+ );
53
+ }
54
+
55
+ export function createDocument(
56
+ workloads: Workload[],
57
+ measurements: Measurement[],
58
+ environment?: Environment,
59
+ ): ProfileDocument {
60
+ const git = captureGitMetadata();
61
+ return {
62
+ schemaVersion: 2,
63
+ toolVersion: TOOL_VERSION,
64
+ bunVersion: Bun.version,
65
+ platform: { os: process.platform, arch: process.arch },
66
+ createdAt: new Date().toISOString(),
67
+ workloads,
68
+ measurements,
69
+ ...definedFields({ environment, git }),
70
+ };
71
+ }
72
+
73
+ export interface SubprocessWorkloadOptions {
74
+ prepare?: PrepareHook;
75
+ timeSource?: TimeSource;
76
+ }
77
+
78
+ /**
79
+ * `prepare` and `timeSource` join the id only when given, so commands
80
+ * without them keep their old id. A function `prepare` hashes by source
81
+ * text. The id excludes `process.cwd()` so baselines match across
82
+ * checkouts. */
83
+ export function makeSubprocessWorkload(
84
+ command: string[],
85
+ label?: string,
86
+ opts: SubprocessWorkloadOptions = {},
87
+ ): Workload {
88
+ if (opts.timeSource) assertReusableTimeSource(opts.timeSource);
89
+ const prepare = prepareArgv(opts.prepare);
90
+ const timeSource = timeSourceSpec(opts.timeSource);
91
+ const prepareKey =
92
+ typeof opts.prepare === "function" ? opts.prepare.toString() : prepare;
93
+ const id = fp(
94
+ "wl",
95
+ "subprocess",
96
+ command,
97
+ ...(prepareKey !== undefined || timeSource !== undefined
98
+ ? [prepareKey ?? null, timeSource ?? null]
99
+ : []),
100
+ );
101
+ return {
102
+ id,
103
+ kind: "subprocess",
104
+ command,
105
+ label,
106
+ ...definedFields({ prepare, timeSource }),
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Without `name` the id hashes the function's name and source, not the
112
+ * values it closes over; `name` replaces both and is the label. */
113
+ export function makeInprocessWorkload(
114
+ fn: (...args: unknown[]) => unknown,
115
+ name?: string,
116
+ ): Workload {
117
+ const id =
118
+ name === undefined
119
+ ? fp("wl", "inprocess", fn.name, fn.toString())
120
+ : fp("wl", "inprocess-named", name);
121
+ return { id, kind: "inprocess", label: name };
122
+ }
123
+
124
+ export interface EntryWorkloadOptions {
125
+ label?: string;
126
+ baseline?: boolean;
127
+ group?: string;
128
+ description?: string;
129
+ groupDescription?: string;
130
+ isolated?: boolean;
131
+ params?: Record<string, string | number | boolean>;
132
+ formerIds?: string[];
133
+ skipped?: boolean;
134
+ }
135
+
136
+ /**
137
+ * The id hashes the file (cwd-relative, so checkouts match), `taskName`
138
+ * (the registry's "group/name") and `params` when present; `params` joins
139
+ * only when given so tasks without it keep their old id, and a `sweep()`
140
+ * reuses one task name across points. Everything else is annotation and
141
+ * never orphans a baseline. */
142
+ export function makeEntryWorkload(
143
+ file: string,
144
+ taskName: string,
145
+ opts: EntryWorkloadOptions = {},
146
+ ): Workload {
147
+ const idPath = isAbsolute(file) ? relative(process.cwd(), file) : file;
148
+ const id =
149
+ opts.params !== undefined
150
+ ? fp("wl", "inprocess-entry", idPath, taskName, opts.params)
151
+ : fp("wl", "inprocess-entry", idPath, taskName);
152
+ const { group, ...annotations } = opts;
153
+ return {
154
+ id,
155
+ kind: "inprocess",
156
+ entry: { file, task: taskName, ...definedFields({ group }) },
157
+ ...definedFields(annotations),
158
+ };
159
+ }
160
+
161
+ export interface TimingMeasurementInput {
162
+ workload: Workload;
163
+ configFingerprint: string;
164
+ trials: Trial[];
165
+ /**
166
+ * Absent when no trial produced a sample (all timed out or missed the
167
+ * `timeSource` pattern); renderers then skip the measurement. */
168
+ timing?: TimingStats;
169
+ warnings: Warning[];
170
+ interleaved?: boolean;
171
+ /** In-process heap readings around the run; see `MemoryEvidence`. */
172
+ heapUsed?: { beforeBytes: number; afterBytes: number };
173
+ instructions?: InstructionStats;
174
+ }
175
+
176
+ export function makeTimingMeasurement(
177
+ input: TimingMeasurementInput,
178
+ ): Measurement {
179
+ return {
180
+ id: measurementId(input.workload.id, "timing", input.configFingerprint),
181
+ workloadId: input.workload.id,
182
+ phase: "timing",
183
+ instrumented: false,
184
+ configFingerprint: input.configFingerprint,
185
+ trials: input.trials,
186
+ timing: input.timing,
187
+ warnings: input.warnings,
188
+ artifacts: [],
189
+ memory: input.heapUsed
190
+ ? {
191
+ origin: "heapStats",
192
+ heapUsedBeforeBytes: input.heapUsed.beforeBytes,
193
+ heapUsedAfterBytes: input.heapUsed.afterBytes,
194
+ }
195
+ : memoryFromTrials(input.trials),
196
+ ...definedFields({
197
+ instructions: input.instructions,
198
+ interleaved: input.interleaved,
199
+ }),
200
+ };
201
+ }
202
+
203
+ function memoryFromTrials(trials: Trial[]): MemoryEvidence | undefined {
204
+ const rss = trials
205
+ .map((t) => t.maxRssBytes)
206
+ .filter((v): v is number => v !== undefined);
207
+ if (rss.length === 0) return undefined;
208
+ return {
209
+ origin: "resourceUsage",
210
+ maxRssBytes: Math.max(...rss),
211
+ };
212
+ }
213
+
214
+ export interface InstrumentedMeasurementInput {
215
+ workload: Workload;
216
+ phase: Extract<Phase, "cpu" | "heap" | "memstats">;
217
+ configFingerprint: string;
218
+ diagnosticWallNs: number;
219
+ exitCode?: number;
220
+ cpu?: CpuEvidence;
221
+ heap?: HeapEvidence;
222
+ memory?: MemoryEvidence;
223
+ jit?: JitTierBreakdown;
224
+ warnings: Warning[];
225
+ artifacts: ArtifactRef[];
226
+ }
227
+
228
+ export function makeInstrumentedMeasurement(
229
+ input: InstrumentedMeasurementInput,
230
+ ): Measurement {
231
+ return {
232
+ id: measurementId(input.workload.id, input.phase, input.configFingerprint),
233
+ workloadId: input.workload.id,
234
+ phase: input.phase,
235
+ instrumented: true,
236
+ configFingerprint: input.configFingerprint,
237
+ trials: [
238
+ { i: 0, wallNs: input.diagnosticWallNs, exitCode: input.exitCode },
239
+ ],
240
+ diagnosticWallNs: input.diagnosticWallNs,
241
+ cpu: input.cpu,
242
+ heap: input.heap,
243
+ memory: input.memory,
244
+ jit: input.jit,
245
+ warnings: input.warnings,
246
+ artifacts: input.artifacts,
247
+ };
248
+ }
249
+
250
+ export type PairedMeasurementInput = {
251
+ workload: Workload;
252
+ configFingerprint: string;
253
+ diagnosticWallNs: number;
254
+ warnings: Warning[];
255
+ } & (
256
+ | {
257
+ /** The candidate side's per-call timing over the rounds. */
258
+ timing: TimingStats;
259
+ paired: PairedEvidence;
260
+ }
261
+ | {
262
+ /** A task that threw, so wasn't timed. */
263
+ threw: NonNullable<Measurement["threw"]>;
264
+ }
265
+ );
266
+
267
+ /**
268
+ * `timing` is the candidate side; `paired` holds the base side and the
269
+ * ratios.
270
+ */
271
+ export function makePairedMeasurement(
272
+ input: PairedMeasurementInput,
273
+ ): Measurement {
274
+ return {
275
+ id: measurementId(input.workload.id, "paired", input.configFingerprint),
276
+ workloadId: input.workload.id,
277
+ phase: "paired",
278
+ instrumented: false,
279
+ configFingerprint: input.configFingerprint,
280
+ trials: [],
281
+ ...("threw" in input
282
+ ? { threw: input.threw }
283
+ : { timing: input.timing, paired: input.paired }),
284
+ diagnosticWallNs: input.diagnosticWallNs,
285
+ warnings: input.warnings,
286
+ artifacts: [],
287
+ };
288
+ }
289
+
290
+ export async function makeArtifactRef(
291
+ ownerId: string,
292
+ kind: ArtifactRef["kind"],
293
+ path: string,
294
+ ): Promise<ArtifactRef> {
295
+ const buf = await Bun.file(path).arrayBuffer();
296
+ return {
297
+ id: fp("art", ownerId, kind, path),
298
+ kind,
299
+ path,
300
+ sha256: Bun.CryptoHasher.hash("sha256", buf, "hex"),
301
+ bytes: buf.byteLength,
302
+ };
303
+ }
304
+
305
+ export function configFingerprint(opts: Record<string, unknown>): string {
306
+ return fp("cfg", opts);
307
+ }
308
+
309
+ export function serializeDocument(doc: ProfileDocument): string {
310
+ return `${canonicalJSON(doc, 2)}\n`;
311
+ }
312
+
313
+ /**
314
+ * Writes to a unique temp file then renames, so a killed process never
315
+ * leaves a truncated document at `path` and concurrent saves of one path
316
+ * don't share a temp file. Takes serialized text so a caller that already
317
+ * has it can skip `serializeDocument`. */
318
+ export async function saveDocumentText(
319
+ text: string,
320
+ path: string,
321
+ ): Promise<void> {
322
+ const tmpPath = `${path}.tmp-${process.pid}-${crypto.randomUUID().slice(0, 8)}`;
323
+ try {
324
+ await Bun.write(tmpPath, text);
325
+ await rename(tmpPath, path);
326
+ } catch (err) {
327
+ await rm(tmpPath, { force: true });
328
+ throw err;
329
+ }
330
+ }
331
+
332
+ export async function saveDocument(
333
+ doc: ProfileDocument,
334
+ path: string,
335
+ ): Promise<void> {
336
+ await saveDocumentText(serializeDocument(doc), path);
337
+ }
338
+
339
+ export class OstiaDocumentError extends Error {
340
+ readonly code: "invalid-json" | "not-a-document" | "unsupported-schema";
341
+ readonly path?: string;
342
+ readonly schemaVersion?: unknown;
343
+
344
+ constructor(
345
+ code: OstiaDocumentError["code"],
346
+ message: string,
347
+ opts: { path?: string; schemaVersion?: unknown } = {},
348
+ ) {
349
+ super(message);
350
+ this.name = "OstiaDocumentError";
351
+ this.code = code;
352
+ this.path = opts.path;
353
+ this.schemaVersion = opts.schemaVersion;
354
+ }
355
+ }
356
+
357
+ export async function loadDocument(path: string): Promise<ProfileDocument> {
358
+ const text = await Bun.file(path).text();
359
+ let raw: unknown;
360
+ try {
361
+ raw = JSON.parse(text);
362
+ } catch (err) {
363
+ const cause = errorMessage(err);
364
+ throw new OstiaDocumentError(
365
+ "invalid-json",
366
+ `${path}: invalid JSON (${cause})`,
367
+ { path },
368
+ );
369
+ }
370
+ const schemaVersion =
371
+ raw !== null && typeof raw === "object"
372
+ ? (raw as { schemaVersion?: unknown }).schemaVersion
373
+ : undefined;
374
+ if (typeof schemaVersion !== "number") {
375
+ throw new OstiaDocumentError(
376
+ "not-a-document",
377
+ `${path}: not a ProfileDocument (missing schemaVersion)`,
378
+ { path },
379
+ );
380
+ }
381
+ if (schemaVersion !== 2) {
382
+ throw new OstiaDocumentError(
383
+ "unsupported-schema",
384
+ `${path}: unsupported ProfileDocument schemaVersion ${schemaVersion} (this ostia reads 2)`,
385
+ { path, schemaVersion },
386
+ );
387
+ }
388
+ assertDocumentShape(raw as Record<string, unknown>, path);
389
+ return renamePairedRatioFields(backfillTimingStats(raw as ProfileDocument));
390
+ }
391
+
392
+ const isObject = (v: unknown): v is Record<string, unknown> =>
393
+ typeof v === "object" && v !== null && !Array.isArray(v);
394
+
395
+ /**
396
+ * Cheap structural check, so a hand-edited or truncated document fails
397
+ * here with a path and index instead of a TypeError deep in a renderer. */
398
+ function assertDocumentShape(doc: Record<string, unknown>, path: string): void {
399
+ const bad = (what: string) =>
400
+ new OstiaDocumentError(
401
+ "not-a-document",
402
+ `${path}: malformed document: ${what}`,
403
+ {
404
+ path,
405
+ },
406
+ );
407
+ if (!Array.isArray(doc.workloads)) throw bad(`"workloads" must be an array`);
408
+ if (!Array.isArray(doc.measurements)) {
409
+ throw bad(`"measurements" must be an array`);
410
+ }
411
+ doc.workloads.forEach((w, i) => {
412
+ if (!isObject(w) || typeof w.id !== "string") {
413
+ throw bad(`workloads[${i}] must be an object with a string "id"`);
414
+ }
415
+ });
416
+ doc.measurements.forEach((m, i) => {
417
+ if (
418
+ !isObject(m) ||
419
+ typeof m.id !== "string" ||
420
+ typeof m.workloadId !== "string" ||
421
+ typeof m.phase !== "string"
422
+ ) {
423
+ throw bad(
424
+ `measurements[${i}] must be an object with string "id", "workloadId" and "phase"`,
425
+ );
426
+ }
427
+ for (const key of ["trials", "warnings", "artifacts"]) {
428
+ if (!Array.isArray(m[key])) {
429
+ throw bad(`measurements[${i}].${key} must be an array`);
430
+ }
431
+ }
432
+ });
433
+ }
434
+
435
+ /**
436
+ * `ab` documents from ostia 0.2.8-0.2.9 name the ratio quartiles
437
+ * `p25`/`p75`, now `ratioP25`/`ratioP75`; read the old names so saved
438
+ * documents still render. Those from before 0.2.12 lack `ab.metric`. */
439
+ function renamePairedRatioFields(doc: ProfileDocument): ProfileDocument {
440
+ const rename = (r: Record<string, unknown>) => {
441
+ if (r.ratioP25 !== undefined || r.p25 === undefined) return;
442
+ r.ratioP25 = r.p25;
443
+ r.ratioP75 = r.p75;
444
+ delete r.p25;
445
+ delete r.p75;
446
+ };
447
+ for (const m of doc.measurements) {
448
+ if (!m.paired) continue;
449
+ rename(m.paired as unknown as Record<string, unknown>);
450
+ for (const r of m.paired.repeats ?? [])
451
+ rename(r as unknown as Record<string, unknown>);
452
+ }
453
+ // Before 0.2.12, `ab` judged by time alone.
454
+ if (doc.ab) doc.ab.metric ??= "time";
455
+ return doc;
456
+ }
457
+
458
+ /**
459
+ * Documents from before ostia 0.2.4 lack `p25`/`p75`/`p99`/`mad`;
460
+ * recompute them so every consumer sees the full `TimingStats`. */
461
+ function backfillTimingStats(doc: ProfileDocument): ProfileDocument {
462
+ for (const m of doc.measurements) {
463
+ const t = m.timing;
464
+ if (!t || t.mad !== undefined || t.samples.length === 0) continue;
465
+ m.timing = {
466
+ ...computeTimingStats(t.samples),
467
+ ...(t.batch !== undefined && { batch: t.batch }),
468
+ };
469
+ }
470
+ return doc;
471
+ }
package/src/ir/fp.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Key-order-independent JSON: equal values give equal text, which keeps
3
+ * `fp()` ids and saved documents stable. */
4
+ export function canonicalJSON(value: unknown, indent?: number): string {
5
+ return JSON.stringify(sortKeysDeep(value), null, indent);
6
+ }
7
+
8
+ /**
9
+ * Deep copy with plain-object keys sorted. Arrays of only primitives (a
10
+ * 10k-entry `samples`) are returned as is, keeping `JSON.stringify` on its
11
+ * fast path. */
12
+ function sortKeysDeep(value: unknown): unknown {
13
+ if (Array.isArray(value)) {
14
+ const hasObjects = value.some((v) => v !== null && typeof v === "object");
15
+ return hasObjects ? value.map(sortKeysDeep) : value;
16
+ }
17
+ if (value !== null && typeof value === "object") {
18
+ const source = value as Record<string, unknown>;
19
+ const out: Record<string, unknown> = {};
20
+ for (const key of Object.keys(source).sort()) {
21
+ out[key] = sortKeysDeep(source[key]);
22
+ }
23
+ return out;
24
+ }
25
+ return value;
26
+ }
27
+
28
+ export function fp(tag: string, ...parts: unknown[]): string {
29
+ const hex = Bun.CryptoHasher.hash("sha256", canonicalJSON(parts), "hex");
30
+ return `${tag}_${hex.slice(0, 16)}`;
31
+ }
package/src/ir/git.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { GitMetadata } from "./types.ts";
2
+
3
+ const GIT_TIMEOUT_MS = 200;
4
+
5
+ let memo: { git: GitMetadata | undefined } | undefined;
6
+
7
+ function runGit(args: string[]): string | undefined {
8
+ const proc = Bun.spawnSync(["git", ...args], {
9
+ timeout: GIT_TIMEOUT_MS,
10
+ stdout: "pipe",
11
+ stderr: "ignore",
12
+ });
13
+ return proc.success ? proc.stdout.toString().trim() : undefined;
14
+ }
15
+
16
+ function readGitMetadata(): GitMetadata | undefined {
17
+ try {
18
+ const sha = runGit(["rev-parse", "--short", "HEAD"]);
19
+ if (sha === undefined) return undefined;
20
+ return {
21
+ sha,
22
+ branch: runGit(["rev-parse", "--abbrev-ref", "HEAD"]) ?? "HEAD",
23
+ dirty: (runGit(["status", "--porcelain"])?.length ?? 0) > 0,
24
+ };
25
+ } catch {
26
+ return undefined;
27
+ }
28
+ }
29
+
30
+ /** Repo state of the process's cwd, memoized for the process lifetime.
31
+ * Undefined outside a repo, without `git`, or past the 200ms per-call
32
+ * timeout: metadata is never worth failing a measurement over. */
33
+ export function captureGitMetadata(): GitMetadata | undefined {
34
+ memo ??= { git: readGitMetadata() };
35
+ return memo.git;
36
+ }