@turingcode/cli 0.1.0 → 0.2.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.
- package/README.md +96 -0
- package/dist/cli/create-cli.js +15 -4
- package/dist/cli/index.js +1 -1
- package/dist/core/bound-error.js +14 -0
- package/dist/{features/table/ast.js → core/exact/expression.js} +22 -14
- package/dist/{features/table → core/exact}/fraction.js +62 -0
- package/dist/core/files.js +26 -0
- package/dist/{features/table/shape.js → core/json-shape.js} +45 -40
- package/dist/core/report.js +14 -0
- package/dist/core/tables/csv.js +95 -0
- package/dist/core/tables/markdown.js +107 -0
- package/dist/core/tables/types.js +1 -0
- package/dist/features/clock/command.js +26 -13
- package/dist/features/contract/check.js +31 -0
- package/dist/features/contract/command.js +60 -0
- package/dist/features/contract/describe.js +93 -0
- package/dist/features/contract/diagnostics.js +108 -0
- package/dist/features/contract/load.js +212 -0
- package/dist/features/contract/model.js +33 -0
- package/dist/features/contract/rules.js +197 -0
- package/dist/features/table/check.js +295 -0
- package/dist/features/table/command.js +32 -74
- package/dist/features/table/read.js +33 -0
- package/package.json +2 -2
- package/dist/features/table/contract.js +0 -487
- package/dist/features/table/contract_check.js +0 -265
- package/dist/features/table/describe.js +0 -197
- package/dist/features/table/diagnostics.js +0 -129
- package/dist/features/table/format.js +0 -75
- package/dist/features/table/primitives.js +0 -268
- package/dist/features/table/source_kinds.js +0 -41
- package/dist/features/table/table_check.js +0 -538
- package/dist/features/table/tables.js +0 -223
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { BoundError } from "../bound-error.js";
|
|
2
|
+
const SEPARATOR = /^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
|
|
3
|
+
const HEADING = /^##\s+(.+?)\s*#*\s*$/;
|
|
4
|
+
/**
|
|
5
|
+
* Splits one Markdown table line into trimmed cells; `\|` is a literal pipe.
|
|
6
|
+
*
|
|
7
|
+
* @param {string} line - A line starting with `|`.
|
|
8
|
+
* @returns {string[]} The cells.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* splitRow("| a | b \\| c |"); // ["a", "b | c"]
|
|
12
|
+
*/
|
|
13
|
+
export function splitRow(line) {
|
|
14
|
+
let body = line.trim();
|
|
15
|
+
if (body.startsWith("|"))
|
|
16
|
+
body = body.slice(1);
|
|
17
|
+
if (body.endsWith("|") && !body.endsWith("\\|"))
|
|
18
|
+
body = body.slice(0, -1);
|
|
19
|
+
const cells = [];
|
|
20
|
+
let cell = "";
|
|
21
|
+
for (let i = 0; i < body.length; i++) {
|
|
22
|
+
if (body[i] === "\\" && body[i + 1] === "|") {
|
|
23
|
+
cell += "|";
|
|
24
|
+
i++;
|
|
25
|
+
}
|
|
26
|
+
else if (body[i] === "|") {
|
|
27
|
+
cells.push(cell.trim());
|
|
28
|
+
cell = "";
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
cell += body[i];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
cells.push(cell.trim());
|
|
35
|
+
return cells;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Reads the tables of a Markdown document. A table is the first pipe
|
|
39
|
+
* table under a `## <Name>` heading; pipe tables inside fenced code blocks
|
|
40
|
+
* are ignored.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} text - The Markdown text.
|
|
43
|
+
* @param {number} maxRows - `bounds.max_table_rows`.
|
|
44
|
+
* @returns {TablesDoc} The tables.
|
|
45
|
+
* @throws {BoundError} When a table has more than maxRows rows.
|
|
46
|
+
*/
|
|
47
|
+
export function parseMarkdown(text, maxRows) {
|
|
48
|
+
const lines = text.replace(/^/, "").split(/\r?\n/);
|
|
49
|
+
const tables = new Map();
|
|
50
|
+
const duplicates = [];
|
|
51
|
+
const malformed = [];
|
|
52
|
+
/** [table name, first line index, end line index (exclusive)] of every pipe-table block. */
|
|
53
|
+
const blocks = [];
|
|
54
|
+
let section = null;
|
|
55
|
+
let fenced = false;
|
|
56
|
+
for (let i = 0; i < lines.length; i++) {
|
|
57
|
+
const line = lines[i];
|
|
58
|
+
if (/^\s*(```|~~~)/.test(line)) {
|
|
59
|
+
fenced = !fenced;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (fenced)
|
|
63
|
+
continue;
|
|
64
|
+
const heading = HEADING.exec(line);
|
|
65
|
+
if (heading || /^#\s/.test(line)) {
|
|
66
|
+
section = heading ? heading[1] : null;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (section === null || !line.trim().startsWith("|"))
|
|
70
|
+
continue;
|
|
71
|
+
const start = i;
|
|
72
|
+
while (i + 1 < lines.length && lines[i + 1].trim().startsWith("|"))
|
|
73
|
+
i++;
|
|
74
|
+
const block = lines.slice(start, i + 1);
|
|
75
|
+
blocks.push([section, start, i + 1]);
|
|
76
|
+
if (tables.has(section) || malformed.some(([n]) => n === section)) {
|
|
77
|
+
if (!duplicates.includes(section))
|
|
78
|
+
duplicates.push(section);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (block.length < 2 || !SEPARATOR.test(block[1])) {
|
|
82
|
+
malformed.push([section, `line ${start + 1}: the header row is not followed by a '|---|' separator row`]);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const rows = block.slice(2).map(splitRow);
|
|
86
|
+
if (rows.length > maxRows)
|
|
87
|
+
throw new BoundError("max_table_rows", maxRows);
|
|
88
|
+
tables.set(section, {
|
|
89
|
+
name: section,
|
|
90
|
+
header: splitRow(block[0]),
|
|
91
|
+
rows,
|
|
92
|
+
rowLines: rows.map((_, k) => start + 3 + k),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
tables, duplicates, malformed, text,
|
|
97
|
+
textOutside(names) {
|
|
98
|
+
const skip = new Set();
|
|
99
|
+
for (const [name, from, to] of blocks) {
|
|
100
|
+
if (names.includes(name))
|
|
101
|
+
for (let k = from; k < to; k++)
|
|
102
|
+
skip.add(k);
|
|
103
|
+
}
|
|
104
|
+
return lines.filter((_, k) => !skip.has(k)).join("\n");
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -30,20 +30,28 @@ const finite = (value) => {
|
|
|
30
30
|
return value;
|
|
31
31
|
};
|
|
32
32
|
const sharedOptions = {
|
|
33
|
-
project: { type: "string", describe: "Project folder name on the server
|
|
34
|
-
format: { choices: ["markdown", "json"], describe: "
|
|
35
|
-
"hse-ppm": { type: "number", coerce: finite, describe: "HSE
|
|
36
|
-
vdd: { type: "number", coerce: finite, describe: "Supply voltage in
|
|
33
|
+
project: { type: "string", describe: "Project folder name on the server" },
|
|
34
|
+
format: { choices: ["markdown", "json"], describe: "markdown | json (default markdown)" },
|
|
35
|
+
"hse-ppm": { type: "number", coerce: finite, describe: "HSE tolerance in ppm, for the worst case (default 0)" },
|
|
36
|
+
vdd: { type: "number", coerce: finite, describe: "Supply voltage in V, for SPI limits (default 3.3)" },
|
|
37
37
|
};
|
|
38
38
|
const solve = {
|
|
39
39
|
command: "solve",
|
|
40
|
-
describe: "Solve a clock tree for a target SYSCLK
|
|
40
|
+
describe: "Solve a clock tree for a target SYSCLK; prints a .ioc patch for stm32_cubetools_set_params",
|
|
41
41
|
builder: cli => cli.options({
|
|
42
42
|
...sharedOptions,
|
|
43
|
-
config: { type: "string", coerce: readJsonArg, describe: "Design
|
|
44
|
-
target: { type: "number", coerce: finite, describe: "Target SYSCLK in Hz" },
|
|
45
|
-
objective: {
|
|
46
|
-
|
|
43
|
+
config: { type: "string", coerce: readJsonArg, describe: "Design (before a project exists), inline JSON or .json path" },
|
|
44
|
+
target: { type: "number", coerce: finite, describe: "Target SYSCLK in Hz (with --project)" },
|
|
45
|
+
objective: {
|
|
46
|
+
choices: ["exact_target", "min_error", "max_clock"],
|
|
47
|
+
describe: "exact_target | min_error | max_clock (default exact_target; with --project)",
|
|
48
|
+
},
|
|
49
|
+
})
|
|
50
|
+
.example(`$0 clock solve --config '{"part":"STM32G474RETx","sources":{"hse":{"hz":8000000,"ppm":50}},`
|
|
51
|
+
+ `"system":{"objective":"exact_target","target_sysclk_hz":170000000}}'`, "")
|
|
52
|
+
.example("$0 clock solve --project my_board --target 170000000", "")
|
|
53
|
+
.epilogue("Give --project, --config or both. With --config, put target, objective, ppm and vdd inside it "
|
|
54
|
+
+ "(system, sources, conditions)."),
|
|
47
55
|
handler: args => runServerTool("stm32_cubetools_clock_solve", {
|
|
48
56
|
project_name: args.project, config: args.config, target_sysclk_hz: args.target, objective: args.objective,
|
|
49
57
|
output_format: args.format, hse_ppm: args["hse-ppm"], vdd: args.vdd,
|
|
@@ -51,16 +59,21 @@ const solve = {
|
|
|
51
59
|
};
|
|
52
60
|
const audit = {
|
|
53
61
|
command: "audit",
|
|
54
|
-
describe: "Audit a project's clocks and peripheral timing
|
|
55
|
-
builder: cli => cli.options(
|
|
62
|
+
describe: "Audit a project's clocks and peripheral timing against the datasheet limits",
|
|
63
|
+
builder: cli => cli.options({
|
|
64
|
+
...sharedOptions,
|
|
65
|
+
project: { ...sharedOptions.project, demandOption: true, describe: "Project folder name on the server (required)" },
|
|
66
|
+
})
|
|
67
|
+
.example("$0 clock audit --project my_board", ""),
|
|
56
68
|
handler: args => runServerTool("stm32_cubetools_clock_audit", {
|
|
57
69
|
project_name: args.project, output_format: args.format, hse_ppm: args["hse-ppm"], vdd: args.vdd,
|
|
58
70
|
}),
|
|
59
71
|
};
|
|
60
72
|
const command = {
|
|
61
73
|
command: "clock",
|
|
62
|
-
describe: "STM32 clock tree
|
|
63
|
-
builder: cli => cli.command(solve).command(audit).demandCommand(1)
|
|
74
|
+
describe: "Solve or audit an STM32 clock tree on the Turing Code server",
|
|
75
|
+
builder: cli => cli.command(solve).command(audit).demandCommand(1)
|
|
76
|
+
.epilogue("Needs TURINGCODE_TOKEN (gateway token); TURINGCODE_URL overrides the gateway."),
|
|
64
77
|
handler: () => { },
|
|
65
78
|
};
|
|
66
79
|
export default command;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { formatDiagnostics, sortDiagnostics } from "./diagnostics.js";
|
|
2
|
+
import { loadContract } from "./load.js";
|
|
3
|
+
/** Labels of a loaded contract and all its dependencies. */
|
|
4
|
+
const labels = (c) => [c.label, ...[...c.deps.values()].flatMap(labels)];
|
|
5
|
+
/**
|
|
6
|
+
* contract check: validates a contract and the contracts it depends on.
|
|
7
|
+
*
|
|
8
|
+
* @param {string} path - Contract file.
|
|
9
|
+
* @returns {ContractCheckResult} Status and diagnostics.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* contractCheck("orders.contract.json").status; // "VALID"
|
|
13
|
+
*/
|
|
14
|
+
export function contractCheck(path) {
|
|
15
|
+
const diags = [];
|
|
16
|
+
const loaded = loadContract(path, diags);
|
|
17
|
+
const status = diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA"
|
|
18
|
+
: loaded.contract ? "VALID" : "INVALID_CONTRACT";
|
|
19
|
+
return { status, contract: loaded.label, checked: [...new Set(labels(loaded))], diagnostics: sortDiagnostics(diags) };
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Compact text for a contract check (or describe) result.
|
|
23
|
+
*
|
|
24
|
+
* @param {{status: string, contract: string, diagnostics: Diagnostic[], checked?: string[]}} r - The result.
|
|
25
|
+
* @returns {string} Status line, then the diagnostics.
|
|
26
|
+
*/
|
|
27
|
+
export function formatContractCheck(r) {
|
|
28
|
+
const fails = r.diagnostics.filter(d => d.severity === "FAIL").length;
|
|
29
|
+
const deps = r.checked && r.checked.length > 1 ? ` (with ${r.checked.slice(1).join(", ")})` : "";
|
|
30
|
+
return [`${r.status} ${r.contract}${deps}: ${fails} FAIL`, ...formatDiagnostics(r.diagnostics)].join("\n") + "\n";
|
|
31
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { report } from "../../core/report.js";
|
|
2
|
+
import { contractCheck, formatContractCheck } from "./check.js";
|
|
3
|
+
import { describeContract } from "./describe.js";
|
|
4
|
+
export const CONTRACT = { type: "string", demandOption: true, describe: "Contract JSON (required)" };
|
|
5
|
+
export const JSON_FLAG = { type: "boolean", describe: "Full result as one-line JSON" };
|
|
6
|
+
/** The contract format in brief, for `contract --help`. Only tables, and each table's and column's name, are required. */
|
|
7
|
+
const FORMAT = `Contract JSON (only "tables" and each table's and column's "name" are required; defaults shown):
|
|
8
|
+
{
|
|
9
|
+
"name": "shop.orders", "version": "1.0.0", "description": "...",
|
|
10
|
+
"format": "markdown", // or "csv": one <table>.csv per table
|
|
11
|
+
"missing_values": [""], // cell texts that count as empty, e.g. ["", "-"]
|
|
12
|
+
"allow_extra_tables": false,
|
|
13
|
+
"depends_on": { "customers": "customers.contract.json" }, // tables passed with --dep customers=<file>
|
|
14
|
+
"tables": [{
|
|
15
|
+
"name": "Orders", "required": true, "primary_key": "Order_ID", // or ["A", "B"]; filled and unique
|
|
16
|
+
"ordered": false, "allow_extra_columns": false,
|
|
17
|
+
"columns": [{
|
|
18
|
+
"name": "Total",
|
|
19
|
+
"type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
|
|
20
|
+
"required": false, "unique": false,
|
|
21
|
+
"pattern": "regex", "enum": ["a", "b"], "minimum": 0, "maximum": 100,
|
|
22
|
+
"min_length": 1, "max_length": 9, "separator": ",", // lengths: chars, or list items
|
|
23
|
+
"references": "Table.Column" // or "alias:Table.Column" of a dependency
|
|
24
|
+
}],
|
|
25
|
+
"rules": [{ "kind": "...", "when": { "Status": "shipped" }, "severity": "error" }] // or "warning"
|
|
26
|
+
}]
|
|
27
|
+
}
|
|
28
|
+
Rule kinds and their fields:
|
|
29
|
+
required_if {columns} empty_if {columns} unique_together {columns} row_count {min, max}
|
|
30
|
+
compare {left, op: < <= == != >= >, right, tolerance} e.g. "Qty * Price" == "Total" (exact arithmetic)
|
|
31
|
+
mentioned {values_of: "Column" | "Table.Column", in: ["Table.Column", ...] | "*" (anywhere else)}`;
|
|
32
|
+
const check = {
|
|
33
|
+
command: "check",
|
|
34
|
+
describe: "Validate a contract and the contracts it depends on",
|
|
35
|
+
builder: cli => cli.options({ contract: CONTRACT, json: JSON_FLAG })
|
|
36
|
+
.example("$0 contract check --contract orders.contract.json", "")
|
|
37
|
+
.epilogue("Contract format: turingcode contract --help.\nExit: 0 VALID, 1 INVALID_CONTRACT, 2 missing file."),
|
|
38
|
+
handler: args => {
|
|
39
|
+
const result = contractCheck(args.contract);
|
|
40
|
+
report(result, formatContractCheck(result), args.json);
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
const describe = {
|
|
44
|
+
command: "describe",
|
|
45
|
+
describe: "Print the tables a contract expects, their columns and rules, as Markdown",
|
|
46
|
+
builder: cli => cli.options({ contract: CONTRACT, json: JSON_FLAG })
|
|
47
|
+
.example("$0 contract describe --contract orders.contract.json", "")
|
|
48
|
+
.epilogue("Contract format: turingcode contract --help."),
|
|
49
|
+
handler: args => {
|
|
50
|
+
const result = describeContract(args.contract);
|
|
51
|
+
report(result, result.markdown ?? formatContractCheck(result), args.json);
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
const contract = {
|
|
55
|
+
command: "contract",
|
|
56
|
+
describe: "Validate a table contract, or print the tables it expects",
|
|
57
|
+
builder: cli => cli.command(check).command(describe).demandCommand(1).epilogue(FORMAT),
|
|
58
|
+
handler: () => { },
|
|
59
|
+
};
|
|
60
|
+
export default contract;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { sortDiagnostics } from "./diagnostics.js";
|
|
2
|
+
import { loadContract } from "./load.js";
|
|
3
|
+
import { keyColumns } from "./model.js";
|
|
4
|
+
import { RULE_KINDS, whenText } from "./rules.js";
|
|
5
|
+
const code = (v) => `\`${String(v)}\``;
|
|
6
|
+
const list = (vs) => vs.map(code).join(", ");
|
|
7
|
+
/** Escapes a cell for a Markdown table. */
|
|
8
|
+
const cell = (s) => s.replace(/\|/g, "\\|");
|
|
9
|
+
/** The constraints of a column, in words. */
|
|
10
|
+
function constraints(col) {
|
|
11
|
+
const parts = [];
|
|
12
|
+
if (col.unique)
|
|
13
|
+
parts.push("unique");
|
|
14
|
+
if (col.enum)
|
|
15
|
+
parts.push(`one of ${list(col.enum)}`);
|
|
16
|
+
if (col.pattern)
|
|
17
|
+
parts.push(`matches ${code(col.pattern)}`);
|
|
18
|
+
if (col.minimum !== undefined)
|
|
19
|
+
parts.push(`>= ${col.minimum}`);
|
|
20
|
+
if (col.maximum !== undefined)
|
|
21
|
+
parts.push(`<= ${col.maximum}`);
|
|
22
|
+
if (col.min_length !== undefined || col.max_length !== undefined) {
|
|
23
|
+
parts.push(`length ${col.min_length ?? 0}..${col.max_length ?? "any"}`);
|
|
24
|
+
}
|
|
25
|
+
if (col.type === "list")
|
|
26
|
+
parts.push(`items separated by ${code(col.separator ?? ",")}`);
|
|
27
|
+
if (col.references)
|
|
28
|
+
parts.push(`values of ${code(col.references)}`);
|
|
29
|
+
return parts.join("; ");
|
|
30
|
+
}
|
|
31
|
+
/** Markdown lines for one table. */
|
|
32
|
+
function tableSection(t) {
|
|
33
|
+
const key = keyColumns(t);
|
|
34
|
+
const lines = [`### Table ${code(t.name)}${t.required === false ? " (optional)" : ""}`, ""];
|
|
35
|
+
if (t.description)
|
|
36
|
+
lines.push(t.description, "");
|
|
37
|
+
lines.push([
|
|
38
|
+
key.length ? `Primary key: ${list(key)} (filled and unique).` : "",
|
|
39
|
+
t.ordered ? "Columns in this order." : "Columns in any order.",
|
|
40
|
+
t.allow_extra_columns ? "Other columns are allowed." : "No other columns.",
|
|
41
|
+
].filter(Boolean).join(" "), "");
|
|
42
|
+
lines.push("| Column | Type | Required | Constraints | Description |", "|---|---|---|---|---|");
|
|
43
|
+
for (const col of t.columns) {
|
|
44
|
+
const required = col.required || key.includes(col.name) ? "yes" : "no";
|
|
45
|
+
lines.push(`| ${col.name} | ${col.type ?? "string"} | ${required} | ${cell(constraints(col))} | ${cell(col.description ?? "")} |`);
|
|
46
|
+
}
|
|
47
|
+
const rules = (t.rules ?? []).map(r => `- ${whenText(r)}${RULE_KINDS[r.kind].describe(r)}`
|
|
48
|
+
+ (r.severity === "warning" ? " (warning)" : "") + (r.description ? ` ${r.description}` : ""));
|
|
49
|
+
if (rules.length)
|
|
50
|
+
lines.push("", "Rules:", ...rules);
|
|
51
|
+
lines.push("");
|
|
52
|
+
return lines;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Renders a valid contract as a Markdown guide to the tables it expects.
|
|
56
|
+
*
|
|
57
|
+
* @param {Contract} c - The contract.
|
|
58
|
+
* @returns {string} The guide.
|
|
59
|
+
*/
|
|
60
|
+
export function renderGuide(c) {
|
|
61
|
+
const missing = (c.missing_values ?? [""]).map(v => (v === "" ? "an empty cell" : code(v))).join(" or ");
|
|
62
|
+
const lines = [`# Contract ${c.name ? code(c.version ? `${c.name}@${c.version}` : c.name) : ""}`.trimEnd(), ""];
|
|
63
|
+
if (c.description)
|
|
64
|
+
lines.push(c.description, "");
|
|
65
|
+
lines.push("## Format", "", c.format === "csv"
|
|
66
|
+
? "Write each table as `<table name>.csv` in one folder, header row first."
|
|
67
|
+
: `Write each table under a heading with its name, e.g. ${code(`## ${c.tables[0].name}`)}, as a Markdown table: `
|
|
68
|
+
+ "a header row, a `|---|` separator row, then one row per item. Write `\\|` for a `|` inside a cell.", `A missing value is ${missing}. ${c.allow_extra_tables ? "Other tables are allowed." : "No other tables."}`, "", "## Tables", "");
|
|
69
|
+
for (const t of c.tables)
|
|
70
|
+
lines.push(...tableSection(t));
|
|
71
|
+
const deps = Object.entries(c.depends_on ?? {});
|
|
72
|
+
if (deps.length) {
|
|
73
|
+
lines.push("## Dependencies", "", ...deps.map(([alias, path]) => `- ${code(alias)}: contract ${code(path)}`), "");
|
|
74
|
+
}
|
|
75
|
+
const depFlags = deps.map(([alias]) => ` --dep ${alias}=<its tables>`).join("");
|
|
76
|
+
lines.push("## Checking", "", "```", `turingcode table check --contract <this contract> --tables <your tables>${depFlags}`, "```");
|
|
77
|
+
return lines.join("\n").replace(/\n{3,}/g, "\n\n") + "\n";
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* contract describe: validates the contract, then renders its guide.
|
|
81
|
+
*
|
|
82
|
+
* @param {string} path - Contract file.
|
|
83
|
+
* @returns {DescribeResult} OK with the Markdown, or the contract's problems.
|
|
84
|
+
*/
|
|
85
|
+
export function describeContract(path) {
|
|
86
|
+
const diags = [];
|
|
87
|
+
const loaded = loadContract(path, diags);
|
|
88
|
+
if (!loaded.contract) {
|
|
89
|
+
const status = diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT";
|
|
90
|
+
return { status, contract: loaded.label, diagnostics: sortDiagnostics(diags) };
|
|
91
|
+
}
|
|
92
|
+
return { status: "OK", contract: loaded.label, markdown: renderGuide(loaded.contract), diagnostics: sortDiagnostics(diags) };
|
|
93
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** Every code, with its fix hint. */
|
|
2
|
+
const HINTS = {
|
|
3
|
+
// Contract problems (contract check, and table check before it starts).
|
|
4
|
+
"CONTRACT.BAD_JSON": "Fix the JSON syntax of the contract file.",
|
|
5
|
+
"CONTRACT.BAD_FIELD": "Give the field the type or value named in 'expected'; remove unknown fields.",
|
|
6
|
+
"CONTRACT.BAD_REGEX": "Write a valid JavaScript regular expression.",
|
|
7
|
+
"CONTRACT.BAD_EXPRESSION": "Write an arithmetic expression over this table's number columns.",
|
|
8
|
+
"CONTRACT.UNKNOWN_TABLE": "Name a table the contract declares.",
|
|
9
|
+
"CONTRACT.UNKNOWN_COLUMN": "Name a column the table declares.",
|
|
10
|
+
"CONTRACT.UNKNOWN_DEPENDENCY": "Declare the alias in depends_on.",
|
|
11
|
+
"CONTRACT.DUPLICATE": "Give each table, column and rule a unique name.",
|
|
12
|
+
"CONTRACT.CONFLICT": "Make the settings agree (e.g. minimum <= maximum, constraint fits the type).",
|
|
13
|
+
"CONTRACT.CYCLE": "Remove the circular depends_on.",
|
|
14
|
+
"CONTRACT.MISSING_FILE": "Check the path; the file must exist and be readable.",
|
|
15
|
+
// Problems in the tables (table check).
|
|
16
|
+
"MISSING_TABLE": "Add the table under a '## <name>' heading (Markdown) or as <name>.csv.",
|
|
17
|
+
"EXTRA_TABLE": "Remove the table, or declare it in the contract.",
|
|
18
|
+
"DUPLICATE_TABLE": "Write each table once.",
|
|
19
|
+
"BAD_TABLE": "Write the table as a header row, a '|---|' separator row, then data rows.",
|
|
20
|
+
"MISSING_COLUMN": "Add the column to the header.",
|
|
21
|
+
"EXTRA_COLUMN": "Remove the column, or declare it in the contract.",
|
|
22
|
+
"DUPLICATE_COLUMN": "Name each column once.",
|
|
23
|
+
"COLUMN_ORDER": "Put the columns in the declared order.",
|
|
24
|
+
"ROW_SHAPE": "Give the row one cell per column; in Markdown write '\\|' for a '|' inside a cell.",
|
|
25
|
+
"MISSING_VALUE": "Fill the cell.",
|
|
26
|
+
"BAD_TYPE": "Write the value in the column's type.",
|
|
27
|
+
"BAD_VALUE": "Use one of the allowed values, spelled exactly.",
|
|
28
|
+
"PATTERN": "Write the value in the required format.",
|
|
29
|
+
"OUT_OF_RANGE": "Use a value within the allowed range.",
|
|
30
|
+
"BAD_LENGTH": "Use a value of the allowed length.",
|
|
31
|
+
"DUPLICATE_KEY": "Make the value unique in its table.",
|
|
32
|
+
"UNKNOWN_REF": "Use only values that exist in the referenced column.",
|
|
33
|
+
"REQUIRED_IF": "Fill the cell; the rule requires it for this row.",
|
|
34
|
+
"EMPTY_IF": "Leave the cell empty; the rule forbids a value for this row.",
|
|
35
|
+
"COMPARE": "Correct the values so the comparison holds.",
|
|
36
|
+
"UNIQUE_TOGETHER": "Make the combination of values unique.",
|
|
37
|
+
"ROW_COUNT": "Add or remove rows so the count fits.",
|
|
38
|
+
"NOT_MENTIONED": "Mention the value where the rule says.",
|
|
39
|
+
// Inputs.
|
|
40
|
+
"MISSING_FILE": "Check the path; the file must exist and be readable.",
|
|
41
|
+
"MISSING_DEPENDENCY": "Pass the dependency's tables with --dep <alias>=<file>.",
|
|
42
|
+
"TOO_LARGE": "Split the table; it exceeds the row limit.",
|
|
43
|
+
"INVALID_INPUT": "Fix the command arguments named in the message.",
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Builds a diagnostic with its fix hint.
|
|
47
|
+
*
|
|
48
|
+
* @param {Code} code - The code.
|
|
49
|
+
* @param {string} message - What is wrong.
|
|
50
|
+
* @param {Where} at - Table, row, column and rule.
|
|
51
|
+
* @param {string} found - Observed value.
|
|
52
|
+
* @param {string} expected - Required value.
|
|
53
|
+
* @param {"FAIL"|"WARN"} [severity="FAIL"] - Severity.
|
|
54
|
+
* @returns {Diagnostic} The diagnostic.
|
|
55
|
+
*/
|
|
56
|
+
export function diag(code, message, at, found, expected, severity = "FAIL") {
|
|
57
|
+
return {
|
|
58
|
+
severity, code, table: at.table ?? "-", row: at.row ?? "-", column: at.column ?? "-", message, found, expected,
|
|
59
|
+
fix: HINTS[code], ...(at.rule ? { rule: at.rule } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Sorts diagnostics deterministically: FAIL before WARN, then by table, row, column, code.
|
|
64
|
+
*
|
|
65
|
+
* @param {Diagnostic[]} list - Diagnostics.
|
|
66
|
+
* @returns {Diagnostic[]} A sorted copy.
|
|
67
|
+
*/
|
|
68
|
+
export function sortDiagnostics(list) {
|
|
69
|
+
const key = (d) => [d.severity, d.table, d.row, d.column, d.code, d.message].join("\u0000");
|
|
70
|
+
return [...list].sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
|
|
71
|
+
}
|
|
72
|
+
/** Most rows listed on one grouped line before "+N more". */
|
|
73
|
+
const MAX_ROWS_PER_LINE = 20;
|
|
74
|
+
/** " table row column" without unset parts ("-"), with a leading space when not empty. */
|
|
75
|
+
const place = (...parts) => parts.filter(p => p !== "-").map(p => ` ${p}`).join("");
|
|
76
|
+
/**
|
|
77
|
+
* Renders diagnostics as compact text: one line per finding, findings that
|
|
78
|
+
* differ only by row grouped onto one line, then each fix hint once per code.
|
|
79
|
+
*
|
|
80
|
+
* @param {Diagnostic[]} diags - Sorted diagnostics.
|
|
81
|
+
* @returns {string[]} The lines.
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* formatDiagnostics(result.diagnostics);
|
|
85
|
+
* // ["FAIL BAD_VALUE Orders Status ×2: O-1=Open, O-4=Shipped; expected open, closed", "fix BAD_VALUE: ..."]
|
|
86
|
+
*/
|
|
87
|
+
export function formatDiagnostics(diags) {
|
|
88
|
+
const lines = [];
|
|
89
|
+
const groups = new Map();
|
|
90
|
+
for (const d of diags) {
|
|
91
|
+
const key = [d.severity, d.code, d.table, d.column, d.expected, d.rule].join("\u0000");
|
|
92
|
+
groups.set(key, [...(groups.get(key) ?? []), d]);
|
|
93
|
+
}
|
|
94
|
+
for (const [d, ...more] of groups.values()) {
|
|
95
|
+
const rule = d.rule ? ` [${d.rule}]` : "";
|
|
96
|
+
if (!more.length) {
|
|
97
|
+
lines.push(`${d.severity} ${d.code}${place(d.table, d.row, d.column)}: ${d.message}; expected ${d.expected}${rule}`);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const all = [d, ...more];
|
|
101
|
+
const rows = all.slice(0, MAX_ROWS_PER_LINE).map(x => `${x.row}=${x.found}`).join(", ");
|
|
102
|
+
const extra = all.length > MAX_ROWS_PER_LINE ? ` +${all.length - MAX_ROWS_PER_LINE} more` : "";
|
|
103
|
+
lines.push(`${d.severity} ${d.code}${place(d.table, d.column)} ×${all.length}: ${rows}${extra}; expected ${d.expected}${rule}`);
|
|
104
|
+
}
|
|
105
|
+
for (const [code, fix] of new Map(diags.map(d => [d.code, d.fix])))
|
|
106
|
+
lines.push(`fix ${code}: ${fix}`);
|
|
107
|
+
return lines;
|
|
108
|
+
}
|