@geml/geml 1.7.1 → 1.7.2
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 +20 -4
- package/dist/block-edit.js +15 -1
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +2433 -0
- package/dist/from-md.js +1 -1
- package/dist/geml.d.ts +32 -0
- package/dist/geml.js +172 -2038
- package/dist/history.js +7 -3
- package/dist/mcp.js +46 -8
- package/dist/render-html.d.ts +1 -1
- package/dist/render.d.ts +1 -1
- package/dist/render.js +180 -15
- package/dist/selector.d.ts +7 -0
- package/dist/selector.js +41 -1
- package/package.json +67 -67
- package/skill/SKILL.md +25 -0
- package/skill/references/authoring.geml +6 -1
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2433 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The GEML command line. Split out of geml.ts so that file can be what the
|
|
3
|
+
// viewer imports: a parser LIBRARY. Everything CLI-side lives here — argv
|
|
4
|
+
// dispatch, the verbs, file and stdin I/O, spawning `codemap`/`mcp`, and
|
|
5
|
+
// `skill install`. The browser bundle never reaches this module, so a new
|
|
6
|
+
// node:* import here can no longer break the extension build (it did three
|
|
7
|
+
// times in one day: node:os for homedir, pageAssets, renameSync).
|
|
8
|
+
import { readFileSync, writeFileSync, realpathSync, statSync, existsSync, mkdirSync, readdirSync, copyFileSync, renameSync } from "node:fs";
|
|
9
|
+
import { basename, dirname, isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { spawnSync } from "node:child_process";
|
|
13
|
+
import { PARSER_VERSION, VERSION, EMBED_DEPTH_LIMIT, FENCE_OPEN, parse, blockSpans, sliceUnit, addressedUnits, relJoinPath, relDirPath, closeFenceLine, findBlockSite, historyPathFor, isCloseFence, narrowToHead, newlineOf, narrowToIntro, reLit, sectionEndIndex, splitLines, stripEol, toLf, toNewline, trimSpaceTabEnd, } from "./geml.js";
|
|
14
|
+
import { schemeOf } from "./inline.js";
|
|
15
|
+
import { parseAttrs } from "./attrs.js";
|
|
16
|
+
import { save, restore, verify, isCurrent, listRevisions, resolveContent, firstChangedContent } from "./history.js";
|
|
17
|
+
import { renderHtml } from "./render-html.js";
|
|
18
|
+
import { normalizeBlockId } from "./block-edit.js";
|
|
19
|
+
import { discoveryHint, matchContent, matchLine, matchType, parseSelector, shortestAddress } from "./selector.js";
|
|
20
|
+
import { mdToGeml } from "./from-md.js";
|
|
21
|
+
import { serialize } from "./serialize.js";
|
|
22
|
+
import { gemlToMd } from "./to-md.js";
|
|
23
|
+
// A chain that cannot reach an entity block. Carries the diagnostic code it
|
|
24
|
+
// corresponds to (§3) so the message can name it without inventing a new one.
|
|
25
|
+
class ViewError extends Error {
|
|
26
|
+
code;
|
|
27
|
+
constructor(code, message) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.code = code;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
// Walking a chain is DOCUMENT-DRIVEN file access: `src=` comes from file
|
|
33
|
+
// content, so without a confinement root a document could name any path on the
|
|
34
|
+
// machine. And never a URL — `geml get` is a read command that agents and
|
|
35
|
+
// editors call constantly, so letting content steer it at the network would turn
|
|
36
|
+
// it into an SSRF entry point (§3.1). Both refusals reuse existing codes (§3).
|
|
37
|
+
function readConfined(rel, root) {
|
|
38
|
+
if (!/\.geml$/i.test(rel)) {
|
|
39
|
+
throw new ViewError("embed-target-not-geml", `embed-target-not-geml: \`${rel}\` is not a \`.geml\` document`);
|
|
40
|
+
}
|
|
41
|
+
const base = resolvePath(root);
|
|
42
|
+
const abs = resolvePath(root, rel);
|
|
43
|
+
if (abs !== base && !abs.startsWith(base + sep)) {
|
|
44
|
+
throw new ViewError("unresolvable-document", `unresolvable-document: \`${rel}\` lies outside the confinement root \`${root}\``);
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
return readFileSync(abs, "utf8");
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new ViewError("unresolvable-document", `unresolvable-document: cannot resolve \`${rel}\``);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// One hop: read the target document and select what the fragment names. Several
|
|
54
|
+
// units come back when the fragment names a section (§4.3).
|
|
55
|
+
function oneHop(file, src, root) {
|
|
56
|
+
const hash = src.indexOf("#");
|
|
57
|
+
const docPath = hash < 0 ? src : src.slice(0, hash);
|
|
58
|
+
const frag = hash < 0 ? undefined : src.slice(hash + 1);
|
|
59
|
+
// Check the scheme on what the DOCUMENT wrote, before composition: a URL can
|
|
60
|
+
// only arrive through `src=`, never from joining relative paths — and testing
|
|
61
|
+
// the composed path instead would read a Windows drive letter (`C:/…`) as a
|
|
62
|
+
// scheme and refuse every absolute path, which is exactly what the MCP layer
|
|
63
|
+
// hands the CLI.
|
|
64
|
+
if (schemeOf(docPath) !== null) {
|
|
65
|
+
throw new ViewError("unchecked-cross-document-reference", `unchecked-cross-document-reference: \`${docPath}\` is not local; \`--view\` never fetches over the network`);
|
|
66
|
+
}
|
|
67
|
+
const rel = relJoinPath(relDirPath(file), docPath);
|
|
68
|
+
const text = readConfined(rel, root);
|
|
69
|
+
if (frag === undefined) {
|
|
70
|
+
// `src=other.geml`: the frame looks onto the WHOLE document. Every block
|
|
71
|
+
// comes from the same target, so the resolution base stays uniform — unlike
|
|
72
|
+
// a host-side section selector, where splicing would mix two documents.
|
|
73
|
+
// `meta` is frontmatter, not content (render.ts's selectEmbed).
|
|
74
|
+
//
|
|
75
|
+
// Only TOP-LEVEL units: a heading's unit spans its whole section, so taking
|
|
76
|
+
// every addressed unit would emit the blocks inside a section twice.
|
|
77
|
+
const every = addressedUnits(text).map((a) => a.unit);
|
|
78
|
+
const top = every.filter((u) => !every.some((o) => o !== u && o.span.start <= u.span.start && o.span.end >= u.span.end
|
|
79
|
+
&& (o.span.start < u.span.start || o.span.end > u.span.end)));
|
|
80
|
+
return { doc: rel, text, units: top.filter((u) => !(u.kind === "block" && u.type === "meta")), all: [], from: shownPath(rel, root) };
|
|
81
|
+
}
|
|
82
|
+
const { units, all } = selectUnits(text, rel, `#${frag}`, rel);
|
|
83
|
+
return { doc: rel, text, units, all, from: `${shownPath(rel, root)}#${frag}` };
|
|
84
|
+
}
|
|
85
|
+
// Provenance is stated relative to the confinement root, not as the path the
|
|
86
|
+
// walk happens to have composed. The MCP layer hands the CLI an ABSOLUTE path,
|
|
87
|
+
// so without this `from` would be `C:/Users/…/part.geml#tip` — leaking the
|
|
88
|
+
// server's layout, and not a path any caller could pass back in.
|
|
89
|
+
function shownPath(rel, root) {
|
|
90
|
+
const r = relative(root, rel).replace(/\\/g, "/");
|
|
91
|
+
return r === "" ? rel : r;
|
|
92
|
+
}
|
|
93
|
+
function viewResolve(source, file, unit, root, depth = 0, seen = new Set()) {
|
|
94
|
+
const src = unit.kind === "block" && unit.type === "embed" ? embedSrcOf(source, unit) : undefined;
|
|
95
|
+
if (src === undefined)
|
|
96
|
+
return [{ doc: file, text: source, unit, all: [], from: "" }];
|
|
97
|
+
// The renderer expands no deeper either (EMBED_DEPTH_LIMIT), but where the
|
|
98
|
+
// cycle detector may stop SILENTLY — a 9-deep chain is legal and simply is
|
|
99
|
+
// not expanded — `--view` may not: stopping here means what we are holding is
|
|
100
|
+
// still a frame, and returning it would break the contract silently.
|
|
101
|
+
if (depth >= EMBED_DEPTH_LIMIT) {
|
|
102
|
+
throw new ViewError("depth", `chain still not on an entity block after ${EMBED_DEPTH_LIMIT} hops (the renderer expands no deeper either)`);
|
|
103
|
+
}
|
|
104
|
+
const hop = oneHop(file, src, root);
|
|
105
|
+
// Same key shape as the check's cycle detector: a document plus what was
|
|
106
|
+
// selected in it.
|
|
107
|
+
const key = `${hop.doc}#${hop.units.map((u) => u.id ?? "").join(",")}`;
|
|
108
|
+
if (seen.has(key)) {
|
|
109
|
+
throw new ViewError("transclusion-cycle", `transclusion-cycle: \`${hop.from}\` is already being expanded in this chain`);
|
|
110
|
+
}
|
|
111
|
+
const nextSeen = new Set(seen).add(key);
|
|
112
|
+
// Per-unit application, recursively: what a frame looks onto may itself be a
|
|
113
|
+
// frame, and a section may hold a mix (§4.3).
|
|
114
|
+
return hop.units.flatMap((u) => viewResolve(hop.text, hop.doc, u, root, depth + 1, nextSeen)
|
|
115
|
+
// An inner identity step has no provenance of its own, so carry this hop's:
|
|
116
|
+
// `from` must always name where the bytes actually came from.
|
|
117
|
+
.map((r) => (r.from === "" ? { ...r, from: hop.from } : r)));
|
|
118
|
+
}
|
|
119
|
+
// The `src=` of an embed unit, read off its head line: a Unit carries the span,
|
|
120
|
+
// not parsed attributes.
|
|
121
|
+
function embedSrcOf(source, unit) {
|
|
122
|
+
const braces = /\{[^}]*\}/.exec(sliceUnit(source, unit.span, "head"));
|
|
123
|
+
if (!braces)
|
|
124
|
+
return undefined;
|
|
125
|
+
const v = parseAttrs(braces[0]).attrs["src"];
|
|
126
|
+
return typeof v === "string" ? v : undefined;
|
|
127
|
+
}
|
|
128
|
+
const USAGE = `geml — GEML reference CLI
|
|
129
|
+
|
|
130
|
+
Usage:
|
|
131
|
+
geml <file.geml|-> [--to <fmt>] [--from <fmt>] [--root d] [-o out] transform a document (default: --to json)
|
|
132
|
+
(--root widens cross-doc resolution to dir d, as on check — an
|
|
133
|
+
=== embed whose target sits above the file's own directory
|
|
134
|
+
needs it, or it renders unresolved)
|
|
135
|
+
--to <output>: json | html | md | geml
|
|
136
|
+
--to md -> Markdown (lossy)
|
|
137
|
+
--to html -> self-contained HTML
|
|
138
|
+
--to html --fragment -> body-only markup, no page shell
|
|
139
|
+
(embed in your own layout; assets via pageAssets)
|
|
140
|
+
--to geml -> canonical re-format
|
|
141
|
+
--to json -> document-model JSON (default)
|
|
142
|
+
--from <input>: geml | md | json (overrides extension; html is output-only)
|
|
143
|
+
geml notes.md -> GEML (md inferred from extension)
|
|
144
|
+
geml model.json --to geml -> GEML (round-trips a prior --to json)
|
|
145
|
+
geml - --from md read Markdown on stdin
|
|
146
|
+
geml list <file.geml|-> [--json] list every addressable block: address, kind, lines
|
|
147
|
+
(call this first — its addresses are what every verb below takes)
|
|
148
|
+
geml find <pattern> [<file|dir> …] [--json] [--case] [--head] search block content -> file#address
|
|
149
|
+
(an address, not a line number, so a hit pastes into get/set;
|
|
150
|
+
a dir is walked for *.geml; exit 1 when nothing matched)
|
|
151
|
+
geml get <file.geml|-> [#id] [--json] [--head|--intro|--body] with #id: print that block
|
|
152
|
+
(a heading id = its whole section; --head = head line;
|
|
153
|
+
--json = model node). Without #id: list all addressable
|
|
154
|
+
ids (--json = array). A selector may also be a POSITION,
|
|
155
|
+
'L27' or 'L27-58' — the smallest block containing those
|
|
156
|
+
lines, which is how a grep hit or a stack trace becomes
|
|
157
|
+
an address.
|
|
158
|
+
geml set <file.geml|-> #id [--head|--intro|--body] [--in f[#src]|-] [-o f] replace ONE block by id
|
|
159
|
+
(--in F takes F's block #id, F#src takes #src, else stdin raw;
|
|
160
|
+
default = whole block · --head = head line · --body = body)
|
|
161
|
+
geml add <file.geml|-> (--append | --before #id | --after #id) [--in f[#src]|-] [-o f] insert a fragment
|
|
162
|
+
(1+ blocks and/or prose; content keeps its own ids, a clash is refused)
|
|
163
|
+
geml delete <file.geml|-> #id [#id2 …] [-o f] remove one or more blocks
|
|
164
|
+
(a missing id is skipped; a dangling reference is a warning, not a refusal)
|
|
165
|
+
geml rename <file.geml|-> #old #new [-o f] rename an id and every reference to it (id-boundary safe)
|
|
166
|
+
geml revert <file.geml> #id [--rev <sel>] [--head] undo one block to a past revision (splice / resurrect / remove)
|
|
167
|
+
(sel: 0 | -N | id-prefix | changed; default -1)
|
|
168
|
+
geml check <file.geml|-> [--root d] [--json] validate only: diagnostics + exit code
|
|
169
|
+
(--root widens cross-doc refs to dir d, e.g. the repo root)
|
|
170
|
+
geml history <save|get|restore|verify> <file.geml> [...] .gemlhistory version sidecar
|
|
171
|
+
(save = append the file as a revision · get = list revisions, or
|
|
172
|
+
print one · restore = overwrite the file with one · verify = rebuild
|
|
173
|
+
and re-hash the whole chain)
|
|
174
|
+
geml codemap <build|verify|render|serve|refresh|find> [...] code-graph toolkit (alias: codegraph)
|
|
175
|
+
geml mcp --root <dir> [--graph <dir>] [--no-history] serve documents (and the code graph) over MCP (stdio)
|
|
176
|
+
(10 tools, each geml_ + its CLI command path: list/get/check/history/to +
|
|
177
|
+
set/add/delete/rename/revert; every write is validated before it
|
|
178
|
+
reaches disk. A code graph under --root adds four read-only
|
|
179
|
+
geml_codemap_* tools to the same server)
|
|
180
|
+
geml skill install [--dest <dir>] [--no-global] [--no-mcp] set up GEML for Claude Code, user-global
|
|
181
|
+
(authoring skill -> ~/.claude/skills/geml, CLI -> npm i -g,
|
|
182
|
+
MCP server registered at user scope; touches no settings.json,
|
|
183
|
+
installs no hooks; idempotent — re-run to update)
|
|
184
|
+
geml --help | --version [--json]
|
|
185
|
+
|
|
186
|
+
Use '-' as the file to read from stdin.
|
|
187
|
+
Mutations (set/add/delete/rename) write the whole updated document in place for a
|
|
188
|
+
file, or to stdout for '-' input; -o redirects it (-o - = stdout).
|
|
189
|
+
Exit codes:
|
|
190
|
+
0 ok
|
|
191
|
+
1 document/operation error
|
|
192
|
+
2 command usage error.
|
|
193
|
+
`;
|
|
194
|
+
// One-line usage for each subcommand — the single source for both the error
|
|
195
|
+
// shown on misuse and the `<cmd> --help` text.
|
|
196
|
+
const SUBHELP = {
|
|
197
|
+
get: "usage: geml get <file.geml|-> [<selector>] [--head|--intro|--body] [--view [--root <dir>]] [--json] (selector = a filter over blocks: #id | '## Heading' (its whole section) | '=== type' (every block of that type — N matches print N contents, count on stderr) | '=== type@<hex>[~n]' or '@<hex>[~n]' (content address, for blocks with no #id) | L<n> or L<n>-<m> (position — the smallest block that fully contains those lines, so the `L27-58` the listing prints pastes straight back, and a line number from an editor, a linter or a diff hunk becomes a block); a section cuts three ways — --head = the heading line, --intro = its opening region: everything under it up to its FIRST SUBHEADING (empty when one follows immediately, the whole body when none does; a block has no intro and is refused), --body = everything under it; --view = read THROUGH an `embed` to the entity block it stands for, following a chain to its end (the identity on any other block, and on a section selector — it never splices two documents' bytes together); provenance goes to stderr as `view: <sel> -> <doc>[#<id>]`; read-only, `set` refuses it; chain reads are confined to --root (default: the document's own directory) and never fetched over the network; without a selector: list every addressable block with its shortest unique address, --json = array)",
|
|
198
|
+
set: "usage: geml set <file.geml|-> <selector> [--head|--intro|--body] [--in F | --in F#src | --in -] [-o out.geml] (selector as in `get`, but it must match exactly ONE block — '=== type' matching several is refused; content: --in F takes F's block #id, --in F#src takes #src, else stdin raw; default = whole block, --head = head line — both normalize the id when the target has one — --body = body, --intro = a heading's opening region up to its first subheading (an empty region INSERTS there); guarded splice, refused if it breaks the doc — but a replacement that REMOVES blocks is carried out and reported on stderr, named ones and unnamed alike, with `geml revert` as the way back (the same stance `delete` takes; the ordinary read-edit-write cycle removes nothing, since `get` handed those blocks over); writing through an @<hex> address prints the new address on stderr)",
|
|
199
|
+
add: "usage: geml add <file.geml|-> (--append | --before #id | --after #id) [--in F | --in F#src | --in -] [-o out.geml] (insert a GEML fragment — 1+ blocks and/or prose — at a position; --in F takes all of F, --in F#src takes #src, else stdin raw; content keeps its own ids, a collision is refused)",
|
|
200
|
+
delete: "usage: geml delete <file.geml|-> #id [#id2 …] [-o out.geml] (remove one or more blocks; a missing id is skipped with a note, not an error; a reference left dangling is a warning, not a refusal — delete never fails on a live reference)",
|
|
201
|
+
rename: "usage: geml rename <file.geml|-> #old #new [-o out.geml] (rewrite an id's declaration AND every reference — [[#id]], [text](#id), chart data=#id, footnote [^id] — id-boundary safe, skipping raw block bodies; #new must be free; refused if it breaks the doc)",
|
|
202
|
+
list: "usage: geml list <file.geml|-> [--json] (list every addressable block with its shortest unique address, its kind and its line range — the same listing `geml get <file>` prints with no selector, under the name the MCP surface already uses. Call it FIRST: the addresses it prints are what get/set/add/delete/rename/revert all take)",
|
|
203
|
+
find: "usage: geml find <pattern> [<file.geml|dir> …] [--json] [--case] [--head] (search block CONTENT and print `<file>TAB<address>` per hit — an address, never a line number, so a hit is `geml get <file> '<address>'` with no editing. The address is the INNERMOST block holding the match, never its enclosing section, and a block is reported once however many lines in it matched. Substring, case-insensitive unless --case; a directory is walked for *.geml; no path = the current directory; --head adds the matching line as a third column. Exit 1 when nothing matched, so `if geml find …` works in a script)",
|
|
204
|
+
check: "usage: geml check <file.geml|-> [--root <dir>] [--json] (--root: resolve cross-doc refs within <dir> instead of the file's own directory)",
|
|
205
|
+
revert: "usage: geml revert <file.geml> #id [--rev <sel>] [--append|--before #x|--after #x] [--head] [--dry-run] [-o out] (reconcile #id to a revision: splice / resurrect / remove; sel: 0 | -N | id-prefix | changed; default -1)",
|
|
206
|
+
history: `usage: geml history save <file.geml> [-m <msg>] append the working file as a new revision (identical to the tip = no-op)
|
|
207
|
+
geml history get <file.geml> [<rev>] [--json] NO <rev>: every revision, newest first, first column = the selector; WITH <rev>: that revision's full text
|
|
208
|
+
geml history restore <file.geml> <rev> [--force] overwrite the working file with a revision (--force discards unsaved changes)
|
|
209
|
+
geml history verify <file.geml> rebuild and re-hash every revision in the chain
|
|
210
|
+
(<rev>: 0 = the tip | -N = N revisions back | an unambiguous revision id — the strings 'get' prints.
|
|
211
|
+
All four take --history <path> to point at a sidecar other than <file>.gemlhistory.)`,
|
|
212
|
+
codemap: `usage: geml codemap build [--root <repo>] # auto-detect languages, run the indexer(s), and merge into one codemap (--root defaults to the current directory)
|
|
213
|
+
geml codemap build (--db <graph.db> | --adapter joern|scip --raw <in>)+ [--root <repo>] [--out .geml-code-graph] [--container module|dir|file] [--lang <JAVASRC|NEWC|…>] [--joern <path>] [--history [-m msg]]
|
|
214
|
+
geml codemap verify [dir] geml check + profile reference checks
|
|
215
|
+
geml codemap render [dir] every doc -> sibling .html (open index.html from disk)
|
|
216
|
+
geml codemap serve [dir] [--port 8140] [--watch] [--background|--stop] live viewer: pages render from .geml on request; --watch re-runs the recipe when sources change
|
|
217
|
+
geml codemap refresh [dir] [--force] [--commit] [--background|--hook] re-run the recorded build recipe (_index/refresh.json); --commit lands it as its own commit
|
|
218
|
+
geml codemap find <name> [dir] locate a symbol by substring name -> doc#id + src (stdout, no browser)
|
|
219
|
+
(<dir> for verify/render/serve/refresh/find defaults to ./.geml-code-graph; codegraph and code-graph are accepted as aliases of codemap)`,
|
|
220
|
+
mcp: `usage: geml mcp --root <dir> [--graph <dir>] [--no-history]
|
|
221
|
+
|
|
222
|
+
Serve GEML document CRUD over the MCP stdio transport (JSON-RPC 2.0).
|
|
223
|
+
Every tool is geml_ + its CLI COMMAND PATH, so the terminal and the assistant
|
|
224
|
+
share one vocabulary — geml_history mirrors the "geml history" command group,
|
|
225
|
+
whose read verb (get) is the only one of the four served here.
|
|
226
|
+
Eleven tools: geml_list · geml_find · geml_get · geml_check · geml_history
|
|
227
|
+
geml_to · geml_set · geml_add · geml_delete · geml_rename
|
|
228
|
+
geml_revert
|
|
229
|
+
With a code graph under --root, four more (read-only), so one client entry
|
|
230
|
+
covers both: geml_codemap_search · geml_codemap_callchain
|
|
231
|
+
geml_codemap_list · geml_codemap_node
|
|
232
|
+
|
|
233
|
+
--root <dir> REQUIRED. Root holding the .geml documents. Every path a
|
|
234
|
+
client names is confined here; a client cannot widen it.
|
|
235
|
+
--graph <dir> Code-graph directory, inside --root. Defaults to
|
|
236
|
+
<root>/.geml-code-graph when it holds an index.geml; with
|
|
237
|
+
no graph the four graph tools are not served at all.
|
|
238
|
+
--no-history Skip the .gemlhistory revision saved before each write
|
|
239
|
+
(default: save one, so geml_revert always has a revision
|
|
240
|
+
to undo to).
|
|
241
|
+
|
|
242
|
+
Register with a client:
|
|
243
|
+
claude mcp add geml -- geml mcp --root /abs/path/to/repo`,
|
|
244
|
+
skill: `usage: geml skill install [--dest <skillsDir>] [--no-global] [--no-mcp] [--dry-run]
|
|
245
|
+
|
|
246
|
+
One command, three things, all user-global — so any Claude Code session can
|
|
247
|
+
author, validate, and blockwise-edit GEML:
|
|
248
|
+
1. the authoring skill -> <skillsDir>/geml (default ~/.claude/skills/geml)
|
|
249
|
+
2. the geml CLI -> npm i -g @geml/geml (skipped when already on PATH)
|
|
250
|
+
3. the MCP server -> claude mcp add --scope user geml -- npx -y @geml/geml mcp --root .
|
|
251
|
+
Touches no settings.json and installs no hooks. Idempotent — re-run after an
|
|
252
|
+
upgrade to refresh the skill text alongside the CLI it teaches.
|
|
253
|
+
|
|
254
|
+
--dest <dir> install the skill under <dir> instead of ~/.claude/skills
|
|
255
|
+
--no-global skip the global npm install
|
|
256
|
+
--no-mcp skip the MCP server registration
|
|
257
|
+
--dry-run report what would be written, change nothing
|
|
258
|
+
|
|
259
|
+
Other agent tools are installed by DETECTION: a tool's own context file gets
|
|
260
|
+
the skill text inside a marker pair (refreshed on a re-run, nothing else in
|
|
261
|
+
the file touched) when its directory is already there — ~/.gemini, ~/.qwen,
|
|
262
|
+
and an AGENTS.md in the current project. A tool that is not installed is
|
|
263
|
+
skipped and named; no tool directory is ever created for you.`,
|
|
264
|
+
};
|
|
265
|
+
// Set from argv at dispatch time; when true, errors are emitted as a JSON
|
|
266
|
+
// envelope so an agent that standardizes on --json never has to parse text.
|
|
267
|
+
let jsonMode = false;
|
|
268
|
+
// Clean one-line error + non-zero exit — never a raw Node stack trace. `code`
|
|
269
|
+
// is the process exit status: 2 for a usage error (the default), 1 for a
|
|
270
|
+
// document/operation error. `--json` wraps it in the same {error, code} envelope.
|
|
271
|
+
function fail(msg, code = 2) {
|
|
272
|
+
if (jsonMode)
|
|
273
|
+
console.error(JSON.stringify({ error: msg, code }));
|
|
274
|
+
else
|
|
275
|
+
console.error(`error: ${msg}`);
|
|
276
|
+
process.exit(code);
|
|
277
|
+
}
|
|
278
|
+
// Refuse a mutation whose RESULT would be broken (the pre-write check every
|
|
279
|
+
// mutation runs). Prose mode is the long-standing wording: the first error,
|
|
280
|
+
// phrased by the call site. `--json` additionally carries the FULL diagnostic
|
|
281
|
+
// list with the stable codes of spec Appendix A, so a programmatic caller —
|
|
282
|
+
// `geml mcp` above all — reports what actually broke instead of re-parsing
|
|
283
|
+
// English out of stderr.
|
|
284
|
+
function refuseBroken(prose, errs) {
|
|
285
|
+
if (jsonMode) {
|
|
286
|
+
console.error(JSON.stringify({ error: prose, code: 1, diagnostics: errs }));
|
|
287
|
+
process.exit(1);
|
|
288
|
+
}
|
|
289
|
+
fail(prose, 1);
|
|
290
|
+
}
|
|
291
|
+
// Read a file, or stdin when the path is "-". On failure emit a clean error.
|
|
292
|
+
function readInput(file) {
|
|
293
|
+
try {
|
|
294
|
+
return readFileSync(file === "-" ? 0 : file, "utf8");
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
fail(file === "-" ? "cannot read stdin" : `cannot read ${file}`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
// A cross-document resolver rooted at the input's directory (cwd for stdin),
|
|
301
|
+
// CONFINED to that directory's subtree. A reference that resolves outside the
|
|
302
|
+
// base — via a `..` escape, an absolute path, or (on Windows) a different drive
|
|
303
|
+
// — is refused (returns null, i.e. an unresolvable ref) so a crafted document
|
|
304
|
+
// cannot turn `geml check`/parse into an arbitrary local-file read oracle. §8.
|
|
305
|
+
//
|
|
306
|
+
// A purely LEXICAL check is not enough: a symlink that sits lexically inside the
|
|
307
|
+
// subtree but points to `../../outside.geml` passes `path.relative` yet reads an
|
|
308
|
+
// external target. So after the cheap lexical gate we resolve BOTH the base and
|
|
309
|
+
// the target through `realpathSync` (following every symlink component) and
|
|
310
|
+
// re-check that the REAL target still lies within the REAL base subtree before
|
|
311
|
+
// reading. A target that does not exist makes `realpathSync` throw — handled as
|
|
312
|
+
// an ordinary unresolvable ref (null), never a crash.
|
|
313
|
+
//
|
|
314
|
+
// `root` (CLI `--root`, an explicit per-invocation user grant — never
|
|
315
|
+
// document-controlled) widens the confinement base from the input's own
|
|
316
|
+
// directory to an ancestor the user names, so repo-relative `../` references
|
|
317
|
+
// between sibling directories can be checked. It moves WHERE the boundary
|
|
318
|
+
// stands, never whether it is enforced: both gates below run against the
|
|
319
|
+
// widened base, so escapes past the root are refused exactly as above. The
|
|
320
|
+
// viewer/web surfaces never pass a root — their boundary is unchanged.
|
|
321
|
+
function resolverFor(file, root) {
|
|
322
|
+
const dirAbs = resolvePath(file === "-" ? "." : dirname(file));
|
|
323
|
+
const baseAbs = root === undefined ? dirAbs : resolvePath(root);
|
|
324
|
+
// Canonicalise the base once. If the base itself cannot be realpath'd, no
|
|
325
|
+
// cross-doc ref can be safely confined — resolve nothing.
|
|
326
|
+
let realBase = null;
|
|
327
|
+
try {
|
|
328
|
+
realBase = realpathSync(baseAbs);
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
realBase = null;
|
|
332
|
+
}
|
|
333
|
+
const outside = (from, to) => {
|
|
334
|
+
const rel = relative(from, to);
|
|
335
|
+
return rel === ".." || rel.startsWith(".." + sep) || isAbsolute(rel);
|
|
336
|
+
};
|
|
337
|
+
return (d) => {
|
|
338
|
+
if (realBase === null)
|
|
339
|
+
return null;
|
|
340
|
+
// References resolve FROM the document's own directory; the gates below
|
|
341
|
+
// confine them to the (possibly widened) base.
|
|
342
|
+
let targetAbs = resolvePath(dirAbs, d);
|
|
343
|
+
// A SOURCE route (`code`/`data` `src=`) may instead be written relative to
|
|
344
|
+
// the resolution root — that is how the code-graph profile writes them
|
|
345
|
+
// (`geml-parser/src/attrs.ts` from a document two levels down). So when
|
|
346
|
+
// the document-relative path does not exist and a root was named, try the
|
|
347
|
+
// root as the base. Only a widened `--root` can enable this, and both
|
|
348
|
+
// confinement gates below still apply, so it cannot reach further than a
|
|
349
|
+
// document-relative reference already could.
|
|
350
|
+
if (baseAbs !== dirAbs && !existsSync(targetAbs)) {
|
|
351
|
+
const fromBase = resolvePath(baseAbs, d);
|
|
352
|
+
if (existsSync(fromBase))
|
|
353
|
+
targetAbs = fromBase;
|
|
354
|
+
}
|
|
355
|
+
// Cheap lexical gate: reject an obvious `..`/absolute/other-drive escape
|
|
356
|
+
// before touching the filesystem.
|
|
357
|
+
if (outside(baseAbs, targetAbs))
|
|
358
|
+
return null;
|
|
359
|
+
// Real (symlink-resolved) gate: a symlink pointing out of the subtree
|
|
360
|
+
// resolves to a real path outside `realBase` and is refused here.
|
|
361
|
+
let realTarget;
|
|
362
|
+
try {
|
|
363
|
+
realTarget = realpathSync(targetAbs);
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
return null;
|
|
367
|
+
}
|
|
368
|
+
if (outside(realBase, realTarget))
|
|
369
|
+
return null;
|
|
370
|
+
try {
|
|
371
|
+
return readFileSync(realTarget, "utf8");
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
// The existence half of the same question, behind the SAME gates. A link may
|
|
379
|
+
// point at a directory — `[the extension](integrations/vscode/)` — which has no
|
|
380
|
+
// text for `resolverFor` to return but is not a broken link. Answering this
|
|
381
|
+
// outside the confinement root would turn link checking into a probe for what
|
|
382
|
+
// exists on the machine, so every gate above is repeated rather than skipped.
|
|
383
|
+
function existsFor(file, root) {
|
|
384
|
+
const read = resolverFor(file, root);
|
|
385
|
+
const dirAbs = resolvePath(file === "-" ? "." : dirname(file));
|
|
386
|
+
const baseAbs = root === undefined ? dirAbs : resolvePath(root);
|
|
387
|
+
let realBase = null;
|
|
388
|
+
try {
|
|
389
|
+
realBase = realpathSync(baseAbs);
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
realBase = null;
|
|
393
|
+
}
|
|
394
|
+
const outside = (from, to) => {
|
|
395
|
+
const rel = relative(from, to);
|
|
396
|
+
return rel === ".." || rel.startsWith(".." + sep) || isAbsolute(rel);
|
|
397
|
+
};
|
|
398
|
+
return (d) => {
|
|
399
|
+
if (realBase === null)
|
|
400
|
+
return false;
|
|
401
|
+
// Readable already means it exists; this only has to answer for the rest.
|
|
402
|
+
if (read(d) !== null)
|
|
403
|
+
return true;
|
|
404
|
+
let targetAbs = resolvePath(dirAbs, d);
|
|
405
|
+
if (baseAbs !== dirAbs && !existsSync(targetAbs)) {
|
|
406
|
+
const fromBase = resolvePath(baseAbs, d);
|
|
407
|
+
if (existsSync(fromBase))
|
|
408
|
+
targetAbs = fromBase;
|
|
409
|
+
}
|
|
410
|
+
if (outside(baseAbs, targetAbs))
|
|
411
|
+
return false;
|
|
412
|
+
let realTarget;
|
|
413
|
+
try {
|
|
414
|
+
realTarget = realpathSync(targetAbs);
|
|
415
|
+
}
|
|
416
|
+
catch {
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
419
|
+
if (outside(realBase, realTarget))
|
|
420
|
+
return false;
|
|
421
|
+
return existsSync(realTarget);
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
// Both halves for a parse: every call site wants them together, and pairing
|
|
425
|
+
// them here keeps a resolver from being wired up without its existence probe.
|
|
426
|
+
function docOpts(file, root) {
|
|
427
|
+
return { resolveDoc: resolverFor(file, root), docExists: existsFor(file, root) };
|
|
428
|
+
}
|
|
429
|
+
// `geml check <file>` — validate only: diagnostics + exit code, no document
|
|
430
|
+
// dump (cheap for agents). `--json` prints the diagnostics array for machines.
|
|
431
|
+
function runCheck(args) {
|
|
432
|
+
const json = args.includes("--json");
|
|
433
|
+
const root = flag(args, "--root");
|
|
434
|
+
const file = args.find((a) => a === "-" || (!a.startsWith("-") && a !== root));
|
|
435
|
+
if (!file)
|
|
436
|
+
fail(SUBHELP.check);
|
|
437
|
+
// A mistyped --root must be a usage error (exit 2), not a wall of misleading
|
|
438
|
+
// "cannot resolve document" errors from a resolver confined to nothing.
|
|
439
|
+
if (root !== undefined) {
|
|
440
|
+
let isDir = false;
|
|
441
|
+
try {
|
|
442
|
+
isDir = statSync(root).isDirectory();
|
|
443
|
+
}
|
|
444
|
+
catch { /* missing -> not a dir */ }
|
|
445
|
+
if (!isDir)
|
|
446
|
+
fail(`--root ${root} is not a directory`);
|
|
447
|
+
}
|
|
448
|
+
const doc = parse(readInput(file), { ...docOpts(file, root), self: file === "-" ? undefined : basename(file) });
|
|
449
|
+
if (json) {
|
|
450
|
+
console.log(JSON.stringify(doc.diagnostics, null, 2));
|
|
451
|
+
}
|
|
452
|
+
else {
|
|
453
|
+
for (const d of doc.diagnostics)
|
|
454
|
+
console.error(`${d.severity}: ${d.message} (line ${d.line})`);
|
|
455
|
+
const errs = doc.diagnostics.filter((d) => d.severity === "error").length;
|
|
456
|
+
const warns = doc.diagnostics.filter((d) => d.severity === "warning").length;
|
|
457
|
+
console.error(errs || warns ? `${errs} error(s), ${warns} warning(s)` : "ok: no diagnostics");
|
|
458
|
+
}
|
|
459
|
+
if (doc.diagnostics.some((d) => d.severity === "error"))
|
|
460
|
+
process.exit(1);
|
|
461
|
+
}
|
|
462
|
+
// Map a thrown error from the history layer to a clean one-line message —
|
|
463
|
+
// never a raw node:fs stack trace, and without leaking the absolute path the
|
|
464
|
+
// runtime resolved (we report the relative path the user actually passed).
|
|
465
|
+
function historyError(e, file, historyPath) {
|
|
466
|
+
const err = e;
|
|
467
|
+
if (err?.code === "ENOENT") {
|
|
468
|
+
const p = err.path ?? "";
|
|
469
|
+
if (p.endsWith(basename(historyPath)))
|
|
470
|
+
return `cannot read history ${historyPath}`;
|
|
471
|
+
return `cannot read ${file}`;
|
|
472
|
+
}
|
|
473
|
+
return err?.message ?? String(e);
|
|
474
|
+
}
|
|
475
|
+
// Subcommand, file and revision, read positionally around the options —
|
|
476
|
+
// `--history <path>` and `-m <msg>` may sit anywhere, and the old args[0..2]
|
|
477
|
+
// indexing read `--history` itself as the file.
|
|
478
|
+
//
|
|
479
|
+
// The generic `positionals()` cannot be reused: it drops every `-`-leading token,
|
|
480
|
+
// and a revision selector `-N` LOOKS exactly like a flag. That is the whole point
|
|
481
|
+
// of the first column `history get` prints, so `-N` is admitted and every other
|
|
482
|
+
// `-`-leading token is treated as an option.
|
|
483
|
+
function historyPositionals(args) {
|
|
484
|
+
const out = [];
|
|
485
|
+
for (let i = 0; i < args.length; i++) {
|
|
486
|
+
const a = args[i];
|
|
487
|
+
if (a === "--history" || a === "-m" || a === "--message") {
|
|
488
|
+
i++;
|
|
489
|
+
continue;
|
|
490
|
+
} // flag AND its value
|
|
491
|
+
if (a.startsWith("-") && !/^-\d+$/.test(a))
|
|
492
|
+
continue; // --json, --force, …
|
|
493
|
+
out.push(a);
|
|
494
|
+
}
|
|
495
|
+
return out;
|
|
496
|
+
}
|
|
497
|
+
function runHistory(args) {
|
|
498
|
+
const [sub, file, rev, ...extra] = historyPositionals(args);
|
|
499
|
+
if (!sub || !file)
|
|
500
|
+
fail(SUBHELP.history);
|
|
501
|
+
const historyPath = flag(args, "--history") ?? historyPathFor(file);
|
|
502
|
+
const json = args.includes("--json");
|
|
503
|
+
try {
|
|
504
|
+
if (sub === "save") {
|
|
505
|
+
// design §3.1/§9-Q4: `--author` and `--at` were withdrawn from the CLI (nothing
|
|
506
|
+
// outside tests ever passed either). Refusing beats ignoring for the same
|
|
507
|
+
// reason the retired verbs above refuse: a silently dropped `--author
|
|
508
|
+
// alice` discards precisely the value the caller went out of their way to
|
|
509
|
+
// type. Both stay on the library API (save({ author, at })).
|
|
510
|
+
for (const gone of ["--author", "--at"]) {
|
|
511
|
+
if (args.some((a) => a === gone || a.startsWith(`${gone}=`))) {
|
|
512
|
+
fail(`${gone} is no longer accepted by 'geml history save' — the only option is -m/--message. (Both remain on the library API, save({ author, at }), for embedders and for tests that pin a revision id.)`);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
// design §3.1: an empty save is a NO-OP. `save` is the one non-idempotent verb,
|
|
516
|
+
// so an agent retrying a save it is unsure landed must not lengthen the
|
|
517
|
+
// chain by a revision with no ops. `geml mcp` already gated its
|
|
518
|
+
// pre-write snapshot on this exact predicate (mcp.ts snapshot()); this is
|
|
519
|
+
// the same `isCurrent()`, not a second hash comparison.
|
|
520
|
+
if (existsSync(historyPath) && isCurrent(historyPath, file)) {
|
|
521
|
+
console.log(`already saved as ${listRevisions(historyPath)[0].id} (no changes)`);
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
const r = save({
|
|
525
|
+
gemlPath: file,
|
|
526
|
+
historyPath,
|
|
527
|
+
summary: flag(args, "-m") ?? flag(args, "--message") ?? "",
|
|
528
|
+
});
|
|
529
|
+
console.log(`saved ${r.id}`);
|
|
530
|
+
}
|
|
531
|
+
else if (sub === "get") {
|
|
532
|
+
// Three tiers, split by how many addresses were given — the same rule the
|
|
533
|
+
// top-level `geml get` follows (design §1.2). Tier 2 takes a BLOCK
|
|
534
|
+
// selector inside the revision and reuses the top-level grammar verbatim
|
|
535
|
+
// (§10.1): a revision rebuilt is just a document's text, so there is no
|
|
536
|
+
// new algorithm here, and the two selector namespaces cannot collide —
|
|
537
|
+
// position is fixed and the lexis does not overlap (§10.2).
|
|
538
|
+
if (extra.length > 1) {
|
|
539
|
+
fail(`history get takes ONE revision selector and ONE block selector; got ${extra.length + 1} positionals after the file`, 2);
|
|
540
|
+
}
|
|
541
|
+
if (rev === undefined) {
|
|
542
|
+
// Newest-first, with each row's selector in the first column (`0` for
|
|
543
|
+
// the tip, then `-1`, `-2`, …) so the output is copy-paste into `get`,
|
|
544
|
+
// `restore` and `revert --rev` alike.
|
|
545
|
+
const revs = listRevisions(historyPath);
|
|
546
|
+
if (json) {
|
|
547
|
+
console.log(JSON.stringify(revs, null, 2));
|
|
548
|
+
}
|
|
549
|
+
else {
|
|
550
|
+
for (const r of revs) {
|
|
551
|
+
const sel = r.current ? "0" : `-${r.offset}`;
|
|
552
|
+
console.log(`${sel.padEnd(7)} ${r.id} ${r.author ?? "-"} ${r.summary ?? ""}`.trimEnd());
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
else {
|
|
557
|
+
// resolveContent() routes through the ONE selector grammar
|
|
558
|
+
// (resolveRevision) that the list above prints — see its comment for
|
|
559
|
+
// what happened the last time that was written twice.
|
|
560
|
+
const { id, text } = resolveContent(historyPath, rev);
|
|
561
|
+
const blockSel = extra[0];
|
|
562
|
+
if (blockSel === undefined) {
|
|
563
|
+
if (json)
|
|
564
|
+
console.log(JSON.stringify({ id, text }, null, 2));
|
|
565
|
+
else
|
|
566
|
+
process.stdout.write(text);
|
|
567
|
+
}
|
|
568
|
+
else {
|
|
569
|
+
// Tier 2 (§10.1). Cardinality and the flag rules are the top-level
|
|
570
|
+
// ones, checked here because this tier has its own argument list.
|
|
571
|
+
const headOnly = args.includes("--head");
|
|
572
|
+
const bodyOnly = args.includes("--body");
|
|
573
|
+
const introOnly = args.includes("--intro");
|
|
574
|
+
const named = [headOnly && "--head", introOnly && "--intro", bodyOnly && "--body"].filter(Boolean);
|
|
575
|
+
const part = headOnly ? "head" : bodyOnly ? "body" : introOnly ? "intro" : "whole";
|
|
576
|
+
if (named.length > 1)
|
|
577
|
+
fail(`${named.join(" and ")} are mutually exclusive — they name different parts of one block`, 2);
|
|
578
|
+
if (json && named.length > 0) {
|
|
579
|
+
fail(`--json cannot be combined with ${named[0]} — --json returns the model node, which has no sub-node for one part of a block`, 2);
|
|
580
|
+
}
|
|
581
|
+
const { units, all } = selectUnits(text, file, blockSel, `revision ${id}`);
|
|
582
|
+
if (json) {
|
|
583
|
+
// §3.2's tier table: the revision id travels with the block, so the
|
|
584
|
+
// caller can tell WHICH version it is holding.
|
|
585
|
+
const nodes = units.map((u) => unitNode(text, file, u, all));
|
|
586
|
+
console.log(JSON.stringify({ id, block: units.length === 1 ? nodes[0] : nodes }, null, 2));
|
|
587
|
+
}
|
|
588
|
+
else {
|
|
589
|
+
if (units.length > 1)
|
|
590
|
+
reportMatches(units[0].type ?? "", units);
|
|
591
|
+
for (const u of units)
|
|
592
|
+
process.stdout.write(sliceUnit(text, u.span, part));
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
else if (sub === "restore") {
|
|
598
|
+
if (!rev)
|
|
599
|
+
fail("usage: geml history restore <file.geml> <revision> [--force]");
|
|
600
|
+
restore({ historyPath, gemlPath: file, revision: rev, write: true, force: args.includes("--force") });
|
|
601
|
+
console.log(`restored ${file} to ${rev}`);
|
|
602
|
+
}
|
|
603
|
+
else if (sub === "verify") {
|
|
604
|
+
const res = verify(historyPath, file);
|
|
605
|
+
for (const e of res.errors)
|
|
606
|
+
console.error(`error: ${e}`);
|
|
607
|
+
for (const w of res.warnings)
|
|
608
|
+
console.error(`warning: ${w}`);
|
|
609
|
+
console.log(`verify: ${res.ok ? "OK" : "FAILED"} (${res.checked} revisions reconstructed & hashed)`);
|
|
610
|
+
if (!res.ok)
|
|
611
|
+
process.exit(1);
|
|
612
|
+
}
|
|
613
|
+
else {
|
|
614
|
+
fail(`unknown history subcommand: ${sub}. Run 'geml --help'.`);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
catch (e) {
|
|
618
|
+
fail(historyError(e, file, historyPath));
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
function runTransform(argv) {
|
|
622
|
+
const out = flag(argv, "-o") ?? flag(argv, "--out");
|
|
623
|
+
const fromRaw = flag(argv, "--from");
|
|
624
|
+
const toRaw = flag(argv, "--to");
|
|
625
|
+
// `--to html --fragment`: body-only markup for embedding in an existing
|
|
626
|
+
// layout (library parity: RenderOptions.fragment). Consumed here so it can
|
|
627
|
+
// be rejected on any other target — a discarded flag is a silent lie.
|
|
628
|
+
const fragIdx = argv.indexOf("--fragment");
|
|
629
|
+
const fragment = fragIdx >= 0;
|
|
630
|
+
if (fragment)
|
|
631
|
+
argv.splice(fragIdx, 1);
|
|
632
|
+
// Same `--root` as `check`, and for the same reason: cross-document resolution is
|
|
633
|
+
// fail-closed at the document's own directory, so a reference that climbs out of
|
|
634
|
+
// it needs the tree's root named. Without this the transform silently ignored the
|
|
635
|
+
// flag — a document whose embeds `check --root .` validated still rendered with
|
|
636
|
+
// every one of them unresolved, which reads as "transclusion does not work".
|
|
637
|
+
const root = flag(argv, "--root");
|
|
638
|
+
if (argv.includes("--root") && root === undefined)
|
|
639
|
+
fail("--root needs a directory", 2);
|
|
640
|
+
const [file] = positionals(argv, ["-o", "--out", "--from", "--to", "--root"]);
|
|
641
|
+
if (!file)
|
|
642
|
+
fail("no input file (use '-' to read from stdin)", 2);
|
|
643
|
+
// A bare `--to`/`--from` (no following value) is a mistyped flag, not a
|
|
644
|
+
// silent fall-through to the default — flag() would return undefined and we
|
|
645
|
+
// must not quietly ignore it.
|
|
646
|
+
if (argv.includes("--from") && fromRaw === undefined)
|
|
647
|
+
fail("--from needs a format (geml | md | json)", 2);
|
|
648
|
+
if (argv.includes("--to") && toRaw === undefined)
|
|
649
|
+
fail("--to needs a format (json | html | md | geml)", 2);
|
|
650
|
+
// Input format: an explicit --from wins (for any input, file or stdin), else
|
|
651
|
+
// the file extension, else GEML (covers .geml, unknown extensions, and stdin).
|
|
652
|
+
let inFmt;
|
|
653
|
+
if (fromRaw !== undefined) {
|
|
654
|
+
if (fromRaw !== "geml" && fromRaw !== "md" && fromRaw !== "json") {
|
|
655
|
+
fail(`--from: unknown input format '${fromRaw}' (want geml | md | json)`, 2);
|
|
656
|
+
}
|
|
657
|
+
inFmt = fromRaw;
|
|
658
|
+
}
|
|
659
|
+
else if (/\.(md|markdown)$/i.test(file)) {
|
|
660
|
+
inFmt = "md";
|
|
661
|
+
}
|
|
662
|
+
else if (/\.json$/i.test(file)) {
|
|
663
|
+
inFmt = "json";
|
|
664
|
+
}
|
|
665
|
+
else {
|
|
666
|
+
inFmt = "geml";
|
|
667
|
+
}
|
|
668
|
+
// Output format: an explicit --to wins, else md input -> geml, geml -> json.
|
|
669
|
+
let outFmt;
|
|
670
|
+
if (toRaw !== undefined) {
|
|
671
|
+
if (toRaw !== "json" && toRaw !== "html" && toRaw !== "md" && toRaw !== "geml") {
|
|
672
|
+
fail(`--to: unknown output format '${toRaw}' (want json | html | md | geml)`, 2);
|
|
673
|
+
}
|
|
674
|
+
outFmt = toRaw;
|
|
675
|
+
}
|
|
676
|
+
else {
|
|
677
|
+
outFmt = inFmt === "geml" ? "json" : "geml"; // geml->json; md/json->geml
|
|
678
|
+
}
|
|
679
|
+
if (fragment && outFmt !== "html")
|
|
680
|
+
fail("--fragment only applies to --to html", 2);
|
|
681
|
+
const src = readInput(file);
|
|
682
|
+
// md -> geml is a direct projection, not a parse/serialize round-trip: emit
|
|
683
|
+
// the converter's GEML verbatim (the old `convert`; no diagnostics to raise).
|
|
684
|
+
if (inFmt === "md" && outFmt === "geml") {
|
|
685
|
+
const { geml, notes } = mdToGeml(src);
|
|
686
|
+
writeOut(geml, out);
|
|
687
|
+
for (const n of notes)
|
|
688
|
+
console.error(`note: ${n}`);
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
// Otherwise load a document — a md input is converted to GEML first — and
|
|
692
|
+
// project it to the target.
|
|
693
|
+
let notes = [];
|
|
694
|
+
let doc;
|
|
695
|
+
if (inFmt === "json") {
|
|
696
|
+
doc = loadModelJson(src, file); // the inverse of `--to json`
|
|
697
|
+
}
|
|
698
|
+
else if (inFmt === "md") {
|
|
699
|
+
const conv = mdToGeml(src);
|
|
700
|
+
notes = conv.notes;
|
|
701
|
+
doc = parse(conv.geml, { ...docOpts(file, root), self: file === "-" ? undefined : basename(file) });
|
|
702
|
+
}
|
|
703
|
+
else {
|
|
704
|
+
doc = parse(src, { ...docOpts(file, root), self: file === "-" ? undefined : basename(file) });
|
|
705
|
+
}
|
|
706
|
+
let output;
|
|
707
|
+
switch (outFmt) {
|
|
708
|
+
case "json":
|
|
709
|
+
output = JSON.stringify(doc, null, 2) + "\n"; // == the former bare parse
|
|
710
|
+
break;
|
|
711
|
+
case "geml":
|
|
712
|
+
output = serialize(doc); // == the former `fmt`
|
|
713
|
+
break;
|
|
714
|
+
case "html":
|
|
715
|
+
output = renderHtml(doc, {
|
|
716
|
+
source: file === "-" ? "stdin" : basename(file),
|
|
717
|
+
fragment,
|
|
718
|
+
// geml-code-graph embeds load + parse sibling codemap docs on demand.
|
|
719
|
+
loadDoc: resolverFor(file, root),
|
|
720
|
+
parseDoc: (s) => parse(s, { ...docOpts(file, root) }),
|
|
721
|
+
});
|
|
722
|
+
break;
|
|
723
|
+
case "md": {
|
|
724
|
+
const r = gemlToMd(doc); // == the former `export`
|
|
725
|
+
notes = notes.concat(r.notes);
|
|
726
|
+
output = r.md;
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
writeOut(output, out);
|
|
731
|
+
for (const n of notes)
|
|
732
|
+
console.error(`note: ${n}`);
|
|
733
|
+
for (const d of doc.diagnostics)
|
|
734
|
+
console.error(`${d.severity}: ${d.message} (line ${d.line})`);
|
|
735
|
+
if (doc.diagnostics.some((d) => d.severity === "error"))
|
|
736
|
+
process.exit(1);
|
|
737
|
+
}
|
|
738
|
+
// Load a document-model JSON (the exact output of `--to json`) back into a
|
|
739
|
+
// Document, so `--from json --to geml` is the inverse of a prior `--to json`.
|
|
740
|
+
// The model is trusted as-is — no re-parse — so a clean round-trip is byte-stable
|
|
741
|
+
// with `--to geml`. Anything that is not a document model is refused, and any
|
|
742
|
+
// carried diagnostics are preserved (so a broken doc's JSON stays flagged).
|
|
743
|
+
function loadModelJson(src, file) {
|
|
744
|
+
let obj;
|
|
745
|
+
try {
|
|
746
|
+
obj = JSON.parse(src);
|
|
747
|
+
}
|
|
748
|
+
catch (e) {
|
|
749
|
+
fail(`--from json: ${file === "-" ? "stdin" : file} is not valid JSON (${e.message})`, 1);
|
|
750
|
+
}
|
|
751
|
+
const d = obj;
|
|
752
|
+
if (!d || typeof d !== "object" || d.kind !== "document" || !Array.isArray(d.children)) {
|
|
753
|
+
fail(`--from json: not a GEML document-model JSON (expected {"kind":"document","children":[…]})`, 1);
|
|
754
|
+
}
|
|
755
|
+
const doc = d;
|
|
756
|
+
if (!Array.isArray(doc.diagnostics))
|
|
757
|
+
doc.diagnostics = [];
|
|
758
|
+
return doc;
|
|
759
|
+
}
|
|
760
|
+
// Write to `-o out` (with a `wrote` note on stderr) or to stdout.
|
|
761
|
+
function writeOut(text, out) {
|
|
762
|
+
if (out) {
|
|
763
|
+
writeFileSync(out, text);
|
|
764
|
+
console.error(`wrote ${out}`);
|
|
765
|
+
}
|
|
766
|
+
else
|
|
767
|
+
process.stdout.write(text);
|
|
768
|
+
}
|
|
769
|
+
// Output-target rule shared by the MUTATION verbs (set, and — soon — add,
|
|
770
|
+
// delete, rename, revert): a real file input with no `-o` is edited IN PLACE
|
|
771
|
+
// (it's the obvious target, and it's what lets an agent chain edits without
|
|
772
|
+
// re-reading a path back out of stdout); stdin (`file === "-"`) has no such
|
|
773
|
+
// target, so it falls back to stdout. `-o` always wins when given: `-o -`
|
|
774
|
+
// explicitly requests stdout (even for a file input), `-o <path>` writes
|
|
775
|
+
// there. Every write announces itself with `wrote <path>` on stderr; stdout
|
|
776
|
+
// stays reserved for the document bytes so it's still pipeable.
|
|
777
|
+
function resolveOutTarget(file, oFlag) {
|
|
778
|
+
const toFile = (path) => ({
|
|
779
|
+
write(text) { writeFileSync(path, text); console.error(`wrote ${path}`); },
|
|
780
|
+
});
|
|
781
|
+
const toStdout = { write(text) { process.stdout.write(text); } };
|
|
782
|
+
if (oFlag === "-")
|
|
783
|
+
return toStdout;
|
|
784
|
+
if (oFlag !== undefined)
|
|
785
|
+
return toFile(oFlag);
|
|
786
|
+
if (file === "-")
|
|
787
|
+
return toStdout;
|
|
788
|
+
return toFile(file);
|
|
789
|
+
}
|
|
790
|
+
// Positional args (a file, an id) are the non-flag tokens that aren't the value
|
|
791
|
+
// of a value-taking flag. `-` (stdin) is a positional, not a flag. An id may be
|
|
792
|
+
// written `#id` or `id`; a leading `-` never begins an id, so this stays
|
|
793
|
+
// unambiguous. `valued` lists the flags that consume the following token.
|
|
794
|
+
function positionals(args, valued) {
|
|
795
|
+
const out = [];
|
|
796
|
+
for (let i = 0; i < args.length; i++) {
|
|
797
|
+
const a = args[i];
|
|
798
|
+
if (valued.includes(a)) {
|
|
799
|
+
i++;
|
|
800
|
+
continue;
|
|
801
|
+
} // skip the flag *and* its value
|
|
802
|
+
if (a === "-") {
|
|
803
|
+
out.push(a);
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
if (a.startsWith("-"))
|
|
807
|
+
continue; // a bare flag (e.g. --json)
|
|
808
|
+
out.push(a);
|
|
809
|
+
}
|
|
810
|
+
return out;
|
|
811
|
+
}
|
|
812
|
+
// Resolve a block SELECTOR to an id. Three spellings address the same block:
|
|
813
|
+
//
|
|
814
|
+
// `#intro` / `intro` the id — the CANONICAL address
|
|
815
|
+
// `## Getting Started` the heading LINE, copied out of the document
|
|
816
|
+
// `##Getting Started` …the space after the `#` run is optional
|
|
817
|
+
//
|
|
818
|
+
// Why more than one form: the id is what `[[#id]]` references, codemap tables
|
|
819
|
+
// and URL fragments (§0.6) all carry, so it must stay accepted verbatim — an id
|
|
820
|
+
// copied out of a reference or out of `geml get <file>` has to work. But a
|
|
821
|
+
// heading's id is AUTO-DERIVED from its text (`## API 设计 (v1)` → `#api-设计-v1`),
|
|
822
|
+
// and nobody can be expected to hand-derive that slug for a heading they can
|
|
823
|
+
// read on screen. So the heading line itself is accepted too.
|
|
824
|
+
//
|
|
825
|
+
// Resolution order, first match wins:
|
|
826
|
+
// 1. the id, exactly — a pasted id is NEVER reinterpreted as prose. (When a
|
|
827
|
+
// heading's TEXT happens to equal another block's ID, the id wins.)
|
|
828
|
+
// 2. the exact heading LINE: `#` count AND text both match.
|
|
829
|
+
// 3. the text alone, at any level — a heading remembered at the wrong depth
|
|
830
|
+
// still resolves while its text is unique.
|
|
831
|
+
// 4. text shared by several headings: the `#` count picks one, or the
|
|
832
|
+
// candidates are listed. Never guessed at.
|
|
833
|
+
function resolveSelector(source, file, raw) {
|
|
834
|
+
const bare = raw.replace(/^#/, "");
|
|
835
|
+
const m = /^(#{1,6})[ \t]*(.+?)[ \t]*$/.exec(raw);
|
|
836
|
+
if (!m)
|
|
837
|
+
return bare; // not a `#`-run form: an id, verbatim
|
|
838
|
+
// 1. The id is canonical and always wins. Checked without a parse, so the
|
|
839
|
+
// common `get #id` stays a byte-slice on a document with diagnostics.
|
|
840
|
+
if (blockSpans(source).has(bare))
|
|
841
|
+
return bare;
|
|
842
|
+
const level = m[1].length;
|
|
843
|
+
const want = m[2];
|
|
844
|
+
const doc = parse(source, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
845
|
+
const heads = doc.ids.flatMap((id) => {
|
|
846
|
+
const site = findBlockSite(doc.children, id);
|
|
847
|
+
const b = site?.siblings[site.index];
|
|
848
|
+
return b?.kind === "heading" ? [{ id, level: b.level, text: b.text.trim() }] : [];
|
|
849
|
+
});
|
|
850
|
+
// 2. exact line — what the caller actually typed.
|
|
851
|
+
const line = heads.find((h) => h.level === level && h.text === want);
|
|
852
|
+
if (line)
|
|
853
|
+
return line.id;
|
|
854
|
+
// 3. the text alone (exact, then case-insensitive).
|
|
855
|
+
let byText = heads.filter((h) => h.text === want);
|
|
856
|
+
if (!byText.length) {
|
|
857
|
+
const lc = want.toLocaleLowerCase();
|
|
858
|
+
byText = heads.filter((h) => h.text.toLocaleLowerCase() === lc);
|
|
859
|
+
}
|
|
860
|
+
if (byText.length === 1)
|
|
861
|
+
return byText[0].id;
|
|
862
|
+
// 4. shared text: the level disambiguates, else show the candidates.
|
|
863
|
+
if (byText.length > 1) {
|
|
864
|
+
const atLevel = byText.filter((h) => h.level === level);
|
|
865
|
+
if (atLevel.length === 1)
|
|
866
|
+
return atLevel[0].id;
|
|
867
|
+
const list = byText.map((h) => ` #${h.id} (h${h.level})`).join("\n");
|
|
868
|
+
fail(`\`${want}\` matches ${byText.length} headings — address one by its id:\n${list}`, 1);
|
|
869
|
+
}
|
|
870
|
+
// Nothing matched. A lone `#` with no whitespace was almost certainly meant as
|
|
871
|
+
// an id, so hand it back and let the caller's own `no block with id` error
|
|
872
|
+
// stand — the precise diagnosis for a typo'd id. Only a heading-SHAPED
|
|
873
|
+
// selector gets the heading-flavoured message.
|
|
874
|
+
if (level === 1 && !/\s/.test(bare))
|
|
875
|
+
return bare;
|
|
876
|
+
fail(`no id or heading matches \`${raw}\` — run \`geml get ${file === "-" ? "-" : file}\` to list every addressable id`, 1);
|
|
877
|
+
}
|
|
878
|
+
// `geml get <file>` with no id: list every addressable id — the document's
|
|
879
|
+
// table of contents. Default output is one id per line with its kind (and, for
|
|
880
|
+
// a heading, its level and text); `--json` is a machine-readable array so an
|
|
881
|
+
// agent can pick its next `get #id` target. Ids are listed in document order
|
|
882
|
+
// (the registration order parse() records), covering the same set `get #id`
|
|
883
|
+
// resolves against: typed blocks and headings. A `[^id]` reference names one
|
|
884
|
+
// of those (§5.2); the `[^id]: text` definition line was withdrawn.
|
|
885
|
+
function listIds(source, file, json) {
|
|
886
|
+
const where = file === "-" ? "stdin" : file;
|
|
887
|
+
const all = addressedUnits(source);
|
|
888
|
+
const doc = parse(source, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
889
|
+
const rows = all.map((a) => {
|
|
890
|
+
const u = a.unit;
|
|
891
|
+
const row = {
|
|
892
|
+
address: shortestAddress(a, all),
|
|
893
|
+
kind: u.kind === "block" ? u.type ?? "block" : u.kind,
|
|
894
|
+
lines: [u.span.start + 1, u.span.end],
|
|
895
|
+
};
|
|
896
|
+
// §6.3: EVERY id-less block is flagged, including one whose address works
|
|
897
|
+
// only because its type happens to be unique (`=== meta`) — that it has no
|
|
898
|
+
// id yet is precisely the fact you might want to act on (§5.2).
|
|
899
|
+
if (u.id === undefined)
|
|
900
|
+
row.anon = true;
|
|
901
|
+
else
|
|
902
|
+
row.id = u.id;
|
|
903
|
+
if (u.kind === "heading") {
|
|
904
|
+
row.level = u.level;
|
|
905
|
+
row.text = u.text;
|
|
906
|
+
}
|
|
907
|
+
// `.footnote` is authored, not synthesized (the `[^id]: text` definition
|
|
908
|
+
// line was withdrawn) — but it still marks a block meant as a footnote.
|
|
909
|
+
if (u.id !== undefined) {
|
|
910
|
+
const site = findBlockSite(doc.children, u.id);
|
|
911
|
+
const b = site?.siblings[site.index];
|
|
912
|
+
if (b?.kind === "block" && b.classes.includes("footnote"))
|
|
913
|
+
row.footnote = true;
|
|
914
|
+
}
|
|
915
|
+
return row;
|
|
916
|
+
});
|
|
917
|
+
// §6.6: the empty document is a legitimate empty answer to "list everything",
|
|
918
|
+
// not a lookup failure — exit 0, and `--json` prints `[]` so a `| jq length`
|
|
919
|
+
// over a prose-only document does not blow up.
|
|
920
|
+
if (json) {
|
|
921
|
+
console.log(JSON.stringify(rows, null, 2));
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
if (rows.length === 0) {
|
|
925
|
+
console.error(`no addressable blocks in ${where}`);
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
const addrW = Math.max(...rows.map((r) => r.address.length));
|
|
929
|
+
const kindW = Math.max(...rows.map((r) => r.kind.length));
|
|
930
|
+
// The line range belongs on EVERY row, headings included. It used to be the
|
|
931
|
+
// alternative to a heading's text, so the one kind of block whose range you
|
|
932
|
+
// most want — a whole section — was the one kind that did not print it, and
|
|
933
|
+
// `L11-493` is itself an address you can paste back into `get`. The heading's
|
|
934
|
+
// text follows it rather than replacing it.
|
|
935
|
+
const lineW = Math.max(...rows.map((r) => `L${r.lines[0]}-${r.lines[1]}`.length));
|
|
936
|
+
for (const r of rows) {
|
|
937
|
+
const mark = r.kind === "heading" ? `h${r.level}` : r.anon ? "anon" : "";
|
|
938
|
+
const span = `L${r.lines[0]}-${r.lines[1]}`;
|
|
939
|
+
const tail = r.kind === "heading" ? `${span.padEnd(lineW)} ${r.text ?? ""}` : span;
|
|
940
|
+
const line = `${r.address.padEnd(addrW)} ${r.kind.padEnd(kindW)} ${mark.padEnd(4)} ${tail}`
|
|
941
|
+
+ (r.footnote ? " footnote" : "");
|
|
942
|
+
console.log(line.trimEnd());
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
// `geml get <file.geml|-> #id [--json]` — print ONE block, addressed by id,
|
|
946
|
+
// without loading the rest of the document into context. Default output is the
|
|
947
|
+
// block's exact source bytes: a typed block's full `=== … ===` span, a
|
|
948
|
+
// footnote's line, or — for a heading — its whole SECTION (heading line through
|
|
949
|
+
// the line before the next same-or-higher heading). `--json` covers the same
|
|
950
|
+
// content: a block/footnote id prints its document-model node; a heading id
|
|
951
|
+
// prints a section envelope `{kind:"section", id, level, blocks:[heading,
|
|
952
|
+
// …siblings up to the boundary]}`.
|
|
953
|
+
// `geml get <file> '=== <type>'` — address a block by its TYPE. One match is
|
|
954
|
+
// the block itself; several are LISTED with their line ranges rather than
|
|
955
|
+
// guessed between, so a document with three notes answers "which one" instead
|
|
956
|
+
// of failing. The uniqueness that makes `=== meta` work is checked here, at
|
|
957
|
+
// resolve time — nothing in the format has to promise a document holds only one.
|
|
958
|
+
// Every block of `type` in document order, nested flow children included —
|
|
959
|
+
// exactly the span scan's reach and order, so the k-th scan match and the k-th
|
|
960
|
+
// model node are the same block. That correspondence is what lets an ANONYMOUS
|
|
961
|
+
// block's `--json` find its node without an id to look it up by.
|
|
962
|
+
function blocksOfType(blocks, type) {
|
|
963
|
+
const hits = [];
|
|
964
|
+
const walk = (list) => {
|
|
965
|
+
for (const b of list) {
|
|
966
|
+
if (b.kind === "block") {
|
|
967
|
+
if (b.type === type)
|
|
968
|
+
hits.push(b);
|
|
969
|
+
if (b.children)
|
|
970
|
+
walk(b.children);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
walk(blocks);
|
|
975
|
+
return hits;
|
|
976
|
+
}
|
|
977
|
+
// A unit's index among the units of its own type, for the positional lookup above.
|
|
978
|
+
function typeIndex(all, u) {
|
|
979
|
+
return all.filter((a) => a.unit.type === u.type).findIndex((a) => a.unit === u);
|
|
980
|
+
}
|
|
981
|
+
// Resolve a NON-list selector to the units it matches, or fail with the reason.
|
|
982
|
+
// `where` names the haystack for the error messages — a file for `geml get`, a
|
|
983
|
+
// revision for `geml history get`'s tier 2. Shared by both so the one selector
|
|
984
|
+
// grammar has one implementation: history's design §10.1 asks for exactly this,
|
|
985
|
+
// and its §3.2 records what happened the last time a selector grammar was
|
|
986
|
+
// written twice (the printed selectors stopped being readable back).
|
|
987
|
+
function selectUnits(source, file, rawSel, where) {
|
|
988
|
+
const sel = parseSelector(rawSel, (braces) => parseAttrs(braces).id);
|
|
989
|
+
// Callers handle the empty selector themselves (list for `get`, usage error
|
|
990
|
+
// for `set`); reaching here with one is a caller bug surfaced as usage.
|
|
991
|
+
if (sel.form === "list")
|
|
992
|
+
fail(`no selector given — run \`geml get ${where}\` to list addressable blocks`, 2);
|
|
993
|
+
if (sel.form === "attr") {
|
|
994
|
+
// §7: the wording says "not implemented yet", not "braces are meaningless" —
|
|
995
|
+
// §2 declares attribute keys as part of the model, so implementing them
|
|
996
|
+
// later fills in a declared slot rather than reversing this message.
|
|
997
|
+
fail(`only \`#id\` is supported as a filter key today (got \`${sel.key}\`) — use \`=== ${sel.type}\` for every ${sel.type} block, or address one by \`#id\` / \`@<hex>\``, 2);
|
|
998
|
+
}
|
|
999
|
+
const all = addressedUnits(source);
|
|
1000
|
+
if (sel.form === "content") {
|
|
1001
|
+
const hit = matchContent(sel, all);
|
|
1002
|
+
if (!hit.ok) {
|
|
1003
|
+
if (hit.why === "wrong-type") {
|
|
1004
|
+
// §3.3: the type prefix is a CHECK. Ignoring a wrong one would make it
|
|
1005
|
+
// a decoration that is allowed to lie, and would silently accept a
|
|
1006
|
+
// hand-edited address.
|
|
1007
|
+
fail(`\`@${sel.hex}\` addresses a \`${hit.found}\` block, not \`${sel.type}\` — drop the type prefix to address it by content alone`, 1);
|
|
1008
|
+
}
|
|
1009
|
+
const suffix = sel.nth ? `~${sel.nth}` : "";
|
|
1010
|
+
fail(`no block matching \`@${sel.hex}${suffix}\` in ${where} — a content address goes stale when the block's content changes (that is the point: §3.2); run \`geml get ${where}\` for current addresses`, 1);
|
|
1011
|
+
}
|
|
1012
|
+
return { units: [hit.unit], all };
|
|
1013
|
+
}
|
|
1014
|
+
if (sel.form === "line") {
|
|
1015
|
+
const hit = matchLine(sel, all);
|
|
1016
|
+
// A range that straddles two blocks contains no single unit — say which
|
|
1017
|
+
// case it is, because "no match" reads like "your line number is wrong"
|
|
1018
|
+
// when the real answer is "that range is not one block".
|
|
1019
|
+
if (!hit) {
|
|
1020
|
+
const span = sel.from === sel.to ? `L${sel.from}` : `L${sel.from}-${sel.to}`;
|
|
1021
|
+
fail(`no block contains ${span} in ${where} — a position selector names ONE block, so a range spanning two of them (or a line past the end) has no answer${discoveryHint(where)}`, 1);
|
|
1022
|
+
}
|
|
1023
|
+
return { units: [hit], all };
|
|
1024
|
+
}
|
|
1025
|
+
if (sel.form === "type") {
|
|
1026
|
+
const hits = matchType(sel.type, all);
|
|
1027
|
+
if (!hits.length)
|
|
1028
|
+
fail(`no \`${sel.type}\` block in ${where}${discoveryHint(where)}`, 1);
|
|
1029
|
+
return { units: hits, all };
|
|
1030
|
+
}
|
|
1031
|
+
// `#id` / bare id / a pasted `## Heading` line — resolveSelector needs a parse
|
|
1032
|
+
// to match heading TEXT, so it stays the one path that reaches the model.
|
|
1033
|
+
const id = resolveSelector(source, file, sel.raw);
|
|
1034
|
+
const unit = all.find((a) => a.unit.id === id)?.unit;
|
|
1035
|
+
// Bare `no block with id \`x\`` — the phrasing every caller of a missing id
|
|
1036
|
+
// has always seen, and which `set`'s own tests pin. `where` is appended only
|
|
1037
|
+
// when it is NOT the file the caller already named (a revision), so the
|
|
1038
|
+
// common case reads the same as before this selector grammar existed.
|
|
1039
|
+
if (!unit)
|
|
1040
|
+
fail(`no block with id \`${id}\`${where.startsWith("revision ") ? ` in ${where}` : ""}`, 1);
|
|
1041
|
+
return { units: [unit], all };
|
|
1042
|
+
}
|
|
1043
|
+
// The document-model node for one unit; a heading yields its SECTION envelope,
|
|
1044
|
+
// so --json covers the same content as the raw span. `kind:"section"` lets a
|
|
1045
|
+
// consumer branch — every other unit yields the single node (the model is flat).
|
|
1046
|
+
function unitNode(source, file, unit, all) {
|
|
1047
|
+
const doc = parse(source, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
1048
|
+
if (unit.id !== undefined) {
|
|
1049
|
+
const site = findBlockSite(doc.children, unit.id);
|
|
1050
|
+
if (!site)
|
|
1051
|
+
fail(`no block with id \`${unit.id}\``, 1);
|
|
1052
|
+
const block = site.siblings[site.index];
|
|
1053
|
+
if (block.kind !== "heading")
|
|
1054
|
+
return block;
|
|
1055
|
+
const end = sectionEndIndex(site.siblings, site.index);
|
|
1056
|
+
return { kind: "section", id: block.id, level: block.level, blocks: site.siblings.slice(site.index, end) };
|
|
1057
|
+
}
|
|
1058
|
+
const node = blocksOfType(doc.children, unit.type ?? "")[typeIndex(all, unit)];
|
|
1059
|
+
if (!node)
|
|
1060
|
+
fail(`could not locate the \`${unit.type}\` block in the document model`, 1);
|
|
1061
|
+
return node;
|
|
1062
|
+
}
|
|
1063
|
+
// stderr line for an N-match selector: content stays on stdout, so a redirect
|
|
1064
|
+
// captures document bytes only, and the caller still learns how many it got (§5).
|
|
1065
|
+
function reportMatches(type, units) {
|
|
1066
|
+
const at = units.map((u) => `L${u.span.start + 1}-${u.span.end}${u.id ? ` #${u.id}` : ""}`).join(" · ");
|
|
1067
|
+
console.error(`${units.length} \`${type}\` blocks (${at})`);
|
|
1068
|
+
}
|
|
1069
|
+
// `geml get <file.geml|-> [<selector>] [--head|--body] [--json]` — read the
|
|
1070
|
+
// document's addressable structure, or one/several blocks out of it.
|
|
1071
|
+
//
|
|
1072
|
+
// The selector is a FILTER (§2 of the get/set selector design): no selector
|
|
1073
|
+
// LISTS every addressable block with its shortest unique address; `#id` /
|
|
1074
|
+
// `## Heading` / `=== type@<hex>` name at most one; `=== type` matches 0..N.
|
|
1075
|
+
// Cardinality is uniform (§5): 0 → exit 1, 1 → the content, N → N contents in
|
|
1076
|
+
// document order with the count on stderr. `--head`/`--body` narrow to one part
|
|
1077
|
+
// of each match, and every flag combination that used to be half-honoured is
|
|
1078
|
+
// now a usage error (§7) — a discarded flag is a command that quietly did
|
|
1079
|
+
// something else.
|
|
1080
|
+
// `geml list <file>` — the same listing `get` prints with no selector, under
|
|
1081
|
+
// the name the MCP surface has always used for it (`geml_list`). One operation
|
|
1082
|
+
// had two names across two surfaces; this makes the CLI agree with the tool
|
|
1083
|
+
// descriptions agents are already reading. `get <file>` keeps working.
|
|
1084
|
+
function runList(args) {
|
|
1085
|
+
const [file, extra] = positionals(args, ["--root"]);
|
|
1086
|
+
if (!file)
|
|
1087
|
+
fail(SUBHELP.list);
|
|
1088
|
+
// `list` IS the empty filter, so a selector here means the caller wanted
|
|
1089
|
+
// `get`. Naming the command they meant beats ignoring the argument.
|
|
1090
|
+
if (extra !== undefined) {
|
|
1091
|
+
fail(`\`list\` takes no selector — it lists every block. To read one: \`geml get ${file} '${extra}'\``, 2);
|
|
1092
|
+
}
|
|
1093
|
+
listIds(readInput(file), file, args.includes("--json"));
|
|
1094
|
+
}
|
|
1095
|
+
// Walk for `.geml` files. Depth-first, sorted, so output order is stable across
|
|
1096
|
+
// platforms — a listing that reorders between machines is a listing nobody can
|
|
1097
|
+
// diff. Hidden directories and `node_modules` are skipped: a search verb that
|
|
1098
|
+
// dredges up vendored copies trains people to stop reading its output.
|
|
1099
|
+
function gemlFilesUnder(path, out) {
|
|
1100
|
+
let dir = false;
|
|
1101
|
+
try {
|
|
1102
|
+
dir = statSync(path).isDirectory();
|
|
1103
|
+
}
|
|
1104
|
+
catch {
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
if (!dir) {
|
|
1108
|
+
if (path.endsWith(".geml"))
|
|
1109
|
+
out.push(path);
|
|
1110
|
+
return;
|
|
1111
|
+
}
|
|
1112
|
+
for (const e of readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
|
|
1113
|
+
if (e.name.startsWith(".") || e.name === "node_modules")
|
|
1114
|
+
continue;
|
|
1115
|
+
gemlFilesUnder(join(path, e.name), out);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
// `geml find <pattern> [path…]` — search block CONTENT, print ADDRESSES.
|
|
1119
|
+
//
|
|
1120
|
+
// This is the half of the workflow that had no verb. `geml list` says what is
|
|
1121
|
+
// addressable and `geml get` reads one block, but "which block mentions X" fell
|
|
1122
|
+
// back to `grep -n`, which answers in line numbers — and a line number stops
|
|
1123
|
+
// being true the moment anything above it changes. `codemap find` already
|
|
1124
|
+
// resolves a substring to `doc#id` for symbols; this is the same move for prose.
|
|
1125
|
+
function runFind(args) {
|
|
1126
|
+
const pos = positionals(args, []);
|
|
1127
|
+
const pattern = pos[0];
|
|
1128
|
+
if (pattern === undefined)
|
|
1129
|
+
fail(SUBHELP.find);
|
|
1130
|
+
const sensitive = args.includes("--case");
|
|
1131
|
+
const withLine = args.includes("--head");
|
|
1132
|
+
const json = args.includes("--json");
|
|
1133
|
+
const needle = sensitive ? pattern : pattern.toLowerCase();
|
|
1134
|
+
const files = [];
|
|
1135
|
+
for (const p of pos.slice(1).length ? pos.slice(1) : ["."])
|
|
1136
|
+
gemlFilesUnder(p, files);
|
|
1137
|
+
const hits = [];
|
|
1138
|
+
for (const f of files) {
|
|
1139
|
+
let source;
|
|
1140
|
+
// An unreadable file mid-walk must not abort the search — report nothing
|
|
1141
|
+
// for it and keep going, the way every search tool behaves.
|
|
1142
|
+
try {
|
|
1143
|
+
source = readFileSync(f, "utf8");
|
|
1144
|
+
}
|
|
1145
|
+
catch {
|
|
1146
|
+
continue;
|
|
1147
|
+
}
|
|
1148
|
+
const all = addressedUnits(source);
|
|
1149
|
+
// Match by LINE, then resolve each line to the innermost unit holding it —
|
|
1150
|
+
// exactly what the `L` selector does, so `find` is `grep` composed with
|
|
1151
|
+
// `L` rather than a second notion of "which block is this in". Testing the
|
|
1152
|
+
// units directly instead would report every ancestor: a heading's span
|
|
1153
|
+
// covers its whole section, so the h1 spans the file and would match every
|
|
1154
|
+
// search ever run.
|
|
1155
|
+
const lines = source.replace(/\r\n?/g, "\n").split("\n");
|
|
1156
|
+
const seen = new Map();
|
|
1157
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1158
|
+
const raw = lines[i];
|
|
1159
|
+
if (!(sensitive ? raw : raw.toLowerCase()).includes(needle))
|
|
1160
|
+
continue;
|
|
1161
|
+
const unit = matchLine({ form: "line", from: i + 1, to: i + 1 }, all);
|
|
1162
|
+
if (!unit)
|
|
1163
|
+
continue;
|
|
1164
|
+
const a = all.find((x) => x.unit === unit);
|
|
1165
|
+
const address = shortestAddress(a, all);
|
|
1166
|
+
// One unit, one hit, however many lines inside it matched — a search that
|
|
1167
|
+
// reports the same block eight times is a search you stop reading.
|
|
1168
|
+
const key = `${a.unit.span.start}:${a.unit.span.end}`;
|
|
1169
|
+
if (seen.has(key))
|
|
1170
|
+
continue;
|
|
1171
|
+
const hit = {
|
|
1172
|
+
file: f,
|
|
1173
|
+
address,
|
|
1174
|
+
kind: unit.kind === "block" ? unit.type ?? "block" : unit.kind,
|
|
1175
|
+
lines: [unit.span.start + 1, unit.span.end],
|
|
1176
|
+
};
|
|
1177
|
+
if (withLine)
|
|
1178
|
+
hit.line = raw.trim();
|
|
1179
|
+
seen.set(key, hit);
|
|
1180
|
+
hits.push(hit);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
if (json) {
|
|
1184
|
+
console.log(JSON.stringify(hits, null, 2));
|
|
1185
|
+
}
|
|
1186
|
+
else {
|
|
1187
|
+
for (const h of hits) {
|
|
1188
|
+
// Two columns, `file` then the address EXACTLY as the listing prints it,
|
|
1189
|
+
// so a hit is `geml get <col1> '<col2>'` with no editing. Not glued into
|
|
1190
|
+
// one `file#addr` token: an id-less block's address is `=== code@a3f9`,
|
|
1191
|
+
// which has a space in it and can never be one token — and a format that
|
|
1192
|
+
// is only pasteable for half the rows is worse than one that is uniform.
|
|
1193
|
+
const row = `${h.file}\t${h.address}`;
|
|
1194
|
+
console.log(withLine && h.line !== undefined ? `${row}\t${h.line}` : row);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
// Exit 1 on no match, like grep: it makes `if geml find …; then` mean what a
|
|
1198
|
+
// shell author expects. An empty `--json` array still prints, so a JSON
|
|
1199
|
+
// consumer sees `[]` rather than nothing.
|
|
1200
|
+
if (!hits.length)
|
|
1201
|
+
process.exit(1);
|
|
1202
|
+
}
|
|
1203
|
+
function runGet(args) {
|
|
1204
|
+
const json = args.includes("--json");
|
|
1205
|
+
const headOnly = args.includes("--head");
|
|
1206
|
+
const bodyOnly = args.includes("--body");
|
|
1207
|
+
const introOnly = args.includes("--intro");
|
|
1208
|
+
const view = args.includes("--view");
|
|
1209
|
+
const [file, rawSel] = positionals(args, ["--root"]);
|
|
1210
|
+
if (!file)
|
|
1211
|
+
fail(SUBHELP.get);
|
|
1212
|
+
const parts = [headOnly && "--head", introOnly && "--intro", bodyOnly && "--body"].filter(Boolean);
|
|
1213
|
+
if (parts.length > 1)
|
|
1214
|
+
fail(`${parts.join(" and ")} are mutually exclusive — they name different parts of one block`, 2);
|
|
1215
|
+
const partFlag = parts[0];
|
|
1216
|
+
if (json && partFlag) {
|
|
1217
|
+
fail(`--json cannot be combined with ${partFlag} — --json returns the model node, which has no sub-node for one part of a block`, 2);
|
|
1218
|
+
}
|
|
1219
|
+
const part = headOnly ? "head" : bodyOnly ? "body" : introOnly ? "intro" : "whole";
|
|
1220
|
+
// One read: stdin can only be consumed once, and the selector resolver needs
|
|
1221
|
+
// the same bytes the slice below works on.
|
|
1222
|
+
const source = readInput(file);
|
|
1223
|
+
const where = file === "-" ? "stdin" : file;
|
|
1224
|
+
const sel = parseSelector(rawSel, (braces) => parseAttrs(braces).id);
|
|
1225
|
+
if (sel.form === "list") {
|
|
1226
|
+
// §5.1: nothing here to narrow, and ignoring the flag would make
|
|
1227
|
+
// `get f --head` print byte-for-byte what `get f` prints.
|
|
1228
|
+
if (partFlag) {
|
|
1229
|
+
fail(`${partFlag} names part of ONE block, so it needs a selector — run \`geml list ${where}\` to see what to address`, 2);
|
|
1230
|
+
}
|
|
1231
|
+
listIds(source, file, json);
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
const { units, all } = selectUnits(source, file, rawSel, where);
|
|
1235
|
+
// The chain is composed with `/` — relJoinPath's rule, and `src=` values are
|
|
1236
|
+
// always `/`-separated — so normalize the PLATFORM path at this boundary. On
|
|
1237
|
+
// Windows `sub\host.geml` otherwise has no directory as far as relDirPath can
|
|
1238
|
+
// tell, and a relative `src=` resolves against the wrong base.
|
|
1239
|
+
const startDoc = where.replace(/\\/g, "/");
|
|
1240
|
+
const viewRoot = flag(args, "--root") ?? (relDirPath(startDoc) || ".");
|
|
1241
|
+
if (json) {
|
|
1242
|
+
// §7: N matches yield N model nodes. The old `{kind:"blocks",
|
|
1243
|
+
// matches:[{lines}]}` coordinate envelope is gone — it answered "where are
|
|
1244
|
+
// they" when the question is "what are they" (§9 change 2).
|
|
1245
|
+
let nodes;
|
|
1246
|
+
try {
|
|
1247
|
+
nodes = units.flatMap((u) => {
|
|
1248
|
+
if (!view)
|
|
1249
|
+
return [unitNode(source, file, u, all)];
|
|
1250
|
+
return viewResolve(source, startDoc, u, viewRoot).map((res) => {
|
|
1251
|
+
const node = unitNode(res.text, res.doc, res.unit, res.all);
|
|
1252
|
+
// Provenance is mandatory (§4): the node's references and relative
|
|
1253
|
+
// paths resolve against ITS document, not the one asked about. A
|
|
1254
|
+
// whole-document target has no `#`, so it carries `doc` alone.
|
|
1255
|
+
if (res.from !== "") {
|
|
1256
|
+
const h = res.from.lastIndexOf("#");
|
|
1257
|
+
node["from"] = h < 0 ? { doc: res.from }
|
|
1258
|
+
: { doc: res.from.slice(0, h), id: res.from.slice(h + 1) };
|
|
1259
|
+
}
|
|
1260
|
+
return node;
|
|
1261
|
+
});
|
|
1262
|
+
});
|
|
1263
|
+
}
|
|
1264
|
+
catch (e) {
|
|
1265
|
+
if (e instanceof ViewError)
|
|
1266
|
+
fail(e.message, 1);
|
|
1267
|
+
throw e;
|
|
1268
|
+
}
|
|
1269
|
+
console.log(JSON.stringify(nodes.length === 1 ? nodes[0] : nodes, null, 2));
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
if (units.length > 1)
|
|
1273
|
+
reportMatches(units[0].type ?? "", units);
|
|
1274
|
+
if (view) {
|
|
1275
|
+
// All-or-nothing (§3.3): resolve EVERYTHING before writing a byte, so a
|
|
1276
|
+
// chain that breaks halfway cannot leave a partial read on stdout for a
|
|
1277
|
+
// caller that ignores the exit code. Partial scenery is not scenery.
|
|
1278
|
+
const out = [];
|
|
1279
|
+
const notes = [];
|
|
1280
|
+
try {
|
|
1281
|
+
for (const u of units) {
|
|
1282
|
+
for (const res of viewResolve(source, startDoc, u, viewRoot)) {
|
|
1283
|
+
if (res.from !== "")
|
|
1284
|
+
notes.push(`view: ${rawSel} -> ${res.from}`);
|
|
1285
|
+
out.push(sliceUnit(res.text, res.unit.span, part));
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
catch (e) {
|
|
1290
|
+
// A chain that cannot reach an entity block is a failed READ, reported the
|
|
1291
|
+
// way `get` reports a selector that matches nothing: one line, exit 1.
|
|
1292
|
+
if (e instanceof ViewError)
|
|
1293
|
+
fail(e.message, 1);
|
|
1294
|
+
throw e;
|
|
1295
|
+
}
|
|
1296
|
+
for (const n of notes)
|
|
1297
|
+
console.error(n);
|
|
1298
|
+
process.stdout.write(out.join(""));
|
|
1299
|
+
return;
|
|
1300
|
+
}
|
|
1301
|
+
// A block has no intro: the region is "what this heading says before its
|
|
1302
|
+
// first subheading", and only a heading has subheadings. Silently handing
|
|
1303
|
+
// back the body instead would answer a question that was not asked.
|
|
1304
|
+
for (const u of units) {
|
|
1305
|
+
if (part === "intro" && u.kind !== "heading") {
|
|
1306
|
+
fail(`--intro names a heading's opening region, and \`${rawSel}\` is a \`${u.type ?? u.kind}\` block — use --body for a block's content`, 2);
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
for (const u of units)
|
|
1310
|
+
process.stdout.write(sliceUnit(source, u.span, part));
|
|
1311
|
+
}
|
|
1312
|
+
const NO_CONTENT = "no replacement content (use --in FILE or pipe it on stdin)";
|
|
1313
|
+
// `geml set <file.geml|-> #id [--head|--body] [--in F|F#src|-] [-o out]` —
|
|
1314
|
+
// replace ONE existing block, addressed by #id, with new content, preserving
|
|
1315
|
+
// every other byte. Two content CHANNELS × three MODES:
|
|
1316
|
+
//
|
|
1317
|
+
// channels · `--in F[#src]` extracts a BLOCK from GEML file F (F is always
|
|
1318
|
+
// read as GEML — extension ignored, no md conversion): `--in F`
|
|
1319
|
+
// takes the block whose id == the target #id; `--in F#src` takes
|
|
1320
|
+
// #src. stdin (default, or `--in -`) is raw bytes.
|
|
1321
|
+
// modes · default replaces the WHOLE block, `--head` only the head line,
|
|
1322
|
+
// `--body` only the body. Default and `--head` NORMALIZE the
|
|
1323
|
+
// content's id to #id (its source id is irrelevant); `--body`
|
|
1324
|
+
// keeps the target's head verbatim, so #id is preserved naturally.
|
|
1325
|
+
//
|
|
1326
|
+
// Output follows resolveOutTarget (file -> in place, stdin -> stdout, `-o`/`-o -`
|
|
1327
|
+
// override) and every splice is guarded — re-parsed and rejected if it broke
|
|
1328
|
+
// the doc, so `set` never writes a corrupt file.
|
|
1329
|
+
function runSet(args) {
|
|
1330
|
+
const out = flag(args, "-o") ?? flag(args, "--out");
|
|
1331
|
+
const from = flag(args, "--in");
|
|
1332
|
+
const headOnly = args.includes("--head");
|
|
1333
|
+
const bodyOnly = args.includes("--body");
|
|
1334
|
+
const introOnly = args.includes("--intro");
|
|
1335
|
+
const named = [headOnly && "--head", introOnly && "--intro", bodyOnly && "--body"].filter(Boolean);
|
|
1336
|
+
if (named.length > 1)
|
|
1337
|
+
fail(`${named.join(" and ")} are mutually exclusive — they name different parts of one block`, 2);
|
|
1338
|
+
// `--view` reads THROUGH an embed (see runGet). Writing through one would mean
|
|
1339
|
+
// one `set` silently editing a different file, so it is refused rather than
|
|
1340
|
+
// ignored — and the message has to point the way, not just say no.
|
|
1341
|
+
if (args.includes("--view")) {
|
|
1342
|
+
fail("--view is read-only. To edit the target, read the frame's `src` and edit that document.", 2);
|
|
1343
|
+
}
|
|
1344
|
+
const [file, rawSel] = positionals(args, ["-o", "--out", "--in"]);
|
|
1345
|
+
if (!file)
|
|
1346
|
+
fail(SUBHELP.set);
|
|
1347
|
+
// No selector: there is no block to replace. Point the way to discovery, not a
|
|
1348
|
+
// bare usage line — `geml get <file>` lists every address `set` can target.
|
|
1349
|
+
if (!rawSel)
|
|
1350
|
+
fail(`no selector given — run 'geml get ${file === "-" ? "<file>" : file}' to list addressable blocks`, 2);
|
|
1351
|
+
// The raw channel is stdin — `--in` omitted or `--in -`; anything else sources
|
|
1352
|
+
// a block from a file. Document and content can't BOTH be stdin: reject that
|
|
1353
|
+
// up front, before consuming stdin, so the document read below is unambiguous.
|
|
1354
|
+
const rawChannel = from === undefined || from === "-";
|
|
1355
|
+
if (file === "-" && rawChannel) {
|
|
1356
|
+
fail("reading the document from stdin needs --in for the new content", 2);
|
|
1357
|
+
}
|
|
1358
|
+
const source = readInput(file);
|
|
1359
|
+
const target = resolveSetTarget(source, file, rawSel);
|
|
1360
|
+
if (introOnly) {
|
|
1361
|
+
runSetIntro(source, target, from, rawChannel, file, out);
|
|
1362
|
+
return;
|
|
1363
|
+
}
|
|
1364
|
+
if (bodyOnly) {
|
|
1365
|
+
runSetBody(source, target, from, rawChannel, file, out);
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
let content;
|
|
1369
|
+
if (rawChannel) {
|
|
1370
|
+
content = readInput("-");
|
|
1371
|
+
if (content === "")
|
|
1372
|
+
fail(NO_CONTENT, 1);
|
|
1373
|
+
// Default mode wants exactly ONE block. Pure prose has no head to carry the
|
|
1374
|
+
// id (steer to --body); multiple blocks are `add`'s job. --head takes a
|
|
1375
|
+
// lone head line, so it skips the whole-block shape check.
|
|
1376
|
+
if (!headOnly) {
|
|
1377
|
+
const shape = contentShape(content);
|
|
1378
|
+
if (shape === "empty")
|
|
1379
|
+
fail(NO_CONTENT, 1);
|
|
1380
|
+
if (shape === "prose")
|
|
1381
|
+
fail(`content is prose, not a block — use --body to set the body of ${target.label}`, 1);
|
|
1382
|
+
if (shape === "multi")
|
|
1383
|
+
fail("set replaces ONE block, but the content has multiple blocks (use add)", 1);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
else {
|
|
1387
|
+
content = extractBlock(from, target.unit.id ?? "", headOnly ? "head" : "whole");
|
|
1388
|
+
}
|
|
1389
|
+
// §5.2: `@<hex>` is not an id, so "normalize the content's id to the target's"
|
|
1390
|
+
// has no subject — the content is used verbatim, and an id it brings that
|
|
1391
|
+
// collides is caught by the splice guard like any other. An id target keeps
|
|
1392
|
+
// normalizing: naming an id on the command line IS the instruction that the
|
|
1393
|
+
// result carries that id (block-mutation design §4.0).
|
|
1394
|
+
const replacement = target.unit.id !== undefined ? normalizeBlockId(content, target.unit.id) : content;
|
|
1395
|
+
const updated = spliceSpan(source, target.unit.span, replacement, file, headOnly, false, target.unit.id);
|
|
1396
|
+
resolveOutTarget(file, out).write(updated);
|
|
1397
|
+
reportNewAddress(updated, target);
|
|
1398
|
+
}
|
|
1399
|
+
// Resolve a selector to the ONE unit `set` will overwrite. `get` may answer with
|
|
1400
|
+
// N blocks; `set` may not — §5: with N targets there is no single id to
|
|
1401
|
+
// normalize the content to, so multi-target `set` is undefined, not merely
|
|
1402
|
+
// risky. Refused with exit 2 (a usage error), not exit 1.
|
|
1403
|
+
function resolveSetTarget(source, file, rawSel) {
|
|
1404
|
+
const where = file === "-" ? "<file>" : file;
|
|
1405
|
+
const sel = parseSelector(rawSel, (braces) => parseAttrs(braces).id);
|
|
1406
|
+
if (sel.form === "list")
|
|
1407
|
+
fail(`no selector given — run 'geml get ${where}' to list addressable blocks`, 2);
|
|
1408
|
+
const { units, all } = selectUnits(source, file, rawSel, where);
|
|
1409
|
+
if (units.length > 1) {
|
|
1410
|
+
// §5: with N targets there is no single id to normalize the content to, so
|
|
1411
|
+
// multi-target `set` is UNDEFINED, not merely risky. The addresses are
|
|
1412
|
+
// printed because they ARE the fix — each is unique and pastes straight
|
|
1413
|
+
// back into this same command (§6.2).
|
|
1414
|
+
const opts = units.map((u) => {
|
|
1415
|
+
const a = all.find((x) => x.unit === u);
|
|
1416
|
+
return ` ${shortestAddress(a, all)} L${u.span.start + 1}-${u.span.end}`;
|
|
1417
|
+
}).join("\n");
|
|
1418
|
+
fail(`\`${rawSel.trim()}\` matches ${units.length} blocks — set writes ONE; address it uniquely:\n${opts}`, 2);
|
|
1419
|
+
}
|
|
1420
|
+
const unit = units[0];
|
|
1421
|
+
const label = unit.id !== undefined && sel.form === "id" ? `#${unit.id}` : `\`${rawSel.trim()}\``;
|
|
1422
|
+
return { unit, label, byContent: sel.form === "content" };
|
|
1423
|
+
}
|
|
1424
|
+
// §5.3: writing through a content address CHANGES it, so print the new one —
|
|
1425
|
+
// otherwise a script editing the same block twice has to re-list in between.
|
|
1426
|
+
// stderr, because stdout may be the document itself (`-o -`).
|
|
1427
|
+
function reportNewAddress(updated, target) {
|
|
1428
|
+
if (!target.byContent)
|
|
1429
|
+
return;
|
|
1430
|
+
const after = addressedUnits(updated).find((a) => a.unit.span.start === target.unit.span.start);
|
|
1431
|
+
if (after)
|
|
1432
|
+
console.error(`new address: ${shortestAddress(after, addressedUnits(updated))}`);
|
|
1433
|
+
}
|
|
1434
|
+
// `--body`: swap ONLY the target block's body, keeping its head (and #id) and,
|
|
1435
|
+
// for a typed block, its close fence. Assembles head + new body + close and
|
|
1436
|
+
// reuses the guarded spliceBlock — the head carries #id, so the id survives
|
|
1437
|
+
// with no normalization needed.
|
|
1438
|
+
// `set --intro` — replace only what a heading says before its first subheading.
|
|
1439
|
+
// The heading line and everything from that subheading down stay byte-identical,
|
|
1440
|
+
// which is the whole point: the region `get --intro` hands out is the region
|
|
1441
|
+
// `set --intro` puts back, so a read-edit-write round trip cannot swallow the
|
|
1442
|
+
// subsections. When the region is EMPTY (a subheading follows the heading
|
|
1443
|
+
// immediately) this inserts there — writing an opening for a section that had
|
|
1444
|
+
// none is the same operation as replacing one that did.
|
|
1445
|
+
function runSetIntro(source, target, from, rawChannel, file, out) {
|
|
1446
|
+
if (target.unit.kind !== "heading") {
|
|
1447
|
+
fail(`--intro names a heading's opening region, and \`${target.label}\` is a \`${target.unit.type ?? target.unit.kind}\` block — use --body for a block's content`, 2);
|
|
1448
|
+
}
|
|
1449
|
+
const region = narrowToIntro(source, target.unit.span);
|
|
1450
|
+
let body = rawChannel ? readInput("-") : extractBlock(from, target.unit.id ?? "", "body");
|
|
1451
|
+
if (rawChannel && body === "")
|
|
1452
|
+
fail(NO_CONTENT, 1);
|
|
1453
|
+
body = toLf(body);
|
|
1454
|
+
if (body !== "" && !body.endsWith("\n"))
|
|
1455
|
+
body += "\n";
|
|
1456
|
+
// Give the opening its blank lines back. `get --intro` hands the region over
|
|
1457
|
+
// WITH the blank lines that separated it, so round-tripping that text lands
|
|
1458
|
+
// byte-identical and this adds nothing. Content typed by hand has no such
|
|
1459
|
+
// padding, and without it the result fuses: `# H1` then the text then `## H2`
|
|
1460
|
+
// on consecutive lines. `add` already settled this — one blank separator on
|
|
1461
|
+
// a side whose neighbour is not blank — so the two agree.
|
|
1462
|
+
const around = splitLines(source);
|
|
1463
|
+
const blankLine = (s) => s === undefined || stripEol(s).trim() === "";
|
|
1464
|
+
if (body !== "" && !blankLine(body.split("\n")[0]))
|
|
1465
|
+
body = "\n" + body;
|
|
1466
|
+
// A following heading needs the separation; end-of-document does not.
|
|
1467
|
+
if (body !== "" && region.end < around.length && !blankLine(body.split("\n").slice(-2)[0]))
|
|
1468
|
+
body += "\n";
|
|
1469
|
+
const updated = spliceSpan(source, region, body, file, false, false, target.unit.id);
|
|
1470
|
+
resolveOutTarget(file, out).write(updated);
|
|
1471
|
+
reportNewAddress(updated, target);
|
|
1472
|
+
}
|
|
1473
|
+
function runSetBody(source, target, from, rawChannel, file, out) {
|
|
1474
|
+
const found = target.unit.span;
|
|
1475
|
+
const lines = splitLines(source);
|
|
1476
|
+
const headLine = lines[found.start] ?? "";
|
|
1477
|
+
// A typed block keeps its closing fence; a heading section has none. Decided
|
|
1478
|
+
// by the same helper `get --body` uses, so the two agree on the span and the
|
|
1479
|
+
// §4 round-trip invariant holds.
|
|
1480
|
+
const closeLine = closeFenceLine(lines, found);
|
|
1481
|
+
let body;
|
|
1482
|
+
if (rawChannel) {
|
|
1483
|
+
body = readInput("-");
|
|
1484
|
+
if (body === "")
|
|
1485
|
+
fail(NO_CONTENT, 1);
|
|
1486
|
+
}
|
|
1487
|
+
else {
|
|
1488
|
+
body = extractBlock(from, target.unit.id ?? "", "body");
|
|
1489
|
+
}
|
|
1490
|
+
let head = headLine;
|
|
1491
|
+
if (head !== "" && !/(\r\n|\r|\n)$/.test(head))
|
|
1492
|
+
head += "\n";
|
|
1493
|
+
let b = toLf(body); // spliceBlock converts the result to the document's style
|
|
1494
|
+
if (closeLine !== null && b !== "" && !b.endsWith("\n"))
|
|
1495
|
+
b += "\n";
|
|
1496
|
+
const replacement = closeLine !== null ? head + b + closeLine : head + b;
|
|
1497
|
+
// A typed block (closeLine !== null) must stay ONE block: enforce the
|
|
1498
|
+
// block-count invariant so a `===` fence in the raw body can't close it early
|
|
1499
|
+
// and inject siblings (SEC F2). A heading section body has no close fence and
|
|
1500
|
+
// may legitimately contain blocks, so it is not count-guarded.
|
|
1501
|
+
const updated = spliceSpan(source, found, replacement, file, false, closeLine !== null, target.unit.id);
|
|
1502
|
+
resolveOutTarget(file, out).write(updated);
|
|
1503
|
+
reportNewAddress(updated, target);
|
|
1504
|
+
}
|
|
1505
|
+
// `geml add <file|-> (--append | --before #x | --after #x) [--in F|F#src|-] [-o]`
|
|
1506
|
+
// — insert a GEML fragment (1+ blocks and/or prose) at a position. Unlike `set`,
|
|
1507
|
+
// `add` names no target id, so content keeps its OWN ids (no normalization); an
|
|
1508
|
+
// id colliding with the document (or duplicated within the fragment) makes the
|
|
1509
|
+
// re-parse fail and nothing is written. Bare prose is a valid fragment.
|
|
1510
|
+
function runAdd(args) {
|
|
1511
|
+
const out = flag(args, "-o") ?? flag(args, "--out");
|
|
1512
|
+
const from = flag(args, "--in");
|
|
1513
|
+
const before = flag(args, "--before");
|
|
1514
|
+
const after = flag(args, "--after");
|
|
1515
|
+
const append = args.includes("--append");
|
|
1516
|
+
const posCount = (append ? 1 : 0) + (before !== undefined ? 1 : 0) + (after !== undefined ? 1 : 0);
|
|
1517
|
+
if (posCount !== 1)
|
|
1518
|
+
fail("add needs exactly one position: --append | --before #id | --after #id", 2);
|
|
1519
|
+
const [file] = positionals(args, ["-o", "--out", "--in", "--before", "--after"]);
|
|
1520
|
+
if (!file)
|
|
1521
|
+
fail(SUBHELP.add);
|
|
1522
|
+
const rawChannel = from === undefined || from === "-";
|
|
1523
|
+
if (file === "-" && rawChannel)
|
|
1524
|
+
fail("reading the document from stdin needs --in for the new content", 2);
|
|
1525
|
+
const source = readInput(file);
|
|
1526
|
+
// Content: --in F#src -> block #src; --in F -> all of F (a multi-block
|
|
1527
|
+
// fragment is fine here); stdin -> raw. No id-normalization: add keeps ids.
|
|
1528
|
+
let content;
|
|
1529
|
+
if (rawChannel)
|
|
1530
|
+
content = readInput("-");
|
|
1531
|
+
else if (from.includes("#"))
|
|
1532
|
+
content = extractBlock(from, "", "whole");
|
|
1533
|
+
else
|
|
1534
|
+
content = readInput(from);
|
|
1535
|
+
if (content.trim() === "")
|
|
1536
|
+
fail("no content to add (use --in FILE or pipe it on stdin)", 1);
|
|
1537
|
+
// Resolve the physical-line insertion point.
|
|
1538
|
+
const lines = splitLines(source);
|
|
1539
|
+
let at;
|
|
1540
|
+
if (append) {
|
|
1541
|
+
at = lines.length;
|
|
1542
|
+
}
|
|
1543
|
+
else {
|
|
1544
|
+
const anchorId = (before ?? after).replace(/^#/, "");
|
|
1545
|
+
const span = blockSpans(source).get(anchorId);
|
|
1546
|
+
if (!span)
|
|
1547
|
+
fail(`no block with id \`${anchorId}\` in ${file === "-" ? "stdin" : file}`, 1);
|
|
1548
|
+
at = before !== undefined ? span.start : span.end;
|
|
1549
|
+
}
|
|
1550
|
+
const updated = insertFragment(source, lines, at, content, file);
|
|
1551
|
+
resolveOutTarget(file, out).write(updated);
|
|
1552
|
+
}
|
|
1553
|
+
// Splice `fragment` into `source` at physical-line index `at` (splitLines
|
|
1554
|
+
// coords), separating it from adjacent content with a single blank line so
|
|
1555
|
+
// blocks don't fuse, then GUARD: the re-parse must be error-free (a colliding
|
|
1556
|
+
// or duplicate id surfaces as an error diagnostic) and no pre-existing id may
|
|
1557
|
+
// vanish. Returns the updated text; on any violation fail()s and writes nothing.
|
|
1558
|
+
function insertFragment(source, lines, at, fragment, file) {
|
|
1559
|
+
const beforeIds = parse(source, { ...docOpts(file), self: file === "-" ? undefined : basename(file) }).ids;
|
|
1560
|
+
const before = lines.slice(0, at);
|
|
1561
|
+
const after = lines.slice(at);
|
|
1562
|
+
const nl = newlineOf(source); // the fragment AND every separator we add
|
|
1563
|
+
// The preceding line must end in a newline so the fragment starts on its own.
|
|
1564
|
+
if (before.length && !/(\r\n|\r|\n)$/.test(before[before.length - 1])) {
|
|
1565
|
+
before[before.length - 1] += nl;
|
|
1566
|
+
}
|
|
1567
|
+
let frag = toNewline(fragment, nl);
|
|
1568
|
+
if (!frag.endsWith("\n"))
|
|
1569
|
+
frag += nl;
|
|
1570
|
+
// A single blank separator on each side that has adjacent content and isn't
|
|
1571
|
+
// already blank — keeps a following head / preceding block from fusing.
|
|
1572
|
+
const blank = (s) => stripEol(s).trim() === "";
|
|
1573
|
+
const sepBefore = before.length && !blank(before[before.length - 1]) ? nl : "";
|
|
1574
|
+
const sepAfter = after.length && !blank(after[0]) ? nl : "";
|
|
1575
|
+
const updated = before.join("") + sepBefore + frag + sepAfter + after.join("");
|
|
1576
|
+
const reparsed = parse(updated, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
1577
|
+
const errs = reparsed.diagnostics.filter((d) => d.severity === "error");
|
|
1578
|
+
if (errs.length) {
|
|
1579
|
+
const first = errs[0];
|
|
1580
|
+
refuseBroken(`adding the content would break the document: ${first.message} (line ${first.line}); not written`, errs);
|
|
1581
|
+
}
|
|
1582
|
+
const now = new Set(reparsed.ids);
|
|
1583
|
+
const dropped = beforeIds.find((x) => !now.has(x));
|
|
1584
|
+
if (dropped !== undefined)
|
|
1585
|
+
fail(`adding the content would drop block \`#${dropped}\`; not written`, 1);
|
|
1586
|
+
return updated;
|
|
1587
|
+
}
|
|
1588
|
+
// `geml delete <file|-> #id [#id2 …] [-o]` — remove one or more blocks. A
|
|
1589
|
+
// missing id is SKIPPED with a note (declarative "ensure absent", not an
|
|
1590
|
+
// error). Unlike set/add, delete's write is LENIENT: removing a complete block
|
|
1591
|
+
// can't break the parse structurally, but it may leave a reference dangling —
|
|
1592
|
+
// that is a WARNING, never a refusal (delete is reversible via revert + history,
|
|
1593
|
+
// and `geml check` still flags the dangling ref afterward). Contained/overlapping
|
|
1594
|
+
// spans (a nested block inside a deleted heading section) are handled by deleting
|
|
1595
|
+
// the UNION of target lines, so a line is never spliced twice.
|
|
1596
|
+
function runDelete(args) {
|
|
1597
|
+
const out = flag(args, "-o") ?? flag(args, "--out");
|
|
1598
|
+
const pos = positionals(args, ["-o", "--out"]);
|
|
1599
|
+
const file = pos[0];
|
|
1600
|
+
if (!file)
|
|
1601
|
+
fail(SUBHELP.delete);
|
|
1602
|
+
const ids = pos.slice(1).map((s) => s.replace(/^#/, ""));
|
|
1603
|
+
if (ids.length === 0)
|
|
1604
|
+
fail("delete needs at least one #id (run 'geml get <file>' to list ids)", 2);
|
|
1605
|
+
const source = readInput(file);
|
|
1606
|
+
const spans = blockSpans(source);
|
|
1607
|
+
const toDelete = new Set();
|
|
1608
|
+
let found = 0;
|
|
1609
|
+
for (const id of ids) {
|
|
1610
|
+
const span = spans.get(id);
|
|
1611
|
+
if (!span) {
|
|
1612
|
+
console.error(`skipped #${id}: no such block`);
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
found++;
|
|
1616
|
+
for (let i = span.start; i < span.end; i++)
|
|
1617
|
+
toDelete.add(i);
|
|
1618
|
+
}
|
|
1619
|
+
if (found === 0) {
|
|
1620
|
+
resolveOutTarget(file, out).write(source);
|
|
1621
|
+
return;
|
|
1622
|
+
} // nothing to remove
|
|
1623
|
+
const updated = splitLines(source).filter((_, i) => !toDelete.has(i)).join("");
|
|
1624
|
+
// Lenient guard: surface any resulting error diagnostic (a reference now
|
|
1625
|
+
// dangling) as a WARNING, but write regardless.
|
|
1626
|
+
const reparsed = parse(updated, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
1627
|
+
for (const d of reparsed.diagnostics.filter((x) => x.severity === "error")) {
|
|
1628
|
+
console.error(`warning: ${d.message} (line ${d.line}) — left dangling by delete; run 'geml check' to see it as an error`);
|
|
1629
|
+
}
|
|
1630
|
+
resolveOutTarget(file, out).write(updated);
|
|
1631
|
+
}
|
|
1632
|
+
// `geml rename <file|-> #old #new [-o]` — the one verb that reaches OUTSIDE a
|
|
1633
|
+
// block: it rewrites #old's declaration AND every reference to it. #new must be
|
|
1634
|
+
// free; the guarded re-parse refuses anything that would break the doc.
|
|
1635
|
+
function runRename(args) {
|
|
1636
|
+
const out = flag(args, "-o") ?? flag(args, "--out");
|
|
1637
|
+
const [file, rawOld, rawNew] = positionals(args, ["-o", "--out"]);
|
|
1638
|
+
if (!file || !rawOld || !rawNew)
|
|
1639
|
+
fail(SUBHELP.rename);
|
|
1640
|
+
const oldId = rawOld.replace(/^#/, "");
|
|
1641
|
+
const newId = rawNew.replace(/^#/, "");
|
|
1642
|
+
if (oldId === newId)
|
|
1643
|
+
fail("#old and #new are the same id — nothing to rename", 2);
|
|
1644
|
+
const source = readInput(file);
|
|
1645
|
+
const before = parse(source, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
1646
|
+
if (!before.ids.includes(oldId))
|
|
1647
|
+
fail(`no block with id \`${oldId}\``, 1);
|
|
1648
|
+
if (before.ids.includes(newId))
|
|
1649
|
+
fail(`id \`${newId}\` already exists; not written`, 1);
|
|
1650
|
+
// Renaming an id that has recorded history breaks the revert-lineage for it
|
|
1651
|
+
// (revert keys by id and can't follow #old -> #new across the boundary). Warn
|
|
1652
|
+
// so the user knows a later `revert #new` won't reach pre-rename revisions.
|
|
1653
|
+
if (file !== "-") {
|
|
1654
|
+
const hp = historyPathFor(file);
|
|
1655
|
+
if (existsSync(hp)) {
|
|
1656
|
+
try {
|
|
1657
|
+
if (blockSpans(resolveContent(hp, "0").text).has(oldId)) {
|
|
1658
|
+
console.error(`warning: #${oldId} has history; revert across this rename is not tracked — see docs`);
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
catch { /* unreadable/empty history: no warning */ }
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
const updated = rewriteId(source, oldId, newId, file);
|
|
1665
|
+
const reparsed = parse(updated, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
1666
|
+
const errs = reparsed.diagnostics.filter((d) => d.severity === "error");
|
|
1667
|
+
if (errs.length) {
|
|
1668
|
+
const e = errs[0];
|
|
1669
|
+
refuseBroken(`rename would break the document: ${e.message} (line ${e.line}); not written`, errs);
|
|
1670
|
+
}
|
|
1671
|
+
if (!reparsed.ids.includes(newId))
|
|
1672
|
+
fail(`rename did not produce #${newId}; not written`, 1);
|
|
1673
|
+
if (reparsed.ids.includes(oldId))
|
|
1674
|
+
fail(`#${oldId} still present after rename; not written`, 1);
|
|
1675
|
+
// Every OTHER id must be untouched. The `#old` match boundary treats a char
|
|
1676
|
+
// outside [A-Za-z0-9_-] as an id terminator, but ids may contain e.g. `.`
|
|
1677
|
+
// (`#foo.bar`), so renaming `#foo` could silently rewrite the *different* id
|
|
1678
|
+
// `#foo.bar` -> `#baz.bar`. Reject when the set of ids other than the rename
|
|
1679
|
+
// pair changed at all (SEC/correctness: collateral id corruption).
|
|
1680
|
+
const othersBefore = before.ids.filter((id) => id !== oldId).sort().join("\n");
|
|
1681
|
+
const othersAfter = reparsed.ids.filter((id) => id !== newId).sort().join("\n");
|
|
1682
|
+
if (othersBefore !== othersAfter) {
|
|
1683
|
+
fail(`rename would also change other ids sharing the \`${oldId}\` prefix (e.g. \`#${oldId}…\`); not written`, 1);
|
|
1684
|
+
}
|
|
1685
|
+
resolveOutTarget(file, out).write(updated);
|
|
1686
|
+
}
|
|
1687
|
+
// Rewrite id `old` -> `new` everywhere it is a declaration or reference, id-
|
|
1688
|
+
// boundary-safe: `#old` is replaced only when NOT followed by an id char, so a
|
|
1689
|
+
// longer id like `#old2` / `#old-x` is untouched. Covers the declaration
|
|
1690
|
+
// (`{#old …}`, labeled close `=== #old`), block references (`[[#old]]`,
|
|
1691
|
+
// `[t](#old)`, chart `data=#old`) and footnotes (`[^old]`). RAW / data block
|
|
1692
|
+
// BODIES (code/diagram/math/table/meta) are skipped — a `#old` there is literal
|
|
1693
|
+
// text, not a reference. (Known residual: id-less raw bodies and inline
|
|
1694
|
+
// code/math spans in flow content — see design §8.)
|
|
1695
|
+
function rewriteId(source, oldId, newId, file) {
|
|
1696
|
+
const doc = parse(source, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
1697
|
+
const spans = blockSpans(source);
|
|
1698
|
+
const protectedLines = new Set();
|
|
1699
|
+
for (const b of doc.children) {
|
|
1700
|
+
if (b.kind === "block" && (b.mode === "raw" || b.mode === "data") && b.id) {
|
|
1701
|
+
const span = spans.get(b.id);
|
|
1702
|
+
if (span) {
|
|
1703
|
+
const br = bodyRange(source, span);
|
|
1704
|
+
for (let i = br.start; i < br.end; i++)
|
|
1705
|
+
protectedLines.add(i);
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
const esc = reLit(oldId);
|
|
1710
|
+
const hashRe = new RegExp(`#${esc}(?![A-Za-z0-9_-])`, "g");
|
|
1711
|
+
const fnRe = new RegExp(`(\\[\\^)${esc}(?![A-Za-z0-9_-])`, "g");
|
|
1712
|
+
const lines = splitLines(source);
|
|
1713
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1714
|
+
if (protectedLines.has(i))
|
|
1715
|
+
continue;
|
|
1716
|
+
lines[i] = lines[i].replace(hashRe, `#${newId}`).replace(fnRe, `$1${newId}`);
|
|
1717
|
+
}
|
|
1718
|
+
return lines.join("");
|
|
1719
|
+
}
|
|
1720
|
+
// Extract one block from a GEML file for `--in`. `spec` is `F` (block whose id
|
|
1721
|
+
// == the target) or `F#src` (block #src) — the last `#` splits path from id, so
|
|
1722
|
+
// a `#` inside the path is tolerated; F is read as GEML regardless of extension
|
|
1723
|
+
// (blockSpans + splitLines, no parse — same slice `geml get` prints). `part`
|
|
1724
|
+
// selects the whole span, its head line, or its body. A missing file or absent
|
|
1725
|
+
// id is an operation error (exit 1); the caller writes nothing.
|
|
1726
|
+
function extractBlock(spec, targetId, part) {
|
|
1727
|
+
const hash = spec.lastIndexOf("#");
|
|
1728
|
+
const fragFile = hash >= 0 ? spec.slice(0, hash) : spec;
|
|
1729
|
+
const fragId = hash >= 0 ? spec.slice(hash + 1).replace(/^#/, "") : targetId;
|
|
1730
|
+
let text;
|
|
1731
|
+
try {
|
|
1732
|
+
text = readFileSync(fragFile, "utf8");
|
|
1733
|
+
}
|
|
1734
|
+
catch {
|
|
1735
|
+
fail(`cannot read ${fragFile}`, 1);
|
|
1736
|
+
}
|
|
1737
|
+
const span = blockSpans(text).get(fragId);
|
|
1738
|
+
if (!span)
|
|
1739
|
+
fail(`no block with id \`${fragId}\` in ${fragFile}`, 1);
|
|
1740
|
+
const lines = splitLines(text);
|
|
1741
|
+
if (part === "head")
|
|
1742
|
+
return lines.slice(span.start, span.start + 1).join("");
|
|
1743
|
+
if (part === "body") {
|
|
1744
|
+
const b = bodyRange(text, span);
|
|
1745
|
+
return lines.slice(b.start, b.end).join("");
|
|
1746
|
+
}
|
|
1747
|
+
return lines.slice(span.start, span.end).join("");
|
|
1748
|
+
}
|
|
1749
|
+
// Strip a single trailing terminator (`\r\n`, `\r`, or `\n`) from one line.
|
|
1750
|
+
// One flag's value out of argv — the CLI's own tiny parser.
|
|
1751
|
+
function flag(args, name) {
|
|
1752
|
+
const i = args.indexOf(name);
|
|
1753
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
1754
|
+
}
|
|
1755
|
+
// The body sub-range of a block span: [head+1, close) for a closed typed block,
|
|
1756
|
+
// otherwise [head+1, end) — a heading section (no close fence) or an
|
|
1757
|
+
// unterminated block whose span already runs to end-of-scope.
|
|
1758
|
+
function bodyRange(text, span) {
|
|
1759
|
+
const lines = splitLines(text);
|
|
1760
|
+
const open = FENCE_OPEN.exec(stripEol(lines[span.start] ?? ""));
|
|
1761
|
+
if (open) {
|
|
1762
|
+
const lastText = trimSpaceTabEnd(stripEol(lines[span.end - 1] ?? ""));
|
|
1763
|
+
const bid = open[3] ? parseAttrs(open[3]).id : undefined;
|
|
1764
|
+
const labeled = bid !== undefined && new RegExp(`^={3,}[ \\t]+#${reLit(bid)}[ \\t]*$`).test(lastText);
|
|
1765
|
+
const closed = isCloseFence(lastText, open[1].length) || labeled;
|
|
1766
|
+
return { start: span.start + 1, end: closed ? span.end - 1 : span.end };
|
|
1767
|
+
}
|
|
1768
|
+
return { start: span.start + 1, end: span.end };
|
|
1769
|
+
}
|
|
1770
|
+
// The shape of default-mode stdin content, section-aware: a heading OWNS its
|
|
1771
|
+
// section (`# H …blocks…` is ONE unit, not many), matching sectionEnd/blockSpans.
|
|
1772
|
+
// Used to reject pure prose (-> --body) and multi-block content (-> add) before
|
|
1773
|
+
// the splice — extraction via --in is inherently one block and skips this.
|
|
1774
|
+
function contentShape(content) {
|
|
1775
|
+
const bs = parse(content).children;
|
|
1776
|
+
let blockUnits = 0, proseUnits = 0, i = 0;
|
|
1777
|
+
while (i < bs.length) {
|
|
1778
|
+
const b = bs[i];
|
|
1779
|
+
if (b.kind === "heading") {
|
|
1780
|
+
i = sectionEndIndex(bs, i);
|
|
1781
|
+
blockUnits++;
|
|
1782
|
+
}
|
|
1783
|
+
else if (b.kind === "block") {
|
|
1784
|
+
i++;
|
|
1785
|
+
blockUnits++;
|
|
1786
|
+
}
|
|
1787
|
+
else {
|
|
1788
|
+
i++;
|
|
1789
|
+
proseUnits++;
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
if (blockUnits === 0)
|
|
1793
|
+
return proseUnits === 0 ? "empty" : "prose";
|
|
1794
|
+
return blockUnits + proseUnits === 1 ? "single" : "multi";
|
|
1795
|
+
}
|
|
1796
|
+
// Replace block #id's source span in `source` with `replacement`, preserving
|
|
1797
|
+
// every other byte, and GUARD the result: the re-parse must be error-free, #id
|
|
1798
|
+
// must survive, and no other pre-existing id may vanish (a malformed replacement
|
|
1799
|
+
// can silently swallow a neighbour). Returns the updated document text; on any
|
|
1800
|
+
// violation it calls fail() and never returns a corrupt document. Shared by
|
|
1801
|
+
// `set` and `revert`.
|
|
1802
|
+
function spliceBlock(source, id, replacement, file, headOnly = false, guardCount = false) {
|
|
1803
|
+
const found = blockSpans(source).get(id);
|
|
1804
|
+
if (!found)
|
|
1805
|
+
fail(`no block with id \`${id}\``, 1);
|
|
1806
|
+
return spliceSpan(source, found, replacement, file, headOnly, guardCount, id);
|
|
1807
|
+
}
|
|
1808
|
+
// The same guarded splice addressed by SPAN rather than by id, because an
|
|
1809
|
+
// anonymous block (addressed by `@<hex>`) has no id to look one up with. `id`
|
|
1810
|
+
// is the survival guard's subject and is simply absent for those: every OTHER
|
|
1811
|
+
// pre-existing id must still survive, which the `dropped` check below covers.
|
|
1812
|
+
// How many typed blocks a document holds. Ids only account for the named ones,
|
|
1813
|
+
// so this is what makes an unnamed block's removal reportable instead of silent
|
|
1814
|
+
// — the whole point of treating both the same.
|
|
1815
|
+
function countBlockUnits(source) {
|
|
1816
|
+
let n = 0;
|
|
1817
|
+
for (const a of addressedUnits(source))
|
|
1818
|
+
if (a.unit.kind === "block")
|
|
1819
|
+
n++;
|
|
1820
|
+
return n;
|
|
1821
|
+
}
|
|
1822
|
+
function spliceSpan(source, found, replacement, file, headOnly = false, guardCount = false, id) {
|
|
1823
|
+
const beforeDoc = parse(source, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
1824
|
+
const beforeIds = beforeDoc.ids;
|
|
1825
|
+
// Keep the bytes before and after the target span exactly; give the new block
|
|
1826
|
+
// a single trailing newline so the following block still starts on its own
|
|
1827
|
+
// line (unless it is the file's last line, which may legitimately lack one).
|
|
1828
|
+
const orig = splitLines(source);
|
|
1829
|
+
// `--head`: splice only the id's head line; everything below stays
|
|
1830
|
+
// byte-identical. The guard below still applies — the replacement must
|
|
1831
|
+
// re-declare `{#id}` and, for a typed block, keep the fence pairing intact
|
|
1832
|
+
// (an opening line that no longer matches the untouched close fence breaks
|
|
1833
|
+
// the re-parse), or the splice is refused.
|
|
1834
|
+
const span = headOnly ? narrowToHead(found) : found;
|
|
1835
|
+
const before = orig.slice(0, span.start);
|
|
1836
|
+
const after = orig.slice(span.end);
|
|
1837
|
+
const nl = newlineOf(source); // adopt the document's style, not LF
|
|
1838
|
+
let inject = toNewline(replacement, nl);
|
|
1839
|
+
const lastLine = span.end >= orig.length;
|
|
1840
|
+
if (!inject.endsWith("\n") && !lastLine)
|
|
1841
|
+
inject += nl;
|
|
1842
|
+
const updated = before.join("") + inject + after.join("");
|
|
1843
|
+
// Re-parse and refuse a broken result. A parse error or a duplicate id both
|
|
1844
|
+
// surface as error diagnostics (registerId flags dups); one check covers both.
|
|
1845
|
+
//
|
|
1846
|
+
// Blocks the replacement REMOVES are a different matter, and they are reported
|
|
1847
|
+
// rather than refused. Refusing made the region unreachable: a section whose
|
|
1848
|
+
// opening held a `=== note {#n}` could not have that opening replaced at all,
|
|
1849
|
+
// while the same note without an id was dropped in silence — the block's fate
|
|
1850
|
+
// turned on whether someone had named it. `delete` already settled the stance
|
|
1851
|
+
// for a destructive edit: do it, and say what it cost (it writes, and warns
|
|
1852
|
+
// about references it left dangling). This follows that, so there is one rule
|
|
1853
|
+
// for removing content instead of two.
|
|
1854
|
+
//
|
|
1855
|
+
// Note the ordinary read-edit-write cycle never reaches this: `get --intro`
|
|
1856
|
+
// hands the blocks over, sending them back keeps them, and nothing is dropped.
|
|
1857
|
+
const reparsed = parse(updated, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
1858
|
+
const now = new Set(reparsed.ids);
|
|
1859
|
+
if (id !== undefined && !now.has(id))
|
|
1860
|
+
fail(`replacement removes id \`${id}\`; not written`, 1);
|
|
1861
|
+
const droppedIds = beforeIds.filter((x) => x !== id && !now.has(x));
|
|
1862
|
+
const droppedAnon = Math.max(0, countBlockUnits(source) - countBlockUnits(updated) - droppedIds.length);
|
|
1863
|
+
// A reference left dangling BY THE REMOVAL is a consequence the caller is
|
|
1864
|
+
// being told about, exactly as `delete` tells them. A reference the new
|
|
1865
|
+
// content itself introduces is a broken write and is still refused — the
|
|
1866
|
+
// difference is whether the missing target is one of the blocks this splice
|
|
1867
|
+
// took away.
|
|
1868
|
+
const collateral = (d) => droppedIds.some((x) => d.message.includes(`\`#${x}\``) || d.message.includes(`#${x}\``));
|
|
1869
|
+
const errs = reparsed.diagnostics.filter((d) => d.severity === "error" && !collateral(d));
|
|
1870
|
+
if (errs.length) {
|
|
1871
|
+
const first = errs[0];
|
|
1872
|
+
refuseBroken(`replacement would break the document: ${first.message} (line ${first.line}); not written`, errs);
|
|
1873
|
+
}
|
|
1874
|
+
if (droppedIds.length || droppedAnon) {
|
|
1875
|
+
const named = droppedIds.map((x) => `\`#${x}\``).join(", ");
|
|
1876
|
+
const anon = droppedAnon ? `${droppedAnon} unnamed block${droppedAnon > 1 ? "s" : ""}` : "";
|
|
1877
|
+
console.error(`dropped ${[named, anon].filter(Boolean).join(" and ")} — run 'geml revert' to put them back`);
|
|
1878
|
+
for (const d of reparsed.diagnostics.filter((x) => x.severity === "error" && collateral(x))) {
|
|
1879
|
+
console.error(`warning: ${d.message} (line ${d.line}) — left dangling by the replacement; run 'geml check' to see it as an error`);
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
// For a typed block with a close fence, the body is opaque and swapping it
|
|
1883
|
+
// keeps exactly ONE block. A raw `--body` can embed a `===` fence of the
|
|
1884
|
+
// block's length that closes the target early and turns the remainder — plus
|
|
1885
|
+
// the close line we re-appended — into NEW sibling blocks, including an id-less
|
|
1886
|
+
// `=== meta` that redefines document metadata (the dropped-id check above
|
|
1887
|
+
// cannot see an id-less injection). Guarded callers refuse any count change.
|
|
1888
|
+
// (Not enforced for heading sections / whole-block set, whose replacement may
|
|
1889
|
+
// legitimately span several top-level blocks.)
|
|
1890
|
+
if (guardCount && reparsed.children.length !== beforeDoc.children.length) {
|
|
1891
|
+
fail(`replacement changes the block count (a fence in the body closed ${id !== undefined ? `#${id}` : "the target"} early and injected sibling block(s)?); not written`, 1);
|
|
1892
|
+
}
|
|
1893
|
+
return updated;
|
|
1894
|
+
}
|
|
1895
|
+
// `geml revert <file.geml> #id [--rev <sel>] [--dry-run] [-o out] [--history PATH]`
|
|
1896
|
+
// Restore ONE block to a past revision's version — a targeted, guarded splice
|
|
1897
|
+
// that leaves the rest of the document untouched. <sel> (default `-1`): `0` (the
|
|
1898
|
+
// tip), `-N` (N revisions back), an id prefix/suffix, or `changed` — a content
|
|
1899
|
+
// selector that skips revisions which never touched the block, landing on its
|
|
1900
|
+
// previous *distinct* version. `--dry-run` prints what would be spliced in,
|
|
1901
|
+
// writing nothing. Writes in place by default (revert is a mutation); `-o` redirects.
|
|
1902
|
+
function runRevert(args) {
|
|
1903
|
+
const dryRun = args.includes("--dry-run");
|
|
1904
|
+
const headOnly = args.includes("--head");
|
|
1905
|
+
const out = flag(args, "-o") ?? flag(args, "--out");
|
|
1906
|
+
const to = flag(args, "--rev") ?? "-1";
|
|
1907
|
+
// `--rev changed` is a CONTENT selector, not a position: skip commits that
|
|
1908
|
+
// never touched this block, landing on its previous *distinct* version. It is
|
|
1909
|
+
// just a `--rev` value, so it cannot conflict with a positional `-N`.
|
|
1910
|
+
const changed = to === "changed";
|
|
1911
|
+
// The former standalone `--changed` flag is now this value; refuse the old
|
|
1912
|
+
// spelling loudly rather than silently ignoring it (and reverting to -1).
|
|
1913
|
+
if (args.includes("--changed"))
|
|
1914
|
+
fail("--changed is now `--rev changed`", 2);
|
|
1915
|
+
const before = flag(args, "--before");
|
|
1916
|
+
const after = flag(args, "--after");
|
|
1917
|
+
const append = args.includes("--append");
|
|
1918
|
+
if ((append ? 1 : 0) + (before !== undefined ? 1 : 0) + (after !== undefined ? 1 : 0) > 1) {
|
|
1919
|
+
fail("revert takes at most one position: --append | --before #id | --after #id", 2);
|
|
1920
|
+
}
|
|
1921
|
+
const [file, rawId] = positionals(args, ["--rev", "--history", "-o", "--out", "--before", "--after"]);
|
|
1922
|
+
if (!file || !rawId)
|
|
1923
|
+
fail(SUBHELP.revert);
|
|
1924
|
+
if (file === "-")
|
|
1925
|
+
fail("revert needs a real file (it reads that file's .gemlhistory)", 2);
|
|
1926
|
+
const id = rawId.replace(/^#/, "");
|
|
1927
|
+
const historyPath = flag(args, "--history") ?? historyPathFor(file);
|
|
1928
|
+
const source = readInput(file);
|
|
1929
|
+
// The sidecar stores every revision newline-NORMALIZED (history.ts), so a
|
|
1930
|
+
// revision's text always comes back LF while the working file may be CRLF.
|
|
1931
|
+
// Comparing those raw would make EVERY block look changed on a CRLF document
|
|
1932
|
+
// (`--rev changed` reverting blocks nobody touched, and the no-op check never
|
|
1933
|
+
// firing), so compare normalized and write back in the file's own style.
|
|
1934
|
+
const norm = toLf; // compare on the LF form
|
|
1935
|
+
const toFileNl = (s) => toNewline(s, newlineOf(source));
|
|
1936
|
+
const curFull = blockSpans(source).get(id); // undefined => absent now
|
|
1937
|
+
const curBlock = curFull === undefined ? undefined : (() => {
|
|
1938
|
+
const span = headOnly ? narrowToHead(curFull) : curFull;
|
|
1939
|
+
return splitLines(source).slice(span.start, span.end).join("");
|
|
1940
|
+
})();
|
|
1941
|
+
// Extract #id's block from a reconstructed revision (undefined => absent
|
|
1942
|
+
// there). Under `--head`, extract only the head line.
|
|
1943
|
+
const pick = (text) => {
|
|
1944
|
+
const s = blockSpans(text).get(id);
|
|
1945
|
+
if (!s)
|
|
1946
|
+
return undefined;
|
|
1947
|
+
const span = headOnly ? narrowToHead(s) : s;
|
|
1948
|
+
return splitLines(text).slice(span.start, span.end).join("");
|
|
1949
|
+
};
|
|
1950
|
+
// Resolve the source revision, formatting any history-layer error cleanly.
|
|
1951
|
+
const target = (() => {
|
|
1952
|
+
try {
|
|
1953
|
+
if (changed) {
|
|
1954
|
+
// `pick` reads normalized revision text, so normalize this side too.
|
|
1955
|
+
const found = firstChangedContent(historyPath, curBlock === undefined ? "" : norm(curBlock), pick);
|
|
1956
|
+
if (!found)
|
|
1957
|
+
fail(`no earlier revision changes \`${id}\``, 1);
|
|
1958
|
+
return found;
|
|
1959
|
+
}
|
|
1960
|
+
return resolveContent(historyPath, to);
|
|
1961
|
+
}
|
|
1962
|
+
catch (e) {
|
|
1963
|
+
fail(historyError(e, file, historyPath), 1);
|
|
1964
|
+
}
|
|
1965
|
+
})();
|
|
1966
|
+
const oldBlock = pick(target.text); // undefined => absent at R
|
|
1967
|
+
// Common write path (bespoke message; -o path redirects; -o - -> stdout).
|
|
1968
|
+
const emit = (updated, verb) => {
|
|
1969
|
+
const dest = out ?? file;
|
|
1970
|
+
if (dest === "-")
|
|
1971
|
+
process.stdout.write(updated);
|
|
1972
|
+
else
|
|
1973
|
+
writeFileSync(dest, updated);
|
|
1974
|
+
console.error(`${verb}${dest === file ? "" : dest === "-" ? " -> stdout" : ` -> ${dest}`}`);
|
|
1975
|
+
};
|
|
1976
|
+
// Reconcile #id between now and revision R across the four presence cells.
|
|
1977
|
+
if (curBlock === undefined && oldBlock === undefined) {
|
|
1978
|
+
fail(`\`${id}\` exists in neither the document nor ${target.id} (try --rev changed)`, 1);
|
|
1979
|
+
}
|
|
1980
|
+
// both present -> SPLICE (undo set)
|
|
1981
|
+
if (curBlock !== undefined && oldBlock !== undefined) {
|
|
1982
|
+
if (norm(oldBlock) === norm(curBlock)) {
|
|
1983
|
+
console.error(`#${id} is unchanged at ${target.id}; nothing to revert${changed ? "" : " (try --rev -2, or --rev changed)"}`);
|
|
1984
|
+
// A no-op still has to PRODUCE the document when an output destination was
|
|
1985
|
+
// asked for: `-o` means "write the result somewhere", and the result of a
|
|
1986
|
+
// no-op revert is the unchanged document. Returning silently here left
|
|
1987
|
+
// `-o -` consumers with exit 0 and empty stdout, which reads as "success,
|
|
1988
|
+
// and the document is now empty".
|
|
1989
|
+
if (out !== undefined)
|
|
1990
|
+
emit(source, `#${id} unchanged`);
|
|
1991
|
+
return;
|
|
1992
|
+
}
|
|
1993
|
+
const replacement = toFileNl(oldBlock); // keep the file's newline style
|
|
1994
|
+
if (dryRun) {
|
|
1995
|
+
console.error(`would revert #${id} to ${target.id}:`);
|
|
1996
|
+
process.stdout.write(replacement.endsWith("\n") ? replacement : replacement + "\n");
|
|
1997
|
+
return;
|
|
1998
|
+
}
|
|
1999
|
+
emit(spliceBlock(source, id, replacement, file, headOnly), `reverted #${id} to ${target.id}`);
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
// --head is only meaningful for the splice cell (it can't resurrect or remove).
|
|
2003
|
+
if (headOnly) {
|
|
2004
|
+
fail("--head only applies when the block exists in both the document and the target revision", 2);
|
|
2005
|
+
}
|
|
2006
|
+
// absent now, present at R -> RESURRECT (undo delete)
|
|
2007
|
+
if (curBlock === undefined && oldBlock !== undefined) {
|
|
2008
|
+
// Guard: if the block we'd resurrect is the same (modulo id) as one already
|
|
2009
|
+
// present under a different id, #id was likely renamed away — resurrecting
|
|
2010
|
+
// would duplicate it. Point at `rename` instead of writing.
|
|
2011
|
+
const cmpKey = normalizeBlockId(norm(oldBlock), "__cmp__");
|
|
2012
|
+
for (const [cid, cs] of blockSpans(source)) {
|
|
2013
|
+
if (cid === id)
|
|
2014
|
+
continue;
|
|
2015
|
+
const csrc = splitLines(source).slice(cs.start, cs.end).join("");
|
|
2016
|
+
if (normalizeBlockId(norm(csrc), "__cmp__") === cmpKey) {
|
|
2017
|
+
fail(`#${id} looks renamed to #${cid}; use 'rename #${cid} #${id}' to undo the rename`, 1);
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
const { at, where, warn } = resurrectPosition(source, target.text, id, before, after, append, file);
|
|
2021
|
+
const fragment = toFileNl(oldBlock); // keep the file's newline style
|
|
2022
|
+
if (dryRun) {
|
|
2023
|
+
console.error(`would resurrect #${id} from ${target.id} at ${where}:`);
|
|
2024
|
+
process.stdout.write(fragment.endsWith("\n") ? fragment : fragment + "\n");
|
|
2025
|
+
return;
|
|
2026
|
+
}
|
|
2027
|
+
if (warn)
|
|
2028
|
+
console.error(`warning: anchors for #${id} are gone; appended at end`);
|
|
2029
|
+
emit(insertFragment(source, splitLines(source), at, fragment, file), `resurrected #${id} from ${target.id} at ${where}`);
|
|
2030
|
+
return;
|
|
2031
|
+
}
|
|
2032
|
+
// present now, absent at R -> REMOVE (undo add)
|
|
2033
|
+
// Guard: if the block we'd remove is the same (modulo id) as one present at R
|
|
2034
|
+
// under a different id, #id was likely renamed IN — removing would delete a
|
|
2035
|
+
// renamed block. Point at `rename` instead (the dangerous direction).
|
|
2036
|
+
{
|
|
2037
|
+
const cmpKey = normalizeBlockId(norm(curBlock), "__cmp__");
|
|
2038
|
+
for (const [rid, rs] of blockSpans(target.text)) {
|
|
2039
|
+
if (rid === id)
|
|
2040
|
+
continue;
|
|
2041
|
+
const rsrc = splitLines(target.text).slice(rs.start, rs.end).join("");
|
|
2042
|
+
if (normalizeBlockId(rsrc, "__cmp__") === cmpKey) {
|
|
2043
|
+
fail(`#${id} looks renamed from #${rid}; revert would delete it — use 'rename #${id} #${rid}'`, 1);
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
if (dryRun) {
|
|
2048
|
+
console.error(`would remove #${id} (absent at ${target.id})`);
|
|
2049
|
+
return;
|
|
2050
|
+
}
|
|
2051
|
+
const span = curFull;
|
|
2052
|
+
const beforeIds = parse(source, { ...docOpts(file), self: file === "-" ? undefined : basename(file) }).ids;
|
|
2053
|
+
const updated = splitLines(source).filter((_, i) => i < span.start || i >= span.end).join("");
|
|
2054
|
+
const reparsed = parse(updated, { ...docOpts(file), self: file === "-" ? undefined : basename(file) });
|
|
2055
|
+
const errs = reparsed.diagnostics.filter((d) => d.severity === "error");
|
|
2056
|
+
if (errs.length) {
|
|
2057
|
+
const first = errs[0];
|
|
2058
|
+
refuseBroken(`removing #${id} would break the document: ${first.message} (line ${first.line}); not written`, errs);
|
|
2059
|
+
}
|
|
2060
|
+
const now = new Set(reparsed.ids);
|
|
2061
|
+
const dropped = beforeIds.find((x) => x !== id && !now.has(x));
|
|
2062
|
+
if (dropped !== undefined)
|
|
2063
|
+
fail(`removing #${id} would drop block \`#${dropped}\`; not written`, 1);
|
|
2064
|
+
emit(updated, `removed #${id} (absent at ${target.id})`);
|
|
2065
|
+
}
|
|
2066
|
+
// Choose the physical-line insertion point for a resurrected block. Explicit
|
|
2067
|
+
// --append/--before/--after win; otherwise infer from the block's neighbours in
|
|
2068
|
+
// revision R: the nearest id BEFORE it that still exists now (insert after it),
|
|
2069
|
+
// else the nearest id AFTER it that still exists (insert before it), else append
|
|
2070
|
+
// at end (warn=true). The deleted block's own former descendants are absent now
|
|
2071
|
+
// too, so they are naturally skipped as anchors.
|
|
2072
|
+
function resurrectPosition(source, revText, id, before, after, append, file) {
|
|
2073
|
+
const lines = splitLines(source);
|
|
2074
|
+
const here = blockSpans(source);
|
|
2075
|
+
if (append)
|
|
2076
|
+
return { at: lines.length, where: "end", warn: false };
|
|
2077
|
+
if (before !== undefined) {
|
|
2078
|
+
const a = before.replace(/^#/, "");
|
|
2079
|
+
const s = here.get(a);
|
|
2080
|
+
if (!s)
|
|
2081
|
+
fail(`no block with id \`${a}\` in ${file}`, 1);
|
|
2082
|
+
return { at: s.start, where: `before #${a}`, warn: false };
|
|
2083
|
+
}
|
|
2084
|
+
if (after !== undefined) {
|
|
2085
|
+
const a = after.replace(/^#/, "");
|
|
2086
|
+
const s = here.get(a);
|
|
2087
|
+
if (!s)
|
|
2088
|
+
fail(`no block with id \`${a}\` in ${file}`, 1);
|
|
2089
|
+
return { at: s.end, where: `after #${a}`, warn: false };
|
|
2090
|
+
}
|
|
2091
|
+
const revIds = [...blockSpans(revText).keys()];
|
|
2092
|
+
const idx = revIds.indexOf(id);
|
|
2093
|
+
for (let i = idx - 1; i >= 0; i--) {
|
|
2094
|
+
const s = here.get(revIds[i]);
|
|
2095
|
+
if (s)
|
|
2096
|
+
return { at: s.end, where: `after #${revIds[i]}`, warn: false };
|
|
2097
|
+
}
|
|
2098
|
+
for (let i = idx + 1; i < revIds.length; i++) {
|
|
2099
|
+
const s = here.get(revIds[i]);
|
|
2100
|
+
if (s)
|
|
2101
|
+
return { at: s.start, where: `before #${revIds[i]}`, warn: false };
|
|
2102
|
+
}
|
|
2103
|
+
return { at: lines.length, where: "end", warn: true };
|
|
2104
|
+
}
|
|
2105
|
+
// geml codemap <sub>: the code-graph toolkit ships as plain scripts in the
|
|
2106
|
+
// package's codemap/ directory (they are argv-driven programs, some
|
|
2107
|
+
// long-running like `serve`) — dispatch = run the script in a child node
|
|
2108
|
+
// with the remaining arguments, propagating the exit code.
|
|
2109
|
+
function runCodemap(args) {
|
|
2110
|
+
const scripts = {
|
|
2111
|
+
build: "build.mjs",
|
|
2112
|
+
verify: "verify.mjs",
|
|
2113
|
+
render: "render-all.mjs",
|
|
2114
|
+
serve: "serve.mjs",
|
|
2115
|
+
refresh: "refresh.mjs",
|
|
2116
|
+
find: "find.mjs",
|
|
2117
|
+
};
|
|
2118
|
+
const sub = args[0] ?? "";
|
|
2119
|
+
// `codemap mcp` was a second stdio server over the same repository. It is
|
|
2120
|
+
// gone, not renamed, so name the replacement instead of letting it fall into
|
|
2121
|
+
// `unknown codemap subcommand`: this string is what an operator sees in a
|
|
2122
|
+
// client's server log when the entry they registered stops starting.
|
|
2123
|
+
if (sub === "mcp") {
|
|
2124
|
+
fail("geml codemap mcp was removed: use `geml mcp --root <dir>`, which serves the three code-graph tools alongside the document tools (graph: <root>/.geml-code-graph, or --graph <dir>).");
|
|
2125
|
+
}
|
|
2126
|
+
const script = scripts[sub];
|
|
2127
|
+
if (!script)
|
|
2128
|
+
fail(`unknown codemap subcommand '${sub}'.\n${SUBHELP.codemap}`);
|
|
2129
|
+
const mod = join(dirname(fileURLToPath(import.meta.url)), "..", "codemap", script);
|
|
2130
|
+
const r = spawnSync(process.execPath, [mod, ...args.slice(1)], { stdio: "inherit" });
|
|
2131
|
+
process.exit(r.status ?? 1);
|
|
2132
|
+
}
|
|
2133
|
+
// geml mcp: the MCP server — document CRUD, plus the code-graph tools when the
|
|
2134
|
+
// root holds a graph. It runs as a child's MAIN module because it owns
|
|
2135
|
+
// stdin/stdout for the whole session (the stdio transport), and dispatching by
|
|
2136
|
+
// spawn keeps this module free of a runtime import cycle (mcp.js imports the
|
|
2137
|
+
// parser from here).
|
|
2138
|
+
function runMcp(args) {
|
|
2139
|
+
const mod = join(dirname(fileURLToPath(import.meta.url)), "mcp.js");
|
|
2140
|
+
const r = spawnSync(process.execPath, [mod, ...args], { stdio: "inherit" });
|
|
2141
|
+
process.exit(r.status ?? 1);
|
|
2142
|
+
}
|
|
2143
|
+
// geml skill install: one command that makes GEML usable everywhere for a
|
|
2144
|
+
// Claude Code user — the authoring skill resident under ~/.claude/skills/geml,
|
|
2145
|
+
// the CLI on the global PATH, and the MCP server registered at user scope.
|
|
2146
|
+
// Deliberately quiet: no settings.json edits, no hooks, no .gemlhistory
|
|
2147
|
+
// sidecars. Idempotent, so re-running after an upgrade refreshes everything.
|
|
2148
|
+
// The other agent tools: install by DETECTION, never by creation. A tool's
|
|
2149
|
+
// own context file is the one place it is guaranteed to read, so the skill
|
|
2150
|
+
// text goes there — inside a marker pair, so a re-run refreshes our block and
|
|
2151
|
+
// nothing a person wrote is ever touched. If the tool's directory is absent
|
|
2152
|
+
// the tool is absent: skip it and say so. Creating `~/.gemini/` for someone
|
|
2153
|
+
// who does not use Gemini would be a lie on disk.
|
|
2154
|
+
const SKILL_MARK_START = "<!-- geml:skill:start -->";
|
|
2155
|
+
const SKILL_MARK_END = "<!-- geml:skill:end -->";
|
|
2156
|
+
// Where each tool reads its instructions from. `dir` is the detection probe:
|
|
2157
|
+
// present means the tool is installed for this user (or, for a project file,
|
|
2158
|
+
// that the project already keeps one).
|
|
2159
|
+
const SKILL_TARGETS = [
|
|
2160
|
+
{ name: "gemini", dir: join(homedir(), ".gemini"), file: join(homedir(), ".gemini", "GEMINI.md"), scope: "user" },
|
|
2161
|
+
{ name: "qwen", dir: join(homedir(), ".qwen"), file: join(homedir(), ".qwen", "QWEN.md"), scope: "user" },
|
|
2162
|
+
// AGENTS.md is read by several tools and lives in a project, so the probe is
|
|
2163
|
+
// the file itself: we add our block to one that exists, never start one.
|
|
2164
|
+
{ name: "agents-md", dir: resolvePath("AGENTS.md"), file: resolvePath("AGENTS.md"), scope: "project" },
|
|
2165
|
+
];
|
|
2166
|
+
// The skill text as another tool should see it: the packaged SKILL.md without
|
|
2167
|
+
// its Claude-only frontmatter, with `<skill-base>` resolved to where the
|
|
2168
|
+
// reference document actually landed, so `geml get …/authoring.geml '#tables'`
|
|
2169
|
+
// is a command the reader can paste.
|
|
2170
|
+
function skillTextFor(src, installedAt) {
|
|
2171
|
+
const body = readFileSync(join(src, "SKILL.md"), "utf8").replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n+/, "");
|
|
2172
|
+
return `${SKILL_MARK_START}\n<!-- Written by \`geml skill install\`. Edit the source, not this block: it is replaced on the next run. -->\n\n${body.replace(/<skill-base>/g, installedAt.replace(/\\/g, "/")).trimEnd()}\n${SKILL_MARK_END}\n`;
|
|
2173
|
+
}
|
|
2174
|
+
function installOtherTools(src, installedAt, dryRun) {
|
|
2175
|
+
const block = skillTextFor(src, installedAt);
|
|
2176
|
+
let ok = 0;
|
|
2177
|
+
let failed = 0;
|
|
2178
|
+
for (const t of SKILL_TARGETS) {
|
|
2179
|
+
if (!existsSync(t.dir)) {
|
|
2180
|
+
console.log(`${t.name.padEnd(6)} not detected — skipped (${t.scope === "project" ? "no AGENTS.md here" : `no ${t.dir}`})`);
|
|
2181
|
+
continue;
|
|
2182
|
+
}
|
|
2183
|
+
// Reading is as failure-prone as writing — the name may be a directory, or
|
|
2184
|
+
// unreadable — so the WHOLE per-target step sits inside the guard. One bad
|
|
2185
|
+
// path is reported and stepped over; it never reaches the next target as a
|
|
2186
|
+
// stack trace.
|
|
2187
|
+
try {
|
|
2188
|
+
const had = existsSync(t.file) ? readFileSync(t.file, "utf8") : "";
|
|
2189
|
+
const s = had.indexOf(SKILL_MARK_START);
|
|
2190
|
+
const e = had.indexOf(SKILL_MARK_END);
|
|
2191
|
+
// A marker pair means we have been here: replace just that span, so the
|
|
2192
|
+
// file's own content survives an upgrade untouched.
|
|
2193
|
+
const next = s >= 0 && e > s
|
|
2194
|
+
? had.slice(0, s) + block + had.slice(e + SKILL_MARK_END.length).replace(/^\r?\n/, "")
|
|
2195
|
+
: (had.trimEnd() ? `${had.trimEnd()}\n\n${block}` : block);
|
|
2196
|
+
if (next === had) {
|
|
2197
|
+
console.log(`${t.name.padEnd(6)} already current -> ${t.file}`);
|
|
2198
|
+
continue;
|
|
2199
|
+
}
|
|
2200
|
+
if (dryRun) {
|
|
2201
|
+
console.log(`${t.name.padEnd(6)} would ${s >= 0 ? "refresh" : "add"} the skill block -> ${t.file}`);
|
|
2202
|
+
continue;
|
|
2203
|
+
}
|
|
2204
|
+
// Atomic: this file can hold the person's own rules, and a half-written
|
|
2205
|
+
// one would destroy them. Write beside it, then rename over.
|
|
2206
|
+
const tmp = `${t.file}.geml-tmp`;
|
|
2207
|
+
writeFileSync(tmp, next);
|
|
2208
|
+
renameSync(tmp, t.file);
|
|
2209
|
+
console.log(`${t.name.padEnd(6)} ${s >= 0 ? "refreshed" : "added"} the skill block -> ${t.file}`);
|
|
2210
|
+
ok++;
|
|
2211
|
+
}
|
|
2212
|
+
catch (err) {
|
|
2213
|
+
// A read-only home, a file another process holds open, a name that is
|
|
2214
|
+
// not a file — say which target and why, then carry on.
|
|
2215
|
+
console.error(`${t.name.padEnd(6)} could not update ${t.file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2216
|
+
failed++;
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
return { ok, failed };
|
|
2220
|
+
}
|
|
2221
|
+
function runSkill(args) {
|
|
2222
|
+
const sub = args[0];
|
|
2223
|
+
if (sub !== "install")
|
|
2224
|
+
fail(`unknown skill subcommand '${sub ?? ""}'.\n${SUBHELP.skill}`);
|
|
2225
|
+
const rest = args.slice(1);
|
|
2226
|
+
const flag = (name) => {
|
|
2227
|
+
const i = rest.indexOf(name);
|
|
2228
|
+
if (i >= 0)
|
|
2229
|
+
rest.splice(i, 1);
|
|
2230
|
+
return i >= 0;
|
|
2231
|
+
};
|
|
2232
|
+
const opt = (name) => {
|
|
2233
|
+
const i = rest.indexOf(name);
|
|
2234
|
+
if (i < 0)
|
|
2235
|
+
return undefined;
|
|
2236
|
+
const v = rest[i + 1];
|
|
2237
|
+
if (!v)
|
|
2238
|
+
fail(`${name} needs a value.\n${SUBHELP.skill}`);
|
|
2239
|
+
rest.splice(i, 2);
|
|
2240
|
+
return v;
|
|
2241
|
+
};
|
|
2242
|
+
const noGlobal = flag("--no-global");
|
|
2243
|
+
const noMcp = flag("--no-mcp");
|
|
2244
|
+
const dryRun = flag("--dry-run");
|
|
2245
|
+
const dest = opt("--dest") ?? join(homedir(), ".claude", "skills");
|
|
2246
|
+
if (rest.length)
|
|
2247
|
+
fail(`unexpected argument '${rest[0]}'.\n${SUBHELP.skill}`);
|
|
2248
|
+
// The skill ships inside the npm package, next to dist/ — the installed
|
|
2249
|
+
// skill text always matches the CLI version it teaches.
|
|
2250
|
+
const src = join(dirname(fileURLToPath(import.meta.url)), "..", "skill");
|
|
2251
|
+
if (!existsSync(join(src, "SKILL.md")))
|
|
2252
|
+
fail(`bundled skill not found at ${src} (broken install?)`, 1);
|
|
2253
|
+
const target = join(dest, "geml");
|
|
2254
|
+
const copied = [];
|
|
2255
|
+
const copyTree = (from, to) => {
|
|
2256
|
+
mkdirSync(to, { recursive: true });
|
|
2257
|
+
for (const e of readdirSync(from, { withFileTypes: true })) {
|
|
2258
|
+
// Never ship a history sidecar — skill and config docs carry none.
|
|
2259
|
+
if (e.name.endsWith(".gemlhistory"))
|
|
2260
|
+
continue;
|
|
2261
|
+
const f = join(from, e.name);
|
|
2262
|
+
const t = join(to, e.name);
|
|
2263
|
+
if (e.isDirectory())
|
|
2264
|
+
copyTree(f, t);
|
|
2265
|
+
else {
|
|
2266
|
+
copyFileSync(f, t);
|
|
2267
|
+
copied.push(relative(dest, t));
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
};
|
|
2271
|
+
let ok = 0;
|
|
2272
|
+
let failed = 0;
|
|
2273
|
+
if (dryRun) {
|
|
2274
|
+
console.log(`skill would install -> ${target}`);
|
|
2275
|
+
}
|
|
2276
|
+
else {
|
|
2277
|
+
try {
|
|
2278
|
+
copyTree(src, target);
|
|
2279
|
+
console.log(`skill installed -> ${target} (${copied.join(", ")})`);
|
|
2280
|
+
ok++;
|
|
2281
|
+
}
|
|
2282
|
+
catch (e) {
|
|
2283
|
+
// Not fatal, and deliberately so: an unwritable `~/.claude` — a locked
|
|
2284
|
+
// file, a read-only home, a name that is not a directory — must not stop
|
|
2285
|
+
// the tools that CAN be installed. A clean one-liner, never a raw stack.
|
|
2286
|
+
console.error(`skill could not install to ${target}: ${e instanceof Error ? e.message : String(e)}`);
|
|
2287
|
+
failed++;
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
const other = installOtherTools(src, target, dryRun);
|
|
2291
|
+
ok += other.ok;
|
|
2292
|
+
failed += other.failed;
|
|
2293
|
+
// Windows npm/claude/geml are .cmd shims: they need a shell. Every argument
|
|
2294
|
+
// below is a fixed literal, so shell:true adds no injection surface.
|
|
2295
|
+
const sh = process.platform === "win32";
|
|
2296
|
+
const run = (cmd, a, inherit = false) => spawnSync(cmd, a, { shell: sh, encoding: "utf8", ...(inherit ? { stdio: "inherit" } : {}) });
|
|
2297
|
+
if (!noGlobal) {
|
|
2298
|
+
const have = run("geml", ["--version"]);
|
|
2299
|
+
if (have.status === 0) {
|
|
2300
|
+
console.log(`cli ${String(have.stdout ?? "").trim()} already on PATH`);
|
|
2301
|
+
}
|
|
2302
|
+
else {
|
|
2303
|
+
console.log("cli installing @geml/geml globally (npm i -g)...");
|
|
2304
|
+
const r = run("npm", ["install", "-g", "@geml/geml", "--no-audit", "--no-fund", "--loglevel=error"], true);
|
|
2305
|
+
if (r.status !== 0)
|
|
2306
|
+
console.error("cli global install failed — install later with: npm i -g @geml/geml");
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
if (!noMcp) {
|
|
2310
|
+
const REG = "claude mcp add --scope user geml -- npx -y @geml/geml mcp --root .";
|
|
2311
|
+
const claude = run("claude", ["--version"]);
|
|
2312
|
+
if (claude.status !== 0) {
|
|
2313
|
+
console.log(`mcp claude CLI not found — register later with: ${REG}`);
|
|
2314
|
+
}
|
|
2315
|
+
else if (run("claude", ["mcp", "get", "geml"]).status === 0) {
|
|
2316
|
+
console.log("mcp server 'geml' already registered");
|
|
2317
|
+
}
|
|
2318
|
+
else {
|
|
2319
|
+
const r = run("claude", ["mcp", "add", "--scope", "user", "geml", "--", "npx", "-y", "@geml/geml", "mcp", "--root", "."]);
|
|
2320
|
+
if (r.status === 0)
|
|
2321
|
+
console.log("mcp registered user-scope server 'geml' (confined to each session's project directory)");
|
|
2322
|
+
else
|
|
2323
|
+
console.error(`mcp registration failed (${String(r.stderr ?? "").trim() || "unknown"}) — register later with: ${REG}`);
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
// Every step is independent, so a single unwritable path is reported and
|
|
2327
|
+
// stepped over. Exit non-zero only when NOTHING landed — that is the one
|
|
2328
|
+
// outcome a caller has to react to; a partial install is still an install.
|
|
2329
|
+
if (failed > 0 && ok === 0) {
|
|
2330
|
+
console.error(`nothing was installed (${failed} target(s) failed) — see the messages above.`);
|
|
2331
|
+
process.exit(1);
|
|
2332
|
+
}
|
|
2333
|
+
if (failed > 0)
|
|
2334
|
+
console.log(`done — ${ok} target(s) installed, ${failed} skipped after an error.`);
|
|
2335
|
+
else
|
|
2336
|
+
console.log("done — new Claude Code sessions pick up the skill.");
|
|
2337
|
+
process.exit(0);
|
|
2338
|
+
}
|
|
2339
|
+
// npm's unix bin shim is a symlink named plain `geml`, so detect "run as a
|
|
2340
|
+
// CLI" by resolving argv[1] to its real path, not by its spelling.
|
|
2341
|
+
const entry = (() => {
|
|
2342
|
+
const argv1 = process.argv[1];
|
|
2343
|
+
if (!argv1)
|
|
2344
|
+
return "";
|
|
2345
|
+
try {
|
|
2346
|
+
return realpathSync(argv1);
|
|
2347
|
+
}
|
|
2348
|
+
catch {
|
|
2349
|
+
return argv1;
|
|
2350
|
+
}
|
|
2351
|
+
})();
|
|
2352
|
+
// This module IS the command line — importing it means running it. There is no
|
|
2353
|
+
// entry test any more, and there must not be: the legacy `dist/geml.js` entry
|
|
2354
|
+
// reaches this file through a dynamic import, so argv[1] names *that* file, and
|
|
2355
|
+
// a test comparing it against this one would silently do nothing (it did).
|
|
2356
|
+
// `entry` is still computed above, because a couple of messages report it.
|
|
2357
|
+
{
|
|
2358
|
+
void entry;
|
|
2359
|
+
const argv = process.argv.slice(2);
|
|
2360
|
+
// The on-disk artifact is `.geml-code-graph/`, so people reconstruct the
|
|
2361
|
+
// command from the directory name — accept those spellings as `codemap`.
|
|
2362
|
+
const cmd = argv[0] === "codegraph" || argv[0] === "code-graph" ? "codemap" : argv[0];
|
|
2363
|
+
jsonMode = argv.includes("--json");
|
|
2364
|
+
const rest = argv.slice(1);
|
|
2365
|
+
if (cmd === "--help" || cmd === "-h") {
|
|
2366
|
+
console.log(USAGE);
|
|
2367
|
+
}
|
|
2368
|
+
else if (cmd === "--version" || cmd === "-V") {
|
|
2369
|
+
if (jsonMode)
|
|
2370
|
+
console.log(JSON.stringify({ parser: PARSER_VERSION, spec: VERSION }));
|
|
2371
|
+
else
|
|
2372
|
+
console.log(`geml ${PARSER_VERSION} (GEML spec ${VERSION})`);
|
|
2373
|
+
}
|
|
2374
|
+
else if (cmd === undefined) {
|
|
2375
|
+
console.error(USAGE);
|
|
2376
|
+
process.exit(2);
|
|
2377
|
+
}
|
|
2378
|
+
else if (SUBHELP[cmd] && (rest.includes("--help") || rest.includes("-h"))) {
|
|
2379
|
+
// `geml <cmd> --help` is a help request, not a usage error: usage to
|
|
2380
|
+
// stdout, exit 0 — never the `error:`-prefixed exit-2 path.
|
|
2381
|
+
console.log(SUBHELP[cmd]);
|
|
2382
|
+
}
|
|
2383
|
+
else if (cmd === "get") {
|
|
2384
|
+
runGet(argv.slice(1));
|
|
2385
|
+
}
|
|
2386
|
+
else if (cmd === "list") {
|
|
2387
|
+
runList(argv.slice(1));
|
|
2388
|
+
}
|
|
2389
|
+
else if (cmd === "find") {
|
|
2390
|
+
runFind(argv.slice(1));
|
|
2391
|
+
}
|
|
2392
|
+
else if (cmd === "set") {
|
|
2393
|
+
runSet(argv.slice(1));
|
|
2394
|
+
}
|
|
2395
|
+
else if (cmd === "add") {
|
|
2396
|
+
runAdd(argv.slice(1));
|
|
2397
|
+
}
|
|
2398
|
+
else if (cmd === "delete") {
|
|
2399
|
+
runDelete(argv.slice(1));
|
|
2400
|
+
}
|
|
2401
|
+
else if (cmd === "rename") {
|
|
2402
|
+
runRename(argv.slice(1));
|
|
2403
|
+
}
|
|
2404
|
+
else if (cmd === "revert") {
|
|
2405
|
+
runRevert(argv.slice(1));
|
|
2406
|
+
}
|
|
2407
|
+
else if (cmd === "history") {
|
|
2408
|
+
runHistory(argv.slice(1));
|
|
2409
|
+
}
|
|
2410
|
+
else if (cmd === "check") {
|
|
2411
|
+
runCheck(argv.slice(1));
|
|
2412
|
+
}
|
|
2413
|
+
else if (cmd === "codemap") {
|
|
2414
|
+
runCodemap(argv.slice(1));
|
|
2415
|
+
}
|
|
2416
|
+
else if (cmd === "mcp") {
|
|
2417
|
+
runMcp(argv.slice(1));
|
|
2418
|
+
}
|
|
2419
|
+
else if (cmd === "skill") {
|
|
2420
|
+
runSkill(argv.slice(1));
|
|
2421
|
+
}
|
|
2422
|
+
else if (cmd !== "-" && !/[.\/\\]/.test(cmd)) {
|
|
2423
|
+
// A bare word that is neither a known command nor a path is almost always
|
|
2424
|
+
// a mistyped command — say so, don't try to read it as a file. (The
|
|
2425
|
+
// reclaimed verbs render/export/fmt/convert land here too.)
|
|
2426
|
+
fail(`unknown command '${cmd}'. Run 'geml --help'.`);
|
|
2427
|
+
}
|
|
2428
|
+
else {
|
|
2429
|
+
// A file (or stdin via '-') is the transform entry: `--to`/`--from`/`-o`,
|
|
2430
|
+
// default `--to json`. The single door for every format conversion.
|
|
2431
|
+
runTransform(argv);
|
|
2432
|
+
}
|
|
2433
|
+
}
|