@trazum/cli 3.0.1 → 3.0.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.
- package/README.md +4 -1
- package/assets/trazum-statusline.sh +45 -0
- package/dist/base-cost.d.ts +173 -0
- package/dist/base-cost.d.ts.map +1 -0
- package/dist/base-cost.js +244 -0
- package/dist/base-cost.js.map +1 -0
- package/dist/bill-range.d.ts +118 -0
- package/dist/bill-range.d.ts.map +1 -0
- package/dist/bill-range.js +122 -0
- package/dist/bill-range.js.map +1 -0
- package/dist/command-help.d.ts +17 -0
- package/dist/command-help.d.ts.map +1 -0
- package/dist/command-help.js +69 -0
- package/dist/command-help.js.map +1 -0
- package/dist/filter.d.ts +7 -1
- package/dist/filter.d.ts.map +1 -1
- package/dist/filter.js +10 -18
- package/dist/filter.js.map +1 -1
- package/dist/gateway-metrics.d.ts +83 -0
- package/dist/gateway-metrics.d.ts.map +1 -0
- package/dist/gateway-metrics.js +181 -0
- package/dist/gateway-metrics.js.map +1 -0
- package/dist/gateway-server.d.ts +23 -5
- package/dist/gateway-server.d.ts.map +1 -1
- package/dist/gateway-server.js +26 -1
- package/dist/gateway-server.js.map +1 -1
- package/dist/gateway-spend.d.ts +11 -1
- package/dist/gateway-spend.d.ts.map +1 -1
- package/dist/gateway-spend.js +44 -32
- package/dist/gateway-spend.js.map +1 -1
- package/dist/git.d.ts +70 -0
- package/dist/git.d.ts.map +1 -1
- package/dist/git.js +145 -0
- package/dist/git.js.map +1 -1
- package/dist/i18n/en.d.ts.map +1 -1
- package/dist/i18n/en.js +358 -6
- package/dist/i18n/en.js.map +1 -1
- package/dist/i18n/es.d.ts +0 -1
- package/dist/i18n/es.d.ts.map +1 -1
- package/dist/i18n/es.js +456 -35
- package/dist/i18n/es.js.map +1 -1
- package/dist/i18n/types.d.ts +205 -0
- package/dist/i18n/types.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +942 -59
- package/dist/index.js.map +1 -1
- package/dist/loopback-guard.d.ts +37 -0
- package/dist/loopback-guard.d.ts.map +1 -0
- package/dist/loopback-guard.js +65 -0
- package/dist/loopback-guard.js.map +1 -0
- package/dist/markdown.d.ts +23 -0
- package/dist/markdown.d.ts.map +1 -1
- package/dist/markdown.js +105 -0
- package/dist/markdown.js.map +1 -1
- package/dist/plan-edits.d.ts +63 -0
- package/dist/plan-edits.d.ts.map +1 -0
- package/dist/plan-edits.js +96 -0
- package/dist/plan-edits.js.map +1 -0
- package/dist/proactive.d.ts +17 -2
- package/dist/proactive.d.ts.map +1 -1
- package/dist/proactive.js +16 -9
- package/dist/proactive.js.map +1 -1
- package/dist/receipt-send.d.ts +44 -0
- package/dist/receipt-send.d.ts.map +1 -0
- package/dist/receipt-send.js +71 -0
- package/dist/receipt-send.js.map +1 -0
- package/dist/serve.d.ts +7 -0
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +22 -1
- package/dist/serve.js.map +1 -1
- package/dist/session-guard.d.ts +210 -0
- package/dist/session-guard.d.ts.map +1 -0
- package/dist/session-guard.js +463 -0
- package/dist/session-guard.js.map +1 -0
- package/dist/task.d.ts +7 -1
- package/dist/task.d.ts.map +1 -1
- package/dist/task.js +7 -26
- package/dist/task.js.map +1 -1
- package/dist/waste.d.ts +25 -0
- package/dist/waste.d.ts.map +1 -0
- package/dist/waste.js +39 -0
- package/dist/waste.js.map +1 -0
- package/dist/zone.d.ts +27 -0
- package/dist/zone.d.ts.map +1 -0
- package/dist/zone.js +96 -0
- package/dist/zone.js.map +1 -0
- package/package.json +2 -2
- package/src/base-cost.ts +384 -0
- package/src/bill-range.ts +206 -0
- package/src/command-help.ts +65 -0
- package/src/filter.ts +11 -18
- package/src/gateway-metrics.ts +209 -0
- package/src/gateway-server.ts +43 -6
- package/src/gateway-spend.ts +45 -33
- package/src/git.ts +158 -0
- package/src/i18n/en.ts +424 -6
- package/src/i18n/es.ts +542 -35
- package/src/i18n/types.ts +208 -0
- package/src/index.ts +952 -58
- package/src/loopback-guard.ts +74 -0
- package/src/markdown.ts +117 -0
- package/src/plan-edits.ts +120 -0
- package/src/proactive.ts +22 -13
- package/src/receipt-send.ts +89 -0
- package/src/serve.ts +23 -1
- package/src/session-guard.ts +541 -0
- package/src/task.ts +8 -26
- package/src/waste.ts +42 -0
- package/src/zone.ts +95 -0
package/src/gateway-server.ts
CHANGED
|
@@ -36,6 +36,8 @@ import { createServer } from 'node:http';
|
|
|
36
36
|
import type { IncomingMessage, Server, ServerResponse } from 'node:http';
|
|
37
37
|
import { estimateTokens, gatewayDecision, streamingUsageReader, usageFromResponse } from '@trazum/core';
|
|
38
38
|
import { GatewaySpend } from './gateway-spend.js';
|
|
39
|
+
import type { GatewayUsage } from './gateway-spend.js';
|
|
40
|
+
import { refuseContentType, refuseHost } from './loopback-guard.js';
|
|
39
41
|
import type {
|
|
40
42
|
GatewayDecision,
|
|
41
43
|
GatewayPolicy,
|
|
@@ -264,6 +266,18 @@ export function route(
|
|
|
264
266
|
/** Why a forwarded call's cost could not be measured. */
|
|
265
267
|
export type UnmeasuredCause = 'stream-broke' | 'no-usage-event' | 'no-usage-in-body';
|
|
266
268
|
|
|
269
|
+
/**
|
|
270
|
+
* Something the gateway did with a call, other than measure it: refused it,
|
|
271
|
+
* substituted its model, forwarded it free, or could not reach the provider.
|
|
272
|
+
* A reason, two model ids or a path from `UPSTREAMS`, and never any text of
|
|
273
|
+
* the call's.
|
|
274
|
+
*/
|
|
275
|
+
export type GatewayCount =
|
|
276
|
+
| { kind: 'refused'; reason: string }
|
|
277
|
+
| { kind: 'substituted'; from: string; to: string }
|
|
278
|
+
| { kind: 'free'; path: string }
|
|
279
|
+
| { kind: 'unreachable' };
|
|
280
|
+
|
|
267
281
|
const HOP_BY_HOP = new Set([
|
|
268
282
|
'connection',
|
|
269
283
|
'keep-alive',
|
|
@@ -304,12 +318,8 @@ export interface GatewayContext {
|
|
|
304
318
|
record: (measured: {
|
|
305
319
|
model: string;
|
|
306
320
|
label: string | null;
|
|
307
|
-
inputTokens: number;
|
|
308
|
-
outputTokens: number;
|
|
309
|
-
cacheReadTokens: number;
|
|
310
|
-
cacheWriteTokens: number;
|
|
311
321
|
substituted: boolean;
|
|
312
|
-
}) => void;
|
|
322
|
+
} & GatewayUsage) => void;
|
|
313
323
|
/**
|
|
314
324
|
* A call that was forwarded and whose cost could not be measured.
|
|
315
325
|
*
|
|
@@ -330,6 +340,8 @@ export interface GatewayContext {
|
|
|
330
340
|
* quietly missing most of their traffic.
|
|
331
341
|
*/
|
|
332
342
|
unmeasured?: (cause: UnmeasuredCause) => void;
|
|
343
|
+
/** What happened to a call that was not measured, for `--metrics-port`. Counts only. */
|
|
344
|
+
count?: (event: GatewayCount) => void;
|
|
333
345
|
/** A line for the operator's terminal. Never given a body, ever. */
|
|
334
346
|
note: (line: string) => void;
|
|
335
347
|
/** Injected so the proxy is testable against a stub upstream. */
|
|
@@ -493,9 +505,18 @@ export function buildGateway(context: GatewayContext): Server {
|
|
|
493
505
|
const doFetch = context.fetchImpl ?? fetch;
|
|
494
506
|
const spend = context.liveBudget ? new GatewaySpend(context.catalogue) : null;
|
|
495
507
|
|
|
496
|
-
|
|
508
|
+
const server: Server = createServer((request: IncomingMessage, response: ServerResponse) => {
|
|
497
509
|
let ticket: symbol | undefined;
|
|
498
510
|
void (async () => {
|
|
511
|
+
// A page that rebound its own hostname to 127.0.0.1 must not read the
|
|
512
|
+
// standing a 402 carries, or reach a path that spends. See
|
|
513
|
+
// `loopback-guard.ts`; the same two refusals as `trazum serve`.
|
|
514
|
+
const refused = refuseHost(server, request);
|
|
515
|
+
if (refused !== null) {
|
|
516
|
+
response.writeHead(refused.status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
517
|
+
response.end(`${JSON.stringify({ error: refused.error, detail: refused.detail })}\n`);
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
499
520
|
if (upstream === undefined) {
|
|
500
521
|
response.writeHead(500, { 'content-type': 'application/json' });
|
|
501
522
|
response.end(`${JSON.stringify({ error: 'no upstream configured for this provider' })}\n`);
|
|
@@ -519,6 +540,15 @@ export function buildGateway(context: GatewayContext): Server {
|
|
|
519
540
|
return;
|
|
520
541
|
}
|
|
521
542
|
|
|
543
|
+
// After routing, so an unknown path is still a 404; before any body is
|
|
544
|
+
// read, so a text/plain POST is never judged or forwarded.
|
|
545
|
+
const untyped = refuseContentType(request);
|
|
546
|
+
if (untyped !== null) {
|
|
547
|
+
response.writeHead(untyped.status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
548
|
+
response.end(`${JSON.stringify({ error: untyped.error, detail: untyped.detail })}\n`);
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
|
|
522
552
|
/**
|
|
523
553
|
* A path that spends nothing is forwarded and nothing else happens to it.
|
|
524
554
|
*
|
|
@@ -553,6 +583,7 @@ export function buildGateway(context: GatewayContext): Server {
|
|
|
553
583
|
...(request.method === 'GET' ? {} : { body: sent ?? '' }),
|
|
554
584
|
});
|
|
555
585
|
} catch (error) {
|
|
586
|
+
context.count?.({ kind: 'unreachable' });
|
|
556
587
|
response.writeHead(502, { 'content-type': 'application/json' });
|
|
557
588
|
response.end(
|
|
558
589
|
`${JSON.stringify({
|
|
@@ -568,6 +599,7 @@ export function buildGateway(context: GatewayContext): Server {
|
|
|
568
599
|
free.headers.forEach((value, name) => {
|
|
569
600
|
if (!HOP_BY_HOP.has(name.toLowerCase())) headers[name] = value;
|
|
570
601
|
});
|
|
602
|
+
context.count?.({ kind: 'free', path: routed.path });
|
|
571
603
|
response.writeHead(free.status, headers);
|
|
572
604
|
response.end(Buffer.from(await free.arrayBuffer()));
|
|
573
605
|
return;
|
|
@@ -620,6 +652,7 @@ export function buildGateway(context: GatewayContext): Server {
|
|
|
620
652
|
* every time. 402 Payment Required is both literally correct and in
|
|
621
653
|
* nobody's default retry list.
|
|
622
654
|
*/
|
|
655
|
+
context.count?.({ kind: 'refused', reason: decision.reason });
|
|
623
656
|
response.writeHead(402, { 'content-type': 'application/json' });
|
|
624
657
|
response.end(refusalBody(decision));
|
|
625
658
|
context.note(`refused ${described.model}: ${decision.reason}`);
|
|
@@ -629,6 +662,7 @@ export function buildGateway(context: GatewayContext): Server {
|
|
|
629
662
|
if (spend !== null) {
|
|
630
663
|
const admission = spend.reserve(call, decision, standing, context.policy.onCannotTell === 'fail-closed');
|
|
631
664
|
if (admission.refusal !== undefined) {
|
|
665
|
+
context.count?.({ kind: 'refused', reason: String(admission.refusal.reason) });
|
|
632
666
|
response.writeHead(402, { 'content-type': 'application/json' });
|
|
633
667
|
response.end(`${JSON.stringify(admission.refusal)}\n`);
|
|
634
668
|
return;
|
|
@@ -652,6 +686,7 @@ export function buildGateway(context: GatewayContext): Server {
|
|
|
652
686
|
const parsed = JSON.parse(body) as Record<string, unknown>;
|
|
653
687
|
parsed.model = decision.to.id;
|
|
654
688
|
forwarded = JSON.stringify(parsed);
|
|
689
|
+
context.count?.({ kind: 'substituted', from: described.model, to: decision.to.id });
|
|
655
690
|
context.note(`substituted ${described.model} → ${decision.to.id}: ${decision.configuredReason}`);
|
|
656
691
|
} else if (decision.unjudged !== null) {
|
|
657
692
|
context.note(`forwarded unjudged (${decision.unjudged}): fail-open`);
|
|
@@ -667,6 +702,7 @@ export function buildGateway(context: GatewayContext): Server {
|
|
|
667
702
|
} catch (error) {
|
|
668
703
|
// A transport failure does not prove the provider did no billable work.
|
|
669
704
|
if (ticket !== undefined) spend?.settle(ticket, described.model, null);
|
|
705
|
+
context.count?.({ kind: 'unreachable' });
|
|
670
706
|
/**
|
|
671
707
|
* The upstream is unreachable. This is **not** a budget refusal and
|
|
672
708
|
* must not look like one: the caller needs to tell "your provider is
|
|
@@ -816,6 +852,7 @@ export function buildGateway(context: GatewayContext): Server {
|
|
|
816
852
|
}
|
|
817
853
|
}).finally(() => { if (ticket !== undefined) spend?.release(ticket); });
|
|
818
854
|
});
|
|
855
|
+
return server;
|
|
819
856
|
}
|
|
820
857
|
|
|
821
858
|
export function listenGateway(
|
package/src/gateway-spend.ts
CHANGED
|
@@ -1,7 +1,49 @@
|
|
|
1
1
|
import { indexUsage, parseUsageLine, usageFromResponse } from '@trazum/core';
|
|
2
2
|
import type { GatewayCall, GatewayDecision, GatewayStanding, MeasuredPosition, PricingCatalogue } from '@trazum/core';
|
|
3
3
|
|
|
4
|
-
type GatewayUsage = NonNullable<ReturnType<typeof usageFromResponse>>;
|
|
4
|
+
export type GatewayUsage = NonNullable<ReturnType<typeof usageFromResponse>>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One measured call's cost at the catalogue's list rates, or `null` when it
|
|
8
|
+
* cannot be priced honestly: a model the catalogue does not carry, a count
|
|
9
|
+
* that is not a finite non-negative number, or a flat cache-write count with
|
|
10
|
+
* no TTL split (assuming 5m would undercharge a 1h write).
|
|
11
|
+
*
|
|
12
|
+
* The live budget and `--metrics-port` both price from here, so the figure a
|
|
13
|
+
* refusal rests on and the figure Prometheus shows cannot disagree.
|
|
14
|
+
*/
|
|
15
|
+
export function priceGatewayUsage(catalogue: PricingCatalogue, model: string, usage: GatewayUsage, nowMs: number): number | null {
|
|
16
|
+
const writesKnown = usage.cacheWriteTokens === 0 ||
|
|
17
|
+
(usage.cacheWrite5mTokens !== undefined && usage.cacheWrite1hTokens !== undefined &&
|
|
18
|
+
usage.cacheWrite5mTokens + usage.cacheWrite1hTokens === usage.cacheWriteTokens);
|
|
19
|
+
if (!writesKnown ||
|
|
20
|
+
Object.values(usage).some((value) => typeof value === 'number' && (!Number.isFinite(value) || value < 0))) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
const record = parseUsageLine(JSON.stringify({
|
|
24
|
+
model, ts: new Date(nowMs).toISOString(),
|
|
25
|
+
input_tokens: usage.inputTokens, output_tokens: usage.outputTokens,
|
|
26
|
+
cache_read_input_tokens: usage.cacheReadTokens,
|
|
27
|
+
cache_creation_input_tokens: usage.cacheWriteTokens,
|
|
28
|
+
cache_creation: {
|
|
29
|
+
ephemeral_5m_input_tokens: usage.cacheWrite5mTokens ?? 0,
|
|
30
|
+
ephemeral_1h_input_tokens: usage.cacheWrite1hTokens ?? 0,
|
|
31
|
+
},
|
|
32
|
+
// Fast mode bills at a multiple of standard; the response said which ran.
|
|
33
|
+
...(usage.speed === undefined ? {} : { speed: usage.speed }),
|
|
34
|
+
// So does OpenAI's service tier, each priced from its own table.
|
|
35
|
+
...(usage.serviceTier === undefined ? {} : { service_tier: usage.serviceTier }),
|
|
36
|
+
// And US-only inference, 1.1x on Claude 4.6 and later.
|
|
37
|
+
...(usage.inferenceGeo === undefined ? {} : { inference_geo: usage.inferenceGeo }),
|
|
38
|
+
// And the searches, $10 per 1,000 on top of the tokens.
|
|
39
|
+
...(usage.webSearchRequests === undefined
|
|
40
|
+
? {}
|
|
41
|
+
: { server_tool_use: { web_search_requests: usage.webSearchRequests } }),
|
|
42
|
+
}));
|
|
43
|
+
const index = record === null ? null : indexUsage([record], { catalogue, on: new Date(nowMs) });
|
|
44
|
+
if (index === null || index.unpriced > 0 || index.dayUsd === null) return null;
|
|
45
|
+
return index.dayUsd;
|
|
46
|
+
}
|
|
5
47
|
|
|
6
48
|
type Admitted = Exclude<GatewayDecision, { kind: 'refuse' }>;
|
|
7
49
|
const DAY_MS = 86_400_000;
|
|
@@ -83,42 +125,12 @@ export class GatewaySpend {
|
|
|
83
125
|
const pending = this.pending.get(ticket);
|
|
84
126
|
if (pending === undefined) return;
|
|
85
127
|
this.pending.delete(ticket);
|
|
86
|
-
const writesKnown = usage !== null && (usage.cacheWriteTokens === 0 ||
|
|
87
|
-
(usage.cacheWrite5mTokens !== undefined && usage.cacheWrite1hTokens !== undefined &&
|
|
88
|
-
usage.cacheWrite5mTokens + usage.cacheWrite1hTokens === usage.cacheWriteTokens));
|
|
89
|
-
if (usage === null || !writesKnown ||
|
|
90
|
-
Object.values(usage).some((value) => typeof value === 'number' && (!Number.isFinite(value) || value < 0))) {
|
|
91
|
-
// A flat write count has no TTL. Assuming 5m undercharges a 1h write.
|
|
92
|
-
this.unknown = true;
|
|
93
|
-
return;
|
|
94
|
-
}
|
|
95
128
|
const now = Date.now();
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
input_tokens: usage.inputTokens, output_tokens: usage.outputTokens,
|
|
99
|
-
cache_read_input_tokens: usage.cacheReadTokens,
|
|
100
|
-
cache_creation_input_tokens: usage.cacheWriteTokens,
|
|
101
|
-
cache_creation: {
|
|
102
|
-
ephemeral_5m_input_tokens: usage.cacheWrite5mTokens ?? 0,
|
|
103
|
-
ephemeral_1h_input_tokens: usage.cacheWrite1hTokens ?? 0,
|
|
104
|
-
},
|
|
105
|
-
// Fast mode bills at a multiple of standard; the response said which ran.
|
|
106
|
-
...(usage.speed === undefined ? {} : { speed: usage.speed }),
|
|
107
|
-
// So does OpenAI's service tier, each priced from its own table.
|
|
108
|
-
...(usage.serviceTier === undefined ? {} : { service_tier: usage.serviceTier }),
|
|
109
|
-
// And US-only inference, 1.1x on Claude 4.6 and later.
|
|
110
|
-
...(usage.inferenceGeo === undefined ? {} : { inference_geo: usage.inferenceGeo }),
|
|
111
|
-
// And the searches, $10 per 1,000 on top of the tokens.
|
|
112
|
-
...(usage.webSearchRequests === undefined
|
|
113
|
-
? {}
|
|
114
|
-
: { server_tool_use: { web_search_requests: usage.webSearchRequests } }),
|
|
115
|
-
}));
|
|
116
|
-
const index = record === null ? null : indexUsage([record], { catalogue: this.catalogue, on: new Date(now) });
|
|
117
|
-
if (index === null || index.unpriced > 0 || index.dayUsd === null) {
|
|
129
|
+
const usd = usage === null ? null : priceGatewayUsage(this.catalogue, model, usage, now);
|
|
130
|
+
if (usd === null) {
|
|
118
131
|
this.unknown = true;
|
|
119
132
|
return;
|
|
120
133
|
}
|
|
121
|
-
const usd = index.dayUsd;
|
|
122
134
|
this.usd += usd;
|
|
123
135
|
const day = Math.floor(now / DAY_MS) * DAY_MS;
|
|
124
136
|
this.days.set(day, (this.days.get(day) ?? 0) + usd);
|
package/src/git.ts
CHANGED
|
@@ -173,6 +173,19 @@ export function repositoryRoot(cwd: string): string | null {
|
|
|
173
173
|
return out === null ? null : out.trim() || null;
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
+
/**
|
|
177
|
+
* Whether git tracks `repoPath` in the repository at `root`.
|
|
178
|
+
*
|
|
179
|
+
* `trazum plan --edits` writes an edit only for a tracked file: the edit is
|
|
180
|
+
* opened later as a pull request, and a pull request can only change what the
|
|
181
|
+
* repository holds. The path goes after `--`, like every path here, so a file
|
|
182
|
+
* named like an option is read as a file.
|
|
183
|
+
*/
|
|
184
|
+
export function isTracked(root: string, repoPath: string): boolean {
|
|
185
|
+
const out = git(['ls-files', '--error-unmatch', '--', repoPath], root);
|
|
186
|
+
return out !== null && out.trim() !== '';
|
|
187
|
+
}
|
|
188
|
+
|
|
176
189
|
/**
|
|
177
190
|
* The path as git knows it — relative to the repository root, forward slashes —
|
|
178
191
|
* or `null` when it falls outside the repository.
|
|
@@ -296,6 +309,115 @@ export function runNotifier(
|
|
|
296
309
|
};
|
|
297
310
|
}
|
|
298
311
|
|
|
312
|
+
/** When one commit of a range was written and when it was committed, in epoch milliseconds. */
|
|
313
|
+
export interface CommitTimes {
|
|
314
|
+
authorMs: number;
|
|
315
|
+
committerMs: number;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* A revision range is one argument that git reads as a range. It is refused
|
|
320
|
+
* before it reaches the argv when it could be read as an option (a leading
|
|
321
|
+
* `-`) or carries a control character or a space, which no range needs.
|
|
322
|
+
*/
|
|
323
|
+
function isSafeRange(range: string): boolean {
|
|
324
|
+
if (range === '' || range.startsWith('-')) return false;
|
|
325
|
+
for (const ch of range) {
|
|
326
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
327
|
+
// `trim()` removes exactly the characters a regular expression's `\s` matches.
|
|
328
|
+
if (code <= 0x1f || code === 0x7f || ch.trim() === '') return false;
|
|
329
|
+
}
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* The author and commit times of every commit in `range`, for `bill --git-range`.
|
|
335
|
+
*
|
|
336
|
+
* Times only: no author's name, no subject, no hash leaves this function, because
|
|
337
|
+
* the one thing the caller needs is when the work began and when it was
|
|
338
|
+
* committed, and anything else would be a way for a name to reach a bill.
|
|
339
|
+
* `null` when git ran and refused the range (it names nothing that exists); an
|
|
340
|
+
* empty list when the range holds no commit; a thrown `GitUnavailableError`
|
|
341
|
+
* when git could not be run at all, so the two never read as the same answer.
|
|
342
|
+
*/
|
|
343
|
+
export function commitTimes(range: string, options: { cwd: string; spawn?: SpawnLike }): CommitTimes[] | null {
|
|
344
|
+
if (!isSafeRange(range)) return null;
|
|
345
|
+
const outcome = runGit(
|
|
346
|
+
['log', '--format=%at\u001f%ct', '--max-count=100000', range, '--'],
|
|
347
|
+
options.cwd,
|
|
348
|
+
options.spawn,
|
|
349
|
+
);
|
|
350
|
+
if (!outcome.ran) throw new GitUnavailableError(outcome.detail);
|
|
351
|
+
if (outcome.stdout === null) return null;
|
|
352
|
+
const times: CommitTimes[] = [];
|
|
353
|
+
for (const row of outcome.stdout.split('\n')) {
|
|
354
|
+
if (row.trim() === '') continue;
|
|
355
|
+
const [author = '', committer = ''] = row.trim().split('\u001f');
|
|
356
|
+
if (!/^\d+$/.test(author) || !/^\d+$/.test(committer)) continue;
|
|
357
|
+
times.push({ authorMs: Number(author) * 1000, committerMs: Number(committer) * 1000 });
|
|
358
|
+
}
|
|
359
|
+
return times;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** What a range delivered, as counts: no name, no subject and no hash is kept. */
|
|
363
|
+
export interface RangeDelivery {
|
|
364
|
+
commits: number;
|
|
365
|
+
/** Commits with more than one parent. They are in `commits` too. */
|
|
366
|
+
merges: number;
|
|
367
|
+
/** Distinct UTC calendar days (YYYY-MM-DD) on which a commit was committed. */
|
|
368
|
+
days: number;
|
|
369
|
+
/** Distinct pull request numbers a subject names; a rebase merge names none, so this is a floor. */
|
|
370
|
+
pullRequests: number;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* The pull request a commit subject names, or `null`: only the number.
|
|
375
|
+
*
|
|
376
|
+
* Two shapes, both written by GitHub's own merge buttons: `Merge pull request
|
|
377
|
+
* #N from ...` on a merge commit, and `... (#N)` closing the subject of a squash
|
|
378
|
+
* commit. The caller keeps the number and the subject goes out of scope on
|
|
379
|
+
* return, so the text of a message cannot reach an output from here.
|
|
380
|
+
*/
|
|
381
|
+
function pullRequestOf(subject: string, parents: number): number | null {
|
|
382
|
+
const text = subject.trim();
|
|
383
|
+
const found = parents > 1 ? text.match(/^Merge pull request #(\d{1,9}) from /) : text.match(/\(#(\d{1,9})\)$/);
|
|
384
|
+
return found === null ? null : Number(found[1]);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* What `range` delivered, for `bill --git-range --delivery` (#825): the number
|
|
389
|
+
* of commits, of them merges, of UTC days with a commit, and of pull requests
|
|
390
|
+
* named by number. Metadata only: the log is asked for the parents, the commit
|
|
391
|
+
* time and the subject, the subject is read for a number and dropped, and the
|
|
392
|
+
* return value is four integers. Same refusals as `commitTimes`.
|
|
393
|
+
*/
|
|
394
|
+
export function rangeDelivery(range: string, options: { cwd: string; spawn?: SpawnLike }): RangeDelivery | null {
|
|
395
|
+
if (!isSafeRange(range)) return null;
|
|
396
|
+
const outcome = runGit(
|
|
397
|
+
['log', '--format=%P\u001f%ct\u001f%s', '--max-count=100000', range, '--'],
|
|
398
|
+
options.cwd,
|
|
399
|
+
options.spawn,
|
|
400
|
+
);
|
|
401
|
+
if (!outcome.ran) throw new GitUnavailableError(outcome.detail);
|
|
402
|
+
if (outcome.stdout === null) return null;
|
|
403
|
+
const days = new Set<string>();
|
|
404
|
+
const pullRequests = new Set<number>();
|
|
405
|
+
let commits = 0;
|
|
406
|
+
let merges = 0;
|
|
407
|
+
for (const row of outcome.stdout.split('\n')) {
|
|
408
|
+
if (row.trim() === '') continue;
|
|
409
|
+
const [parentField = '', committer = '', ...subject] = row.split('\u001f');
|
|
410
|
+
if (!/^\d+$/.test(committer)) continue;
|
|
411
|
+
const parents = parentField.split(' ').filter((p) => p !== '').length;
|
|
412
|
+
commits += 1;
|
|
413
|
+
if (parents > 1) merges += 1;
|
|
414
|
+
days.add(new Date(Number(committer) * 1000).toISOString().slice(0, 10));
|
|
415
|
+
const pr = pullRequestOf(subject.join('\u001f'), parents);
|
|
416
|
+
if (pr !== null) pullRequests.add(pr);
|
|
417
|
+
}
|
|
418
|
+
return { commits, merges, days: days.size, pullRequests: pullRequests.size };
|
|
419
|
+
}
|
|
420
|
+
|
|
299
421
|
/**
|
|
300
422
|
* Commits that touched `repoPath`, newest first.
|
|
301
423
|
*
|
|
@@ -363,6 +485,42 @@ export function contentAt(sha: string, repoPath: string, cwd: string): string |
|
|
|
363
485
|
return git(['show', `${sha}:${repoPath}`], cwd);
|
|
364
486
|
}
|
|
365
487
|
|
|
488
|
+
/**
|
|
489
|
+
* The full sha of the commit `ref` names in this checkout, or `null` when the
|
|
490
|
+
* checkout does not have it.
|
|
491
|
+
*
|
|
492
|
+
* `trazum check --base` (#785) reads the base branch from the clone the job
|
|
493
|
+
* already has, and never fetches: a commit that is not here is reported as
|
|
494
|
+
* not here, with what would bring it, and is never stood in for by the
|
|
495
|
+
* working tree. A ref that starts with a dash is refused before git sees it,
|
|
496
|
+
* because git would read it as an option. Unable to run git at all throws,
|
|
497
|
+
* for the reason `revisionsFor` does.
|
|
498
|
+
*/
|
|
499
|
+
export function commitOf(ref: string, cwd: string, spawn?: SpawnLike): string | null {
|
|
500
|
+
if (ref === '' || ref.startsWith('-')) return null;
|
|
501
|
+
const outcome = runGit(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], cwd, spawn);
|
|
502
|
+
if (!outcome.ran) throw new GitUnavailableError(outcome.detail);
|
|
503
|
+
const sha = outcome.stdout?.trim() ?? '';
|
|
504
|
+
return SHA.test(sha) ? sha : null;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Every file under `repoPath` at a commit, as paths from the repository root,
|
|
509
|
+
* or `null` when git could not answer.
|
|
510
|
+
*
|
|
511
|
+
* `repoPath` is relative to the repository root and `cwd` is that root; an
|
|
512
|
+
* empty `repoPath` means the whole tree. A file path lists that one file when
|
|
513
|
+
* it is there. NUL-separated output, so a name holding a newline is one name.
|
|
514
|
+
*/
|
|
515
|
+
export function filesAt(sha: string, repoPath: string, cwd: string): string[] | null {
|
|
516
|
+
if (!SHA.test(sha)) return null;
|
|
517
|
+
const args = ['ls-tree', '-r', '-z', '--name-only', '--full-tree', sha];
|
|
518
|
+
if (repoPath !== '') args.push('--', repoPath);
|
|
519
|
+
const out = git(args, cwd);
|
|
520
|
+
if (out === null) return null;
|
|
521
|
+
return out.split('\u0000').filter((name) => name !== '');
|
|
522
|
+
}
|
|
523
|
+
|
|
366
524
|
/**
|
|
367
525
|
* The name the file had at each commit, keyed by sha.
|
|
368
526
|
*
|