forked from jflournoy/for-funsies
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgsd_ledger.ts
More file actions
356 lines (307 loc) · 10.5 KB
/
Copy pathgsd_ledger.ts
File metadata and controls
356 lines (307 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
#!/usr/bin/env node
/**
* Append rows to GSD-LEDGER.md.
*
* Ported from the original CommonJS `scripts/gsd_ledger.js` to TypeScript
* following the repository's move to `"type": "module"` and TS-only source.
* The CLI contract is unchanged — see the usages in the issue.
*
* Usage:
* npm run ledger -- --pr <n> --contributor <handle> --issue <n> --amount <n> --kind <kind> \
* [--proposer <handle>] [--denomination GSD|USD] [--notes <text>]
*/
import { readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
import { parseLedger, type LedgerEntry } from "./ledger.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
// dist/js/gsd_ledger.js -> repo root (two levels up)
const LEDGER_PATH = resolve(__dirname, "..", "..", "GSD-LEDGER.md");
const VALID_KINDS = new Set<string>([
"bounty",
"proposal",
"proposal-shipped",
"implementation",
]);
function fail(msg: string): never {
process.stderr.write(`Error: ${msg}\n`);
process.exit(1);
}
function today(): string {
const d = new Date();
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, "0");
const dd = String(d.getDate()).padStart(2, "0");
return `${yyyy}-${mm}-${dd}`;
}
function buildRow(
num: number,
date: string,
contributor: string,
kind: string,
pr: string,
issue: string,
amount: string,
denomination: string,
notes: string,
): string {
return `| ${num} | ${date} | ${contributor} | \`${kind}\` | ${pr} | ${issue} | ${amount} | ${denomination} | ${notes} |`;
}
interface InsertPositions {
insertAt: number;
placeholderIdx: number;
}
/**
* Find where new rows go. Newest entries sit at the bottom of the table, so we
* insert right after the separator (or replace the `_(none yet…)_` placeholder
* when it is still present). The ledger is append-only: we never touch existing
* rows.
*/
function findInsertPositions(lines: string[]): InsertPositions {
let headerFound = false;
let separatorFound = false;
let insertAt = -1;
let placeholderIdx = -1;
for (let i = 0; i < lines.length; i++) {
const trimmed = lines[i]!.trim();
if (!headerFound && trimmed.startsWith("| # |")) {
headerFound = true;
continue;
}
if (headerFound && !separatorFound && trimmed.startsWith("|---")) {
separatorFound = true;
insertAt = i + 1;
continue;
}
if (separatorFound && trimmed.startsWith("|")) {
if (trimmed.startsWith("| _(") || /^\|\s*_\(/.test(trimmed)) {
placeholderIdx = i;
}
insertAt = i + 1;
}
}
if (insertAt === -1) {
fail("Could not find the ledger table in GSD-LEDGER.md");
}
return { insertAt, placeholderIdx };
}
function appendRows(lines: string[], newRows: string[]): string[] {
const { insertAt, placeholderIdx } = findInsertPositions(lines);
if (placeholderIdx !== -1) {
lines.splice(placeholderIdx, 1, ...newRows);
} else {
lines.splice(insertAt, 0, ...newRows);
}
return lines;
}
interface LedgerCliArgs {
pr: number;
contributor: string;
issue: number;
amount: string;
kind: string;
proposer?: string;
denomination?: string;
notes?: string;
}
/** Validate a date cell is a structurally valid ISO yyyy-mm-dd date. */
function isValidIsoDate(value: string): boolean {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
if (!m) return false;
const year = Number(m[1]);
const month = Number(m[2]);
const day = Number(m[3]);
if (month < 1 || month > 12) return false;
const daysInMonth = new Date(year, month, 0).getDate();
return day >= 1 && day <= daysInMonth;
}
/**
* Validate the structural integrity of the ledger: sequential row numbers
* starting from 1, valid ISO dates, positive amounts, kinds in the allowed
* set, and no deleted or reordered rows. Prints the first violation to stderr
* and exits 1 on failure; stays silent and exits 0 on success.
*/
function validateLedger(content: string): void {
// Parse the raw table ourselves rather than reusing parseLedger: parseLedger
// silently skips malformed rows, but a validator must flag them.
const rows: Array<{ line: number; cells: string[] }> = [];
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const trimmed = lines[i]!.trim();
if (!trimmed.startsWith("|")) continue;
const cells = trimmed.slice(1, -1).split("|").map((c) => c.trim());
// Only treat 9-column rows with a numeric first cell as ledger entries.
const index = Number.parseInt(cells[0] ?? "", 10);
if (cells.length !== 9 || !Number.isFinite(index)) continue;
rows.push({ line: i + 1, cells });
}
// An empty ledger is structurally valid.
if (rows.length === 0) {
process.stdout.write("Ledger is valid\n");
return;
}
// 1. Row numbers must be sequential starting from 1, with no deletion/reorder.
for (let i = 0; i < rows.length; i++) {
const expected = i + 1;
const actual = Number.parseInt(rows[i]!.cells[0]!, 10);
if (actual !== expected) {
process.stderr.write(
`Row ${expected} is missing — expected #${expected} but found #${actual}\n`,
);
process.exit(1);
}
}
for (const row of rows) {
const [num, date, , kind, , , amount] = row.cells;
// 2. Dates must be valid ISO format.
if (!isValidIsoDate(date!)) {
process.stderr.write(`Row ${num} has an invalid date: ${date}\n`);
process.exit(1);
}
// 3. Amounts must be positive numbers.
const amountNum = Number.parseFloat(amount!);
if (!Number.isFinite(amountNum) || amountNum <= 0) {
process.stderr.write(`Row ${num} has a non-positive amount: ${amount}\n`);
process.exit(1);
}
// 4. Kinds must be in the allowed set (strip backticks like the parser).
const kindClean = kind!.replace(/`/g, "");
if (!VALID_KINDS.has(kindClean)) {
process.stderr.write(
`Row ${num} has an invalid kind: ${kindClean} (expected one of: ${[...VALID_KINDS].join(", ")})\n`,
);
process.exit(1);
}
}
process.stdout.write("Ledger is valid\n");
}
/**
* Print per-contributor totals, broken down by award kind.
* Originally PR #20 (waterWang), from accepted proposal #7 (Kasuki354).
*/
function printSummary(entries: readonly LedgerEntry[]): void {
const KINDS = ["bounty", "proposal", "proposal-shipped", "implementation"] as const;
const totals = new Map<string, Map<string, number>>();
for (const e of entries) {
if (e.denomination.toUpperCase() !== "GSD") continue;
const row = totals.get(e.contributor) ?? new Map<string, number>();
row.set(e.kind, (row.get(e.kind) ?? 0) + (Number.parseFloat(e.amount) || 0));
totals.set(e.contributor, row);
}
const nameWidth = Math.max(11, ...[...totals.keys()].map((n) => n.length));
const cols = [...KINDS, "Total"];
const widths = cols.map((c) => Math.max(c.length, 6));
const line = (cells: readonly string[]): string =>
" " +
cells
.map((c, i) => c.padEnd(i === 0 ? nameWidth : (widths[i - 1] ?? 6)))
.join(" | ") +
" ";
process.stdout.write(line(["Contributor", ...cols]) + "\n");
process.stdout.write(
line([
"-".repeat(nameWidth),
...cols.map((_, i) => "-".repeat(widths[i] ?? 6)),
]) + "\n",
);
for (const [name, row] of totals) {
const perKind = KINDS.map((k) => String(row.get(k) ?? 0));
const total = [...row.values()].reduce((a, b) => a + b, 0);
process.stdout.write(line([name, ...perKind, String(total)]) + "\n");
}
}
function main(): void {
const { values } = parseArgs({
args: process.argv.slice(2),
options: {
pr: { type: "string" },
contributor: { type: "string" },
issue: { type: "string" },
amount: { type: "string" },
kind: { type: "string" },
proposer: { type: "string" },
denomination: { type: "string" },
notes: { type: "string" },
validate: { type: "boolean" },
format: { type: "string" },
summary: { type: "boolean" },
},
strict: true,
});
// The --validate flag is a standalone mode: read, check, report, exit.
if (values.validate) {
const content = readFileSync(LEDGER_PATH, "utf-8");
validateLedger(content);
return;
}
// --format json: dump the parsed ledger as structured data. (#5, PR #19)
if (values.format !== undefined) {
if (values.format !== "json") {
fail("--format currently supports only: json");
}
const entries = parseLedger(readFileSync(LEDGER_PATH, "utf-8"));
process.stdout.write(JSON.stringify(entries, null, 2) + "\n");
return;
}
// --summary: per-contributor totals broken down by award kind. (#7, PR #20)
if (values.summary) {
printSummary(parseLedger(readFileSync(LEDGER_PATH, "utf-8")));
return;
}
const pr = values.pr;
const contributor = values.contributor;
const issue = values.issue;
const amount = values.amount;
const kind = values.kind;
const proposer = values.proposer;
const denomination = values.denomination ?? "GSD";
const notes = values.notes ?? "";
if (!pr) fail("--pr is required");
if (!contributor) fail("--contributor is required");
if (!issue) fail("--issue is required");
if (!amount) fail("--amount is required");
if (!kind) fail("--kind is required");
if (!VALID_KINDS.has(kind)) {
fail(`--kind must be one of: ${[...VALID_KINDS].join(", ")}`);
}
if (denomination !== "GSD" && denomination !== "USD") {
fail("--denomination must be GSD or USD");
}
const content = readFileSync(LEDGER_PATH, "utf-8");
const lines = content.split("\n");
// Drop trailing blank lines so we control the final newline.
while (lines.length > 0 && lines[lines.length - 1] === "") {
lines.pop();
}
// Reuse the shared parser for the authoritative row shape and numbering.
const existingEntries: LedgerEntry[] = parseLedger(content);
const lastNum =
existingEntries.length > 0
? Math.max(...existingEntries.map((r) => r.index))
: 0;
const date = today();
const newRows: string[] = [];
newRows.push(
buildRow(lastNum + 1, date, contributor, kind, pr, issue, amount, denomination, notes),
);
if (proposer) {
newRows.push(
buildRow(
lastNum + 2,
date,
proposer,
"proposal-shipped",
pr,
issue,
"2",
"GSD",
`Proposer of PR #${pr}`,
),
);
}
const updated = appendRows([...lines], newRows);
writeFileSync(LEDGER_PATH, updated.join("\n") + "\n", "utf-8");
process.stdout.write(`Appended ${newRows.length} row(s) to GSD-LEDGER.md\n`);
}
main();