@henols/c64-re-tools 2.3.0 → 2.4.0-rc.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.3.0",
3
+ "version": "2.4.0-rc.1",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -28,6 +28,7 @@ To get the command list, run the script with no arguments.
28
28
  | Check that each link is up to date, and write nothing | `link README.md docs --source src --check` |
29
29
  | Link the pages when the reference is in a folder with another name | `link README.md docs --source src --reference docs/lookup` |
30
30
  | Link one page | `link docs/main_loop.md --source src` |
31
+ | In a group folder, link the shared pages and the pages of each project | `link README.md docs v1/README.md v1/docs v2/README.md v2/docs --source src` |
31
32
 
32
33
  ---
33
34
 
@@ -60,6 +61,17 @@ Get the values for the commands from these places:
60
61
  - Put a run that is evidence in `runs/<name>/`, with its run file, its results and its snapshot files. Change the paths in the run file to the new paths. Then git keeps them, and another person can do the run again.
61
62
  - A shell redirect (`>`) is relative to the working directory, not to the project folder. From the folder above the project, write `<folder>/.c64-re-tools/local/result.json`.
62
63
 
64
+ ### The group folder
65
+
66
+ A group folder holds one project for each version of a program. It also holds the pages that the versions share.
67
+
68
+ - A group folder is a folder in a git repository. It holds one or more project folders. It is not a project, and it is not in a project.
69
+ - Each project folder in the group folder is a project of the group. The label of the project is the name of its folder, for example `v1`. A project folder that holds `.git` is not a project of the group.
70
+ - The shared pages are `README.md` and `docs/` of the group folder.
71
+ - A page in the group folder can link to each file in the group folder. A link out of the group folder is a problem.
72
+ - Give each project the same folder for the source and the same folder for the reference, for example `src` and `docs/reference`. `--source` and `--reference` apply to each project.
73
+ - To link the shared pages, run `link` in the group folder. Give the pages relative to the group folder. From a different folder, give `--project <group folder>`.
74
+
63
75
  ---
64
76
 
65
77
  ## Flags
@@ -69,8 +81,8 @@ Each flag applies only to the commands in the table. On another command, the scr
69
81
  | Flag | Command | Effect |
70
82
  |---|---|---|
71
83
  | `--out <dir>` | `generate` | Required. The folder of the reference, relative to the project folder. `generate` writes only there. It refuses to start when the folder holds a page that it did not write. |
72
- | `--source <dir>` | `link` | Required. The folder of the generated source, with its `source-map.json`. |
73
- | `--reference <dir>` | `link` | The folder of the reference. The default is the first `reference` folder in a given folder or beside a given page, for example `docs/reference`. |
84
+ | `--source <dir>` | `link` | Required. The folder of the generated source, with its `source-map.json`, relative to the project folder. In a group folder, each project has its source in this folder. |
85
+ | `--reference <dir>` | `link` | The folder of the reference, relative to the project folder. In a group folder, each project has its reference in this folder. The default is the first `reference` folder in a given folder or beside a given page, for example `docs/reference`. |
74
86
  | `--check` | `link` | Write nothing. `result` is `FAIL` when a link is not up to date or a page has a problem. Off by default. |
75
87
  | `--max-listed <n>` | `generate`, `link` | List at most `n` items in each list. The default is 50. The count is always in the body. |
76
88
 
@@ -115,6 +127,7 @@ Errors and their actions:
115
127
 
116
128
  - The reference draws each sprite, bitmap and charset region, and it decodes each table. To get the image of a graphic or the entries of a table, classify its region in the project knowledge. Do not write a script that draws or decodes them.
117
129
  - A script of the project decodes only a format of the program, for example a packed map or a music stream. Put the script in `tools/` of the project. Its output files are the assets, for example in `assets/rooms/`.
130
+ - When two or more projects of a group folder use the script, put it in `tools/` of the group folder. The script takes the paths of its input and output files as arguments.
118
131
  - When the code of the program makes the data, run that code in a test run. Read the memory, or capture the screen. Do not write a 6502 emulator in the script.
119
132
 
120
133
  ---
@@ -141,13 +154,25 @@ These are the forms that it changes. The examples are for a page in `docs/`. In
141
154
  - When the line of a name moves, `link` writes the link again. A link that you made to another target stays as you wrote it.
142
155
  - `link` checks each link and image. The file must exist. A `#anchor` must exist in the page. A `#L` line must exist in the file.
143
156
 
157
+ In a group folder, a label names the project of a name. Write the label and a colon before the name. The label stays in the text. The examples are for `README.md` of the group folder.
158
+
159
+ | You write | `link` writes |
160
+ |---|---|
161
+ | `` `v1:draw_room` `$09BC` `` | `` [`v1:draw_room` `$09BC`](v1/src/room_draw.asm#L6) ``: one link to the line of the name in the source of `v1`. |
162
+ | `` `draw_room` `$09BC` `` | No link. In a shared page, each name needs a label. |
163
+
164
+ - In a page of a project, a name without a label is a name of that project. To link a name of a different project of the group, write its label, for example `` `v2:draw_room` `$0A10` ``.
165
+ - When the line of a name moves in the different project, `link` writes the link again. Thus link to the source of a different project only with a label. `link` does not move a `#L` link that you wrote.
166
+ - `` `v1:draw_room` `` and `` `v2:draw_room` `` are two names. Each can get one link in a section.
167
+
144
168
  `body` holds:
145
169
 
146
170
  - `result`: `PASS` when no page has a problem. `FAIL` when a page has a problem, or with `--check` when a link is not up to date.
147
171
  - `pages`: the count of the pages that it read.
148
172
  - `reference`: the folder of the reference, or `none`.
149
173
  - `linked`: `links`, the count of the links that it wrote, and `pages`, the pages that it changed. With `--check`, `notUpToDate` has the same fields for the links that are not up to date.
150
- - `problems`: `byKind`, `count`, `listed` and `rest`. Each item has `at` (the page and the line), `kind` and `message`.
174
+ - `problems`: `byKind`, `count`, `listed` and `rest`. Each item has `at` (the page and the line), `kind` and `message`. In a group folder, each item also has `project`: the label of the project of the page, or `shared`.
175
+ - `group`: only in a group folder. `folder` is the group folder, relative to the folder of the pages. `projects` holds the labels.
151
176
 
152
177
  `hint` and `nextAction`:
153
178
 
@@ -164,10 +189,16 @@ Do this for each `kind` of problem:
164
189
  | `repeated-link` | The name has a link in the section already. Remove the address from this mention. |
165
190
  | `link-in-table` | A name with its address is in a table row. Remove the address in the table. Link the name in the text above the table. |
166
191
  | `missing-file`, `missing-anchor`, `missing-line` | The link goes to nothing. Correct the link. An image of an asset must exist in the project. |
167
- | `outside-project` | The link goes out of the project folder. Correct the link. |
168
- | `stale-reference` | The source or the reference is older than the project knowledge. Do steps 2 and 3 of the workflow again. |
192
+ | `outside-project` | The link goes out of the project folder, and the project is not in a group folder. Correct the link. |
193
+ | `outside-group` | The link goes out of the group folder. Correct the link. |
194
+ | `unknown-label` | No project of the group folder has the label. `message` gives the labels. Correct the label. |
195
+ | `unlabelled-name` | A shared page gives a name and its address without a label. Write the label of the project before the name. |
196
+ | `stale-reference` | The source or the reference is older than the project knowledge. `message` names the project. Do steps 2 and 3 of the workflow again for that project. |
197
+
198
+ Errors:
169
199
 
170
- Errors: `not-found` names a page or a folder that is not in the project folder. `invalid-input` names a file that is not a `.md` file, or a folder that goes out of the project folder through a symbolic link. Correct the paths.
200
+ - `not-found` names a page or a folder that is not in the project folder or the group folder. `invalid-input` names a file that is not a `.md` file, or a folder that goes out through a symbolic link. Correct the paths.
201
+ - `not-found` that starts with `In the project <label>`: that project has no source map in `--source`. Generate the source of that project. Then run `link` again.
171
202
 
172
203
  ---
173
204
 
@@ -185,7 +216,12 @@ Errors: `not-found` names a page or a folder that is not in the project folder.
185
216
  6. Write each page. Read the code and the knowledge for each fact. When a fact needs a run, run the program in a test run or in the emulator. Explain each part before you name the code. Link only the main parts. Mark each fact with its evidence. Several subagents can write the pages at the same time, one page each. Give each subagent `<skill>/references/page-types.md` and `<skill>/references/style.md`.
186
217
  7. Record each new fact in the project knowledge first: a name, a comment, a region or a module. Then the source and the reference show it too. A fact that is only in a page is lost at the next change of the knowledge.
187
218
  8. Run `link`. Correct each problem. Then run `link` with `--check`. Make sure that `result` is `PASS`.
188
- 9. When the project folder is in a workspace with other projects, find `README.md` at the root of the workspace. This page lists each program of the workspace. Add one row for the program, with a link to `<project>/README.md` and one sentence. If the page does not exist, make it. Use the workspace index in `<skill>/references/page-types.md`. `link` does not read this page, because the page is not in the project folder.
219
+ 9. When the project folder is in a workspace with other projects, find `README.md` at the root of the workspace. This page lists each program of the workspace. Add one row for the program, with a link to `<project>/README.md` and one sentence. If the page does not exist, make it. Use the workspace index in `<skill>/references/page-types.md`. When the workspace folder is a group folder, run `link README.md --source src` in it to check the links of this page. Else `link` does not read this page.
220
+ 9b. When the program has two or more versions in a group folder, write the shared pages in the group folder. Use the group entry page in `<skill>/references/page-types.md`.
221
+ - Write the development, the differences between the versions, the releases and the disk layout one time, in the shared pages.
222
+ - The pages of each project tell only how its version works.
223
+ - In a shared page, write the label of the project before each name.
224
+ - Run `link` in the group folder for the shared pages and the pages of each project.
189
225
  10. After each change to the project knowledge, do steps 2, 3 and 8 again. Then the links go to the new lines.
190
226
 
191
227
  Do not keep the pages, or the facts that are only in the pages, in the project knowledge.
@@ -236,5 +272,5 @@ To get the subjects and the flags of one command, run `<command> --help`. Then `
236
272
 
237
273
  ## Reference
238
274
 
239
- - `<skill>/references/page-types.md`: the page types, with the parts of each type and a template. The types are the entry page, the workspace index, the subsystem page and the entity sections. Other types are the data-format page, the development page and the copy protection page. It also has the conventions block.
275
+ - `<skill>/references/page-types.md`: the page types, with the parts of each type and a template. The types are the entry page, the workspace index, the group entry page, the subsystem page and the entity sections. Other types are the data-format page, the development page and the copy protection page. It also has the conventions block.
240
276
  - `<skill>/references/style.md`: the rules for the text of the pages. They tell how to explain, and how to write the names and the links. They also give the evidence marks, the diagrams and the images.
@@ -97,6 +97,49 @@ Reverse-engineered C64 games. Each game has its own folder with the original dis
97
97
  | [Bruce Lee](bruce_lee/README.md) | Datasoft 1984. How the program works, from the cold start to the last room. |
98
98
  ```
99
99
 
100
+ ## 2b. The group entry page
101
+
102
+ A program with two or more versions in a group folder has one `README.md` in the group folder. It tells the parts of the program that the versions share. Each version has its own entry page in its project folder. The group entry page has these parts, in this order:
103
+
104
+ 1. **One paragraph.** What the program is, who made it and when, and which versions the documentation is for. Under it, one line defines the evidence marks.
105
+ 2. **The versions.** A table with one row for each version: the link to its entry page, the releases of the version, and its entry address. Under the table, tell how the versions are different and why the versions need a project each.
106
+ 3. **The development**, **The copy protection** and **Findings**, as in the entry page of section 1, for the facts that the versions share. Write the label of the version before each name, for example `` `v1:speech_irq` `$29C8` ``.
107
+ 4. **The pages.** A table of the shared pages in `docs/`, for example the development, the changes between the versions, the releases and the disk layout.
108
+ 5. **Still open.**
109
+
110
+ Each fact goes in one place. A fact of all versions goes in the group entry page or a shared page. A fact of one version goes in the pages of that version.
111
+
112
+ ```markdown
113
+ # <Program>
114
+
115
+ <What the program is. The authors and the year. The versions that this documentation is for.>
116
+
117
+ **Evidence.** **Observed** marks a fact that a run showed. **Code** marks a fact from the code only. **Conclusion** marks an interpretation.
118
+
119
+ ## The versions
120
+
121
+ | Version | Releases | Entry |
122
+ |---|---|---|
123
+ | [v1](v1/README.md) | <release> | `$1158` |
124
+ | [v2](v2/README.md) | <base release>, <release> | `$115A` |
125
+
126
+ <How the versions are different: the moved code and data, with the labelled names.> The details are on [docs/versions.md](docs/versions.md).
127
+
128
+ ## The development
129
+
130
+ ...
131
+
132
+ ## The pages
133
+
134
+ | Page | Content |
135
+ |---|---|
136
+ | [docs/development.md](docs/development.md) | **The development.** <one sentence> |
137
+
138
+ ## Still open
139
+
140
+ - <question> — <the run that can answer it>
141
+ ```
142
+
100
143
  ## 3. The subsystem page
101
144
 
102
145
  One page for each subsystem, for example the main loop, the interrupt chain, the room generation or the sound player. It has these parts:
@@ -6,7 +6,7 @@
6
6
  // every link and image of the pages.
7
7
 
8
8
  import { existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
9
- import { join, posix } from "node:path";
9
+ import { basename, join, posix } from "node:path";
10
10
 
11
11
  import { Refusal } from "#src/errors.ts";
12
12
  import { WireFailure } from "#src/host-client/tools.ts";
@@ -15,9 +15,9 @@ import { conflicts } from "#src/knowledge/conflicts.ts";
15
15
  import { openForRead } from "#src/knowledge/database.ts";
16
16
  import { programImage, type ProgramImage } from "#src/knowledge/program.ts";
17
17
  import { currentRevision, listComments, listModules, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
18
- import { resolveProjectFile, resolveProjectPath } from "#src/project.ts";
18
+ import { groupAt, groupOf, projectRoot, resolveProjectFile, resolveProjectPath, type ProjectGroup } from "#src/project.ts";
19
19
  import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
20
- import { checkLinks, linkPage, type Files, type Problem } from "./lib/links.ts";
20
+ import { checkLinks, linkPage, type Files, type LinkContext, type Names, type Problem } from "./lib/links.ts";
21
21
  import { buildReference, GENERATED_MARK } from "./lib/reference.ts";
22
22
  import { readSourceMap } from "./lib/source-map.ts";
23
23
 
@@ -108,162 +108,257 @@ function generate(call: Call): Reply {
108
108
  /** A name outside the image covers the addresses up to the next name, at most this many. */
109
109
  const MAX_BODY = 256;
110
110
 
111
- const isDirectory = (path: string) => {
112
- const real = resolveProjectPath(path);
111
+ const isDirectory = (path: string, root = projectRoot()) => {
112
+ const real = resolveProjectPath(path, root);
113
113
  return existsSync(real) && statSync(real).isDirectory();
114
114
  };
115
115
 
116
- function markdownFiles(directory: string): string[] {
117
- if (!isDirectory(directory)) throw new WireFailure("not-found", `There is no directory ${directory} in the project folder.`);
116
+ /**
117
+ * The folder of a link run. Without a group it is the project. With a group
118
+ * it is the group folder: the paths of the run are relative to it, and a page
119
+ * can link into each project of the group.
120
+ */
121
+ interface Scope {
122
+ /** The absolute folder that the paths of the run are relative to. */
123
+ root: string;
124
+ group: ProjectGroup | undefined;
125
+ /** The folder of the given pages, relative to root: the project of the run, or "" for root itself. */
126
+ base: string;
127
+ /** True when the run is in the group folder and no --project names it: nextAction gives it. */
128
+ unnamed: boolean;
129
+ }
130
+
131
+ /** A project of the run, and its folder relative to the root of the run. */
132
+ interface Member {
133
+ /** The folder name in a group; undefined without a group. */
134
+ label: string | undefined;
135
+ root: string;
136
+ prefix: string;
137
+ }
138
+
139
+ function linkScope(): Scope {
118
140
  let root: string;
119
141
  try {
120
- root = resolveProjectFile(directory);
121
- } catch {
122
- throw new WireFailure("invalid-input", `${directory} leads out of the project folder through a symbolic link.`);
142
+ root = projectRoot();
143
+ } catch (error) {
144
+ // The project lookup refuses a folder with projects in it: in a group folder, link works on the group.
145
+ const group = groupAt(process.cwd());
146
+ if (group === undefined) throw error;
147
+ return { root: group.root, group, base: "", unnamed: true };
123
148
  }
124
- const found: string[] = [];
125
- const walk = (relative: string) => {
126
- for (const entry of readdirSync(join(root, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
127
- const path = posix.join(relative, entry.name);
128
- if (entry.isDirectory()) walk(path);
129
- else if (entry.name.endsWith(".md")) found.push(posix.join(directory, path));
130
- }
131
- };
132
- walk("");
133
- return found;
149
+ const at = groupAt(root);
150
+ if (at !== undefined) return { root, group: at, base: "", unnamed: false };
151
+ const group = groupOf(root);
152
+ if (group === undefined) return { root, group, base: "", unnamed: false };
153
+ return { root: group.root, group, base: basename(root), unnamed: false };
134
154
  }
135
155
 
136
- /** The text of each file that the run read: a page, a source file or a reference page is read once. */
137
- const texts = new Map<string, string | undefined>();
156
+ /** True when `path` is `directory` or below it; every path is below "". */
157
+ const within = (path: string, directory: string | undefined) => directory !== undefined && (directory === "" || path === directory || path.startsWith(`${directory}/`));
158
+
159
+ function link(call: Call): Reply {
160
+ const check = call.flag("check");
161
+ const scope = linkScope();
162
+ const { root, group } = scope;
163
+ const folder = group !== undefined && scope.base === "" ? "the group folder" : "the project folder";
164
+ const toRun = (path: string) => posix.normalize(posix.join(scope.base, path));
165
+ const shown = (path: string) => (scope.base === "" ? path : posix.relative(scope.base, path));
166
+ const members: Member[] = group === undefined ? [{ label: undefined, root, prefix: "" }] : [...group.projects].map(([label, project]) => ({ label, root: project, prefix: label }));
167
+ const memberOf = (path: string) => members.find((member) => within(path, member.prefix));
138
168
 
139
- const files: Files = {
140
- inside: (path) => {
169
+ /** The text of each file that the run read: a page, a source file or a reference page is read once. */
170
+ const texts = new Map<string, string | undefined>();
171
+ const files: Files = {
172
+ inside: (path) => {
173
+ try {
174
+ resolveProjectPath(path, root);
175
+ return true;
176
+ } catch {
177
+ return false;
178
+ }
179
+ },
180
+ exists: (path) => {
181
+ try {
182
+ resolveProjectFile(path, root);
183
+ return true;
184
+ } catch {
185
+ return false;
186
+ }
187
+ },
188
+ text: (path) => {
189
+ if (texts.has(path)) return texts.get(path);
190
+ let text: string | undefined;
191
+ try {
192
+ const real = resolveProjectFile(path, root);
193
+ text = statSync(real).isFile() ? readFileSync(real, "utf8") : undefined;
194
+ } catch {
195
+ text = undefined;
196
+ }
197
+ texts.set(path, text);
198
+ return text;
199
+ },
200
+ group: group !== undefined,
201
+ shown,
202
+ };
203
+ const markdownFiles = (directory: string): string[] => {
204
+ if (!isDirectory(directory, root)) throw new WireFailure("not-found", `There is no directory ${shown(directory)} in ${folder}.`);
205
+ let real: string;
141
206
  try {
142
- resolveProjectPath(path);
143
- return true;
207
+ real = resolveProjectFile(directory, root);
144
208
  } catch {
145
- return false;
209
+ throw new WireFailure("invalid-input", `${shown(directory)} leads out of ${folder} through a symbolic link.`);
146
210
  }
147
- },
148
- exists: (path) => {
211
+ const found: string[] = [];
212
+ const walk = (relative: string) => {
213
+ for (const entry of readdirSync(join(real, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
214
+ const path = posix.join(relative, entry.name);
215
+ if (entry.isDirectory()) walk(path);
216
+ else if (entry.name.endsWith(".md")) found.push(posix.join(directory, path));
217
+ }
218
+ };
219
+ walk("");
220
+ return found;
221
+ };
222
+ /** A .md entry of a directory that is a symbolic link to no file, or to a file outside the folder of the run. */
223
+ const unreadable = (page: string): Problem => ({ page, line: 1, kind: "missing-file", message: `${shown(page)} is a symbolic link to no file or to a file outside ${folder}.` });
224
+
225
+ const given = [...new Set(call.subjects.map((path) => posix.normalize(path)))];
226
+ const pagesGiven = given.map(toRun);
227
+ given.forEach((path, index) => {
228
+ if (!within(pagesGiven[index]!, scope.base) || !files.inside(pagesGiven[index]!)) throw new UsageError(`<page> must be a path relative to ${folder} that stays inside it, not ${path}`);
229
+ });
230
+ given.forEach((path, index) => {
231
+ const page = pagesGiven[index]!;
232
+ if (!page.endsWith(".md") && files.exists(page) && !isDirectory(page, root)) throw new UsageError(`<pages> takes .md files and directories, not ${path}`);
233
+ });
234
+ const directories = pagesGiven.filter((path) => !path.endsWith(".md") || isDirectory(path, root));
235
+ // --source and --reference are relative to each project folder: the projects of a group have the same layout.
236
+ const inProjectFolder = (name: string, value: string) => {
237
+ const path = posix.normalize(value.replaceAll("\\", "/"));
238
+ if (posix.isAbsolute(path) || /^[A-Za-z]:/.test(path) || path === ".." || path.startsWith("../")) throw new UsageError(`--${name} must be a path relative to the project folder that stays inside it, not ${value}`);
239
+ return path;
240
+ };
241
+ const source = inProjectFolder("source", call.string("source")!);
242
+ const givenReference = call.string("reference");
243
+ const checkedReference = givenReference === undefined ? undefined : inProjectFolder("reference", givenReference);
244
+ // The default reference: the reference/ folder in a given folder, or beside a given page, of a project.
245
+ const besides = pagesGiven.map((path) => (directories.includes(path) ? path : posix.dirname(path)));
246
+ const foundReference = besides.map((path) => posix.join(path, "reference")).find((path) => memberOf(path) !== undefined && isDirectory(path, root));
247
+ const reference = checkedReference !== undefined ? checkedReference : foundReference === undefined ? undefined : foundReference.slice(memberOf(foundReference)!.prefix.length).replace(/^\//, "");
248
+ const referenceOf = (member: Member) => (reference === undefined ? undefined : posix.join(member.prefix, reference));
249
+ const problems: Problem[] = [];
250
+
251
+ /** The names of a project, read the first time a page needs them. A project with given pages is read before the pages. */
252
+ const loaded = new Map<Member, Names>();
253
+ const load = (member: Member, required: boolean): Names => {
254
+ const done = loaded.get(member);
255
+ if (done !== undefined) return done;
256
+ const of = member.label === undefined ? "" : ` of the project ${member.label}`;
257
+ const inProject = (path: string) => posix.join(member.prefix, path);
258
+ let map;
149
259
  try {
150
- resolveProjectFile(path);
151
- return true;
152
- } catch {
153
- return false;
260
+ map = readSourceMap(source, member.root);
261
+ } catch (error) {
262
+ if (member.label === undefined || !(error instanceof WireFailure)) throw error;
263
+ throw new WireFailure(error.code, `In the project ${member.label}: ${error.message}`);
154
264
  }
155
- },
156
- text: (path) => {
157
- if (texts.has(path)) return texts.get(path);
158
- let text: string | undefined;
265
+ const db = openForRead(member.root);
266
+ let symbols;
267
+ let revision;
159
268
  try {
160
- const real = resolveProjectFile(path);
161
- text = statSync(real).isFile() ? readFileSync(real, "utf8") : undefined;
162
- } catch {
163
- text = undefined;
269
+ revision = currentRevision(db);
270
+ symbols = listSymbols(db, undefined, undefined, undefined, map.space);
271
+ } finally {
272
+ db?.close();
164
273
  }
165
- texts.set(path, text);
166
- return text;
167
- },
168
- };
169
-
170
- /** A .md entry of a directory that is a symbolic link to no file, or to a file outside the project. */
171
- const unreadable = (page: string): Problem => ({ page, line: 1, kind: "missing-file", message: `${page} is a symbolic link to no file or to a file outside the project folder.` });
274
+ if (map.revision !== revision) {
275
+ problems.push({ page: inProject(map.pathOf("source-map.json")), line: 1, kind: "stale-reference", message: `The source${of} is from knowledge revision ${map.revision}, and the knowledge is at ${revision}. Generate the source and the reference again, then run docs.ts link.` });
276
+ }
277
+ const addresses = new Map<string, number>();
278
+ for (const label of map.labels) addresses.set(label.name, label.address);
279
+ for (const symbol of symbols) addresses.set(symbol.name, symbol.address);
280
+ // A routine runs to the next routine; any other name to the next name of the knowledge, in its file, and outside the image at most MAX_BODY bytes.
281
+ const routines = symbols.filter((symbol) => symbol.kind === "routine").map((symbol) => symbol.address).sort((a, b) => a - b);
282
+ const named = [...new Set(symbols.map((symbol) => symbol.address))].sort((a, b) => a - b);
283
+ const kinds = new Map(symbols.map((symbol) => [symbol.name, symbol.kind]));
284
+ const bodyEnds = new Map<string, number | undefined>();
285
+ const bodyEnd = (name: string) => {
286
+ if (bodyEnds.has(name)) return bodyEnds.get(name);
287
+ const address = addresses.get(name);
288
+ let end: number | undefined;
289
+ if (address !== undefined) {
290
+ const next = ((kinds.get(name) === "routine" ? routines : named).find((other) => other > address) ?? 0x10000) - 1;
291
+ const file = map.lineOf(address)?.file;
292
+ if (file === undefined) end = Math.min(next, address + MAX_BODY - 1);
293
+ else {
294
+ end = address;
295
+ while (end < next && map.lineOf(end + 1)?.file === file) end++;
296
+ }
297
+ }
298
+ bodyEnds.set(name, end);
299
+ return end;
300
+ };
301
+ const nameAt = new Map(symbols.map((symbol) => [symbol.address, symbol.name]));
302
+ /** The routine, else the name, whose body holds an address. */
303
+ const placeOf = (address: number) => {
304
+ for (const list of [routines, named]) {
305
+ let start: number | undefined;
306
+ for (const other of list) if (other <= address) start = other;
307
+ const name = start === undefined ? undefined : nameAt.get(start);
308
+ if (name !== undefined && (bodyEnd(name) ?? start!) >= address) return name;
309
+ }
310
+ return undefined;
311
+ };
172
312
 
173
- function link(call: Call): Reply {
174
- const check = call.flag("check");
175
- const given = [...new Set(call.subjects.map((path) => posix.normalize(path)))];
176
- for (const path of given) if (!files.inside(path)) throw new UsageError(`<page> must be a path relative to the project folder that stays inside it, not ${path}`);
177
- for (const path of given) {
178
- if (!path.endsWith(".md") && files.exists(path) && !isDirectory(path)) throw new UsageError(`<pages> takes .md files and directories, not ${path}`);
179
- }
180
- const directories = given.filter((path) => !path.endsWith(".md") || isDirectory(path));
181
- const map = readSourceMap(call.string("source")!);
182
- const givenReference = call.string("reference");
183
- // The default reference: the reference/ folder in a given folder, or beside a given page.
184
- const besides = given.map((path) => (directories.includes(path) ? path : posix.dirname(path)));
185
- const reference = givenReference === undefined ? besides.map((path) => posix.join(path, "reference")).find((path) => isDirectory(path)) : posix.normalize(givenReference);
186
- const problems: Problem[] = [];
187
- const db = openForRead();
188
- let symbols;
189
- let revision;
190
- try {
191
- revision = currentRevision(db);
192
- symbols = listSymbols(db, undefined, undefined, undefined, map.space);
193
- } finally {
194
- db?.close();
195
- }
196
- if (map.revision !== revision) {
197
- problems.push({ page: map.pathOf("source-map.json"), line: 1, kind: "stale-reference", message: `The source is from knowledge revision ${map.revision}, and the knowledge is at ${revision}. Generate the source and the reference again, then run docs.ts link.` });
198
- }
199
- const addresses = new Map<string, number>();
200
- for (const label of map.labels) addresses.set(label.name, label.address);
201
- for (const symbol of symbols) addresses.set(symbol.name, symbol.address);
202
- // A routine runs to the next routine; any other name to the next name of the knowledge, in its file, and outside the image at most MAX_BODY bytes.
203
- const routines = symbols.filter((symbol) => symbol.kind === "routine").map((symbol) => symbol.address).sort((a, b) => a - b);
204
- const named = [...new Set(symbols.map((symbol) => symbol.address))].sort((a, b) => a - b);
205
- const kinds = new Map(symbols.map((symbol) => [symbol.name, symbol.kind]));
206
- const bodyEnds = new Map<string, number | undefined>();
207
- const bodyEnd = (name: string) => {
208
- if (bodyEnds.has(name)) return bodyEnds.get(name);
209
- const address = addresses.get(name);
210
- let end: number | undefined;
211
- if (address !== undefined) {
212
- const next = ((kinds.get(name) === "routine" ? routines : named).find((other) => other > address) ?? 0x10000) - 1;
213
- const file = map.lineOf(address)?.file;
214
- if (file === undefined) end = Math.min(next, address + MAX_BODY - 1);
215
- else {
216
- end = address;
217
- while (end < next && map.lineOf(end + 1)?.file === file) end++;
313
+ // The pages of the reference: each must be from the revision of the source.
314
+ const referenceDirectory = referenceOf(member);
315
+ const referencePages = referenceDirectory === undefined || (!required && !isDirectory(referenceDirectory, root)) ? [] : markdownFiles(referenceDirectory);
316
+ for (const page of referencePages) {
317
+ const text = files.text(page);
318
+ if (text === undefined) {
319
+ problems.push(unreadable(page));
320
+ continue;
321
+ }
322
+ const stamp = /^<!-- Generated by c64-docs from knowledge revision (\S+) /.exec(text);
323
+ if (text.startsWith(GENERATED_MARK) && stamp !== null && stamp[1] !== map.revision) {
324
+ problems.push({ page, line: 1, kind: "stale-reference", message: `${shown(page)} is from knowledge revision ${stamp[1]}, and the source${of} from ${map.revision}. Run docs.ts generate again.` });
218
325
  }
219
326
  }
220
- bodyEnds.set(name, end);
221
- return end;
222
- };
223
- const nameAt = new Map(symbols.map((symbol) => [symbol.address, symbol.name]));
224
- /** The routine, else the name, whose body holds an address. */
225
- const placeOf = (address: number) => {
226
- for (const list of [routines, named]) {
227
- let start: number | undefined;
228
- for (const other of list) if (other <= address) start = other;
229
- const name = start === undefined ? undefined : nameAt.get(start);
230
- if (name !== undefined && (bodyEnd(name) ?? start!) >= address) return name;
231
- }
232
- return undefined;
327
+ const names: Names = {
328
+ addressOf: (name) => addresses.get(name),
329
+ codeOf: (name) => {
330
+ const label = map.labelOf(name);
331
+ return label === undefined ? undefined : `${inProject(map.pathOf(label.file))}#L${label.line}`;
332
+ },
333
+ bodyEnd,
334
+ placeOf,
335
+ lineOf: (address) => {
336
+ const line = map.lineOf(address);
337
+ return line === undefined ? undefined : `${inProject(map.pathOf(line.file))}#L${line.line}`;
338
+ },
339
+ };
340
+ loaded.set(member, names);
341
+ return names;
233
342
  };
343
+ for (const member of members) if (pagesGiven.some((page) => memberOf(page) === member)) load(member, true);
234
344
 
235
- // The pages of the reference: each must be from the revision of the source.
236
- const referencePages = reference === undefined ? [] : markdownFiles(reference);
237
- for (const page of referencePages) {
238
- const text = files.text(page);
239
- if (text === undefined) {
240
- problems.push(unreadable(page));
241
- continue;
345
+ const labels = members.map((member) => member.label!);
346
+ const namesFor = (page: string) => (label: string | undefined): ReturnType<LinkContext["names"]> => {
347
+ if (group === undefined) return label === undefined ? load(members[0]!, false) : undefined;
348
+ if (label === undefined) {
349
+ const own = memberOf(page);
350
+ if (own !== undefined) return load(own, false);
351
+ return { kind: "unlabelled-name", message: `A page of the group folder must name the project of each name. Write the folder of the project before the name, for example \`${labels[0]}:name\`.` };
242
352
  }
243
- const stamp = /^<!-- Generated by c64-docs from knowledge revision (\S+) /.exec(text);
244
- if (text.startsWith(GENERATED_MARK) && stamp !== null && stamp[1] !== map.revision) {
245
- problems.push({ page, line: 1, kind: "stale-reference", message: `${page} is from knowledge revision ${stamp[1]}, and the source from ${map.revision}. Run docs.ts generate again.` });
246
- }
247
- }
248
- const inside = (path: string, directory: string | undefined) => directory !== undefined && (path === directory || path.startsWith(`${directory}/`));
249
- const context = {
250
- addressOf: (name: string) => addresses.get(name),
251
- codeOf: (name: string) => {
252
- const label = map.labelOf(name);
253
- return label === undefined ? undefined : `${map.pathOf(label.file)}#L${label.line}`;
254
- },
255
- bodyEnd,
256
- placeOf,
257
- lineOf: (address: number) => {
258
- const line = map.lineOf(address);
259
- return line === undefined ? undefined : `${map.pathOf(line.file)}#L${line.line}`;
260
- },
261
- managed: (path: string) => inside(path, posix.normalize(map.directory)) || inside(path, reference),
353
+ const member = members.find((each) => each.label === label);
354
+ if (member === undefined) return { kind: "unknown-label", message: `${label} is no project of the group folder. The projects are ${labels.join(", ")}. Correct the label.` };
355
+ return load(member, false);
262
356
  };
357
+ const managed = (path: string) => members.some((member) => within(path, posix.join(member.prefix, source)) || within(path, referenceOf(member)));
263
358
 
264
- const pages = [...new Set(given.flatMap((path) => {
359
+ const pages = [...new Set(pagesGiven.flatMap((path) => {
265
360
  if (directories.includes(path)) return markdownFiles(path);
266
- if (files.text(path) === undefined) throw new WireFailure("not-found", `There is no file ${path} in the project folder.`);
361
+ if (files.text(path) === undefined) throw new WireFailure("not-found", `There is no file ${shown(path)} in ${folder}.`);
267
362
  return [path];
268
363
  }))];
269
364
  const changedPages: string[] = [];
@@ -276,25 +371,32 @@ function link(call: Call): Reply {
276
371
  }
277
372
  // A generated page is right by its making: it is only checked.
278
373
  const generated = text.startsWith(GENERATED_MARK);
279
- const linked = generated ? { text, changed: 0, problems: [] } : linkPage(text, { page, ...context });
374
+ const linked = generated ? { text, changed: 0, problems: [] } : linkPage(text, { page, names: namesFor(page), managed });
280
375
  problems.push(...linked.problems, ...checkLinks(page, linked.text, files));
281
376
  if (linked.changed === 0) continue;
282
377
  links += linked.changed;
283
- changedPages.push(page);
378
+ changedPages.push(shown(page));
284
379
  if (check) continue;
285
- writeProjectFile(page, Buffer.from(linked.text, "utf8"));
380
+ writeProjectFile(page, Buffer.from(linked.text, "utf8"), { root });
286
381
  texts.set(page, linked.text);
287
382
  }
288
383
  const byKind: Record<string, number> = {};
289
384
  for (const problem of problems) byKind[problem.kind] = (byKind[problem.kind] ?? 0) + 1;
290
- const shownProblems = listed(problems, call.count("max-listed")!, (problem) => ({ at: `${problem.page}:${problem.line}`, kind: problem.kind, message: problem.message }));
385
+ const shownProblems = listed(problems, call.count("max-listed")!, (problem) => ({
386
+ at: `${shown(problem.page)}:${problem.line}`,
387
+ ...(group === undefined ? {} : { project: memberOf(problem.page)?.label ?? "shared" }),
388
+ kind: problem.kind,
389
+ message: problem.message,
390
+ }));
291
391
  const output: Record<string, unknown> = {
392
+ ...(group === undefined ? {} : { group: { folder: scope.base === "" ? "." : "..", projects: labels } }),
292
393
  pages: pages.length,
293
394
  reference: reference ?? "none",
294
395
  ...(check ? { notUpToDate: { links, pages: changedPages } } : { linked: { links, pages: changedPages } }),
295
396
  problems: { byKind, ...shownProblems },
296
397
  };
297
- const again = (withCheck: boolean) => call.next("link", ...call.subjects, "--source", call.string("source")!, ...(givenReference === undefined ? [] : ["--reference", givenReference]), ...(withCheck ? ["--check"] : []));
398
+ const again = (withCheck: boolean) =>
399
+ call.next("link", ...call.subjects, "--source", call.string("source")!, ...(givenReference === undefined ? [] : ["--reference", givenReference]), ...(withCheck ? ["--check"] : []), ...(scope.unnamed ? ["--project", root] : []));
298
400
  const hints: string[] = [];
299
401
  let nextAction: string | undefined;
300
402
  if (reference === undefined) hints.push("No reference/ folder is in or beside the given pages, so the links to the reference are not checked. Give --reference <dir>, or run generate first.");
@@ -332,14 +434,15 @@ await runScript({
332
434
  {
333
435
  name: "link",
334
436
  summary: "Links each name with its address in the pages to its line in the source, and checks every link and image. result is FAIL when a page has a problem, or with --check when a link is not up to date.",
335
- subjects: [{ name: "<page>", help: ".md files and folders of the documentation, relative to the project folder, for example README.md docs. link reads each file and every .md file below each folder", list: true }],
437
+ subjects: [{ name: "<page>", help: ".md files and folders of the documentation, relative to the project folder or the group folder, for example README.md docs. link reads each file and every .md file below each folder", list: true }],
336
438
  options: {
337
- source: { ...SOURCE, required: true },
338
- reference: { kind: "path", value: "<dir>", help: "the folder of the reference pages of generate. The default is the first reference/ folder in a given folder or beside a given page" },
439
+ // Text, not a path of the run: in a group, each project has the source and the reference at this path.
440
+ source: { kind: "text", value: "<dir>", help: `${SOURCE.help}. In a group, the same folder in each project`, required: true },
441
+ reference: { kind: "text", value: "<dir>", help: "the folder of the reference pages of generate, relative to the project folder; in a group, the same folder in each project. The default is the first reference/ folder in a given folder or beside a given page" },
339
442
  check: { kind: "flag", help: "write nothing. FAIL when a link is not up to date or a page has a problem" },
340
443
  "max-listed": OPTIONS["max-listed"],
341
444
  },
342
- notes: "A name in backticks with its address in backticks after it, for example `draw_room` `$09BC`, becomes one link to the line of the name in the source. A name without an address gets no link. A name gets one link in each section, and a table gets no links.",
445
+ notes: "A name in backticks with its address in backticks after it, for example `draw_room` `$09BC`, becomes one link to the line of the name in the source. A name without an address gets no link. A name gets one link in each section, and a table gets no links. In a group folder, write the folder of the project before the name, for example `v2:draw_room` `$09BC`.",
343
446
  run: link,
344
447
  },
345
448
  ],
@@ -6,30 +6,41 @@
6
6
  // address only where a reader needs the code. A link that points into the
7
7
  // source or the reference is managed: docs.ts link writes it again when a line
8
8
  // moves. Other links stay as the person wrote them; docs.ts link only checks
9
- // that their targets exist.
9
+ // that their targets exist. In a group folder, a label before the name
10
+ // ("v2:draw_room $09BC") names the project of the group that has the name.
10
11
 
11
12
  import { posix } from "node:path";
12
13
 
13
14
  import { anchorsOf, linksOf, proseLines } from "./markdown.ts";
14
15
 
15
- export interface LinkContext {
16
- /** The page, relative to the project folder. */
17
- page: string;
16
+ /** The names of one project: of its knowledge and of its source. */
17
+ export interface Names {
18
18
  /** The address of a name of the knowledge or of the source; undefined for a word that is no name. */
19
19
  addressOf: (name: string) => number | undefined;
20
- /** The project path and line of the label of a name, as path#Lnn. */
20
+ /** The path and line of the label of a name, as path#Lnn. */
21
21
  codeOf: (name: string) => string | undefined;
22
22
  /** The last address of the routine or data of a name: an address up to it is a place inside the name. */
23
23
  bodyEnd: (name: string) => number | undefined;
24
- /** The project path and line that writes an address, as path#Lnn. */
24
+ /** The path and line that writes an address, as path#Lnn. */
25
25
  lineOf: (address: number) => string | undefined;
26
26
  /** The name of the routine or data that holds an address, for a message. */
27
27
  placeOf: (address: number) => string | undefined;
28
- /** True for a project path that docs.ts link manages: a file of the source or a page of the reference. */
28
+ }
29
+
30
+ export interface LinkContext {
31
+ /** The page, relative to the folder of the run: the project, or the group folder. */
32
+ page: string;
33
+ /**
34
+ * The names of the project of a label, or for no label of the project of the
35
+ * page. A problem when the label or the page names no project. Undefined
36
+ * for a label without a group: the mention is no mention.
37
+ */
38
+ names: (label: string | undefined) => Names | { kind: ProblemKind; message: string } | undefined;
39
+ /** True for a path that docs.ts link manages: a file of the source or a page of the reference. */
29
40
  managed: (path: string) => boolean;
30
41
  }
31
42
 
32
- export type ProblemKind = "unknown-name" | "wrong-address" | "repeated-link" | "link-in-table" | "missing-file" | "missing-anchor" | "missing-line" | "outside-project" | "stale-reference";
43
+ export type ProblemKind = "unknown-name" | "wrong-address" | "repeated-link" | "link-in-table" | "missing-file" | "missing-anchor" | "missing-line" | "outside-project" | "outside-group" | "unknown-label" | "unlabelled-name" | "stale-reference";
33
44
 
34
45
  export interface Problem {
35
46
  page: string;
@@ -41,13 +52,16 @@ export interface Problem {
41
52
 
42
53
  const NAME = String.raw`([A-Za-z_][A-Za-z0-9_]*)(\+(?:\$[0-9A-Fa-f]{1,4}|[0-9]+))?`;
43
54
  const ADDRESS = String.raw`\$([0-9A-Fa-f]{2,4})(?:-\$[0-9A-Fa-f]{2,4})?`;
55
+ /** The label of a project: the name of its folder. */
56
+ const LABEL = String.raw`([A-Za-z0-9_][A-Za-z0-9_.-]*):`;
44
57
  const TICK = "`";
45
58
  /**
46
59
  * A name in backticks and an address in backticks after it, as text or as one
47
- * link. Groups: 1 the [ of the link, 2 the name, 3 its offset, 4 the space
48
- * between them, 5 the address text, 6 its start digits, 7 the target of the link.
60
+ * link. Groups: 1 the [ of the link, 2 the label, 3 the name, 4 its offset, 5
61
+ * the space between them, 6 the address text, 7 its start digits, 8 the target
62
+ * of the link.
49
63
  */
50
- const MENTION = new RegExp(String.raw`(\[)?${TICK}${NAME}${TICK}(\s+)${TICK}(${ADDRESS})${TICK}(?:\]\(([^)\s]*)\))?`, "g");
64
+ const MENTION = new RegExp(String.raw`(\[)?${TICK}(?:${LABEL})?${NAME}${TICK}(\s+)${TICK}(${ADDRESS})${TICK}(?:\]\(([^)\s]*)\))?`, "g");
51
65
  const HEADING = /^#{1,6}\s/;
52
66
  const TABLE_ROW = /^\s*\|/;
53
67
 
@@ -79,41 +93,48 @@ export function linkPage(text: string, context: LinkContext): { text: string; ch
79
93
  if (!line.prose) return line.text;
80
94
  if (HEADING.test(line.text)) linkedAt = new Map();
81
95
  const inTable = TABLE_ROW.test(line.text);
82
- return line.text.replace(MENTION, (whole: string, open: string | undefined, name: string, offset: string | undefined, space: string, addressText: string, digits: string, target: string | undefined) => {
96
+ return line.text.replace(MENTION, (whole: string, open: string | undefined, label: string | undefined, name: string, offset: string | undefined, space: string, addressText: string, digits: string, target: string | undefined) => {
83
97
  // "[`x` `$10`]" without a target, or "`x` `$10`](y)" in a link of the person: no link of ours, leave it.
84
98
  if ((open === undefined) !== (target === undefined)) return whole;
85
99
  // A link to another target than the source is the person's own link: it stays as it is.
86
100
  if (target !== undefined && !context.managed(targetPath(context.page, target) ?? "")) return whole;
87
- const address = context.addressOf(name);
88
101
  const report = (kind: ProblemKind, message: string) => problems.push({ page: context.page, line: index + 1, kind, message });
89
- const shown = `${TICK}${name}${offset ?? ""}${TICK}${space}${TICK}${addressText}${TICK}`;
102
+ const labelled = `${label === undefined ? "" : `${label}:`}${name}`;
103
+ const names = context.names(label);
104
+ if (names === undefined) return whole;
105
+ if ("kind" in names) {
106
+ report(names.kind, `\`${labelled}\` ${addressText}: ${names.message}`);
107
+ return whole;
108
+ }
109
+ const address = names.addressOf(name);
110
+ const shown = `${TICK}${labelled}${offset ?? ""}${TICK}${space}${TICK}${addressText}${TICK}`;
90
111
  if (address === undefined) {
91
- report("unknown-name", `\`${name}\` is no name of the knowledge or the source. Record the name in the project knowledge, or correct the page.`);
112
+ report("unknown-name", `\`${labelled}\` is no name of the knowledge or the source${label === undefined ? "" : ` of the project ${label}`}. Record the name in the project knowledge, or correct the page.`);
92
113
  return whole;
93
114
  }
94
115
  const delta = offset === undefined ? 0 : offset.startsWith("+$") ? Number.parseInt(offset.slice(2), 16) : Number.parseInt(offset.slice(1), 10);
95
116
  const given = Number.parseInt(digits, 16);
96
- const place = given !== address + delta && given > address && given <= (context.bodyEnd(name) ?? address);
117
+ const place = given !== address + delta && given > address && given <= (names.bodyEnd(name) ?? address);
97
118
  if (given !== address + delta && !place) {
98
119
  const expected = `$${(address + delta).toString(16).toUpperCase().padStart(4, "0")}`;
99
- const holder = context.placeOf(given);
100
- report("wrong-address", `\`${name}${offset ?? ""}\` is ${expected} in the knowledge, and the page gives ${addressText}${holder === undefined || holder === name ? "" : `, a place in \`${holder}\``}. Correct the name or the address.${digits.length <= 2 ? ` For a value, write \`${name}\` = \`${addressText}\`.` : ""}`);
120
+ const holder = names.placeOf(given);
121
+ report("wrong-address", `\`${labelled}${offset ?? ""}\` is ${expected} in the knowledge, and the page gives ${addressText}${holder === undefined || holder === name ? "" : `, a place in \`${holder}\``}. Correct the name or the address.${digits.length <= 2 ? ` For a value, write \`${name}\` = \`${addressText}\`.` : ""}`);
101
122
  // A mention with a problem gets no link: the text stays as the person wrote it until it is correct.
102
123
  return whole;
103
124
  }
104
125
  if (inTable) {
105
- report("link-in-table", `\`${name}${offset ?? ""}\` ${addressText} is a link in a table. Write \`${name}\` without the address in the table, and link it in the text above the table.`);
126
+ report("link-in-table", `\`${labelled}${offset ?? ""}\` ${addressText} is a link in a table. Write \`${labelled}\` without the address in the table, and link it in the text above the table.`);
106
127
  return whole;
107
128
  }
108
- const key = `${name}${offset ?? ""} ${given}`;
129
+ const key = `${labelled}${offset ?? ""} ${given}`;
109
130
  const first = linkedAt.get(key);
110
131
  if (first !== undefined) {
111
- report("repeated-link", `\`${name}${offset ?? ""}\` ${addressText} has a link at line ${first} of this section already. Write \`${name}\` without the address here.`);
132
+ report("repeated-link", `\`${labelled}${offset ?? ""}\` ${addressText} has a link at line ${first} of this section already. Write \`${labelled}\` without the address here.`);
112
133
  return whole;
113
134
  }
114
135
  linkedAt.set(key, index + 1);
115
136
  // The name links to its line; a place inside it or a byte after it links to the line of that address.
116
- const code = given === address ? context.codeOf(name) : (context.lineOf(given) ?? context.codeOf(name));
137
+ const code = given === address ? names.codeOf(name) : (names.lineOf(given) ?? names.codeOf(name));
117
138
  const result = code === undefined ? shown : `[${shown}](${relative(context.page, code)})`;
118
139
  if (result !== whole) changed++;
119
140
  return result;
@@ -125,9 +146,14 @@ export function linkPage(text: string, context: LinkContext): { text: string; ch
125
146
  /** The files that a check reads: their text, or undefined when the file does not exist. */
126
147
  export interface Files {
127
148
  exists: (path: string) => boolean;
128
- /** The text of a project file, or undefined when it is no file. */
149
+ /** The text of a file, or undefined when it is no file. */
129
150
  text: (path: string) => string | undefined;
151
+ /** True for a path in the folder of the run: the project, or the group folder. */
130
152
  inside: (path: string) => boolean;
153
+ /** True when the folder of the run is a group folder or a project in one: a link may go into the other projects. */
154
+ group: boolean;
155
+ /** A path as the messages give it: relative to the folder where the pages were given. */
156
+ shown: (path: string) => string;
131
157
  }
132
158
 
133
159
  /** Checks that each link and image of a page reaches a file, and its anchor or line. */
@@ -149,20 +175,21 @@ export function checkLinks(page: string, text: string, files: Files): Problem[]
149
175
  if (/^[a-z][a-z0-9+.-]*:/i.test(link.target)) continue;
150
176
  const path = link.target.startsWith("#") ? page : targetPath(page, link.target)!;
151
177
  if (!files.inside(path)) {
152
- report("outside-project", `${link.target} leaves the project folder.`);
178
+ if (files.group) report("outside-group", `${link.target} leaves the group folder.`);
179
+ else report("outside-project", `${link.target} leaves the project folder.`);
153
180
  continue;
154
181
  }
155
182
  if (!files.exists(path)) {
156
- report("missing-file", `${link.target}: there is no ${path}.`);
183
+ report("missing-file", `${link.target}: there is no ${files.shown(path)}.`);
157
184
  continue;
158
185
  }
159
186
  if (fragment === undefined || fragment === "") continue;
160
187
  const line = /^L(\d+)(?:-L?\d+)?$/.exec(fragment);
161
188
  if (path.endsWith(".md")) {
162
- if (!anchorsAt(path).has(fragment)) report("missing-anchor", `${link.target}: ${path} has no anchor ${fragment}.`);
189
+ if (!anchorsAt(path).has(fragment)) report("missing-anchor", `${link.target}: ${files.shown(path)} has no anchor ${fragment}.`);
163
190
  } else if (line !== null) {
164
191
  const count = lineCount(path);
165
- if (Number(line[1]) > count) report("missing-line", `${link.target}: ${path} has ${count} lines.`);
192
+ if (Number(line[1]) > count) report("missing-line", `${link.target}: ${files.shown(path)} has ${count} lines.`);
166
193
  }
167
194
  }
168
195
  return problems;
@@ -30,12 +30,12 @@ export interface SourceMap {
30
30
  pathOf: (file: string) => string;
31
31
  }
32
32
 
33
- /** Reads <directory>/source-map.json. A missing map is a refusal with the remedy. */
34
- export function readSourceMap(directory: string): SourceMap {
33
+ /** Reads <directory>/source-map.json of the project `root`. A missing map is a refusal with the remedy. */
34
+ export function readSourceMap(directory: string, root?: string): SourceMap {
35
35
  const path = posix.join(directory, SOURCE_MAP_FILE);
36
36
  let text: string;
37
37
  try {
38
- text = readProjectFile(path).bytes.toString("utf8");
38
+ text = readProjectFile(path, root === undefined ? {} : { root }).bytes.toString("utf8");
39
39
  } catch (error) {
40
40
  if (error instanceof WireFailure && error.code === "not-found") {
41
41
  throw new WireFailure("not-found", `There is no ${path}. Generate the source from the project knowledge into ${directory}. That also writes the source map.`);
@@ -89,9 +89,9 @@ Do the stages in this sequence. Go to the next stage only when its exit check is
89
89
  | 6. Analyze | Analyze the program statically. The analysis reads the program and the coverage from the project knowledge. | No coverage conflict is open. |
90
90
  | 7. Name | If the workspace has a routine library, match the program against it. Apply the matches to the project knowledge. Then name each routine in the scope and give it a comment. Find the platform addresses in the memory map of the C64. Record the modules. When the scope has hundreds of routines, ask the user which routines to name. The source gives the other routines an `l_xxxx` label. | Each routine that the user selected has a name and a comment. |
91
91
  | 8. Releases and switches | For a capture, copy its folder to `original/<label>/` first, because git ignores `.c64-re-tools/local/`. Record the original file as the base release in the project knowledge. Record each other release. Compare the releases. Find the leftovers. Record a switch for each copy protection, trainer, cheat, crack change and correction. Record a patch for each range of a switch. Record each leftover as a region with a comment. | The project knowledge lists each switch. Each difference between the releases is in a patch, or the answer gives it as an exception. |
92
- | 9. Generate | Generate the source from the project knowledge into `src`. For an unpacked program, also generate the loader. | The result of the generation is PASS. Each release with the result `layout differs` is an exception in the answer. |
92
+ | 9. Generate | Generate the source from the project knowledge into `src`. For an unpacked program, also generate the loader. | The result of the generation is PASS. Each release with the result `layout differs` is a version with a project of its own, or an exception in the answer. See "Versions of one program". |
93
93
  | 10. Build and test | Build the base release into `build/`, and compare it with the original. Build the default build. Run the test scenarios in `tests/`. Replay each recording on the rebuild. For each replay, give the checkpoint routine, the state and the random state with the names of stage 7. | The criteria of stage 1 are true. |
94
- | 11. Document | When the criteria ask for documentation, generate it into `README.md` and `docs/`. Then link it. | The link check of the documentation gives PASS. |
94
+ | 11. Document | When the criteria ask for documentation, generate it into `README.md` and `docs/`. For versions in a group folder, also write the shared pages of the group folder. Then link the pages. | The link check of the documentation gives PASS. |
95
95
  | 12. Hand over | Find each file that you made outside `.c64-re-tools/local/` and that is not a deliverable. Move it into `.c64-re-tools/local/`. Then give the answer (below). | Each file that you made outside `.c64-re-tools/local/` is a deliverable. |
96
96
 
97
97
  In stage 5, make the recordings before you change the program. A recording needs no names, and its coverage gives the analysis of stage 6 more code. If you cannot get to a part of the program, ask the user how to get to it. Do stages 7 to 9 again until the source is clear. Each generation writes the source again.
@@ -144,6 +144,29 @@ If the project has a layout, use that layout.
144
144
 
145
145
  A workspace with several projects keeps its routine library in `library/` beside the projects. The library is not a project folder.
146
146
 
147
+ ### Versions of one program
148
+
149
+ Some releases of a program have a different layout. Their code is at different addresses, so patches cannot hold the differences. Each of these releases is a version of the program. Give each version a project of its own in a group folder:
150
+
151
+ ```
152
+ <game>/ the group folder: not a project
153
+ README.md the shared entry page: the program, each version, and how the versions differ
154
+ docs/ the shared pages: the development, the changes between the versions, the releases, the disk layout
155
+ library/ the routine library of the versions
156
+ tools/ the scripts for the formats of the program, for all versions
157
+ v1/ the project of the first version, with the project layout
158
+ v2/ the project of the second version, with the project layout
159
+ ```
160
+
161
+ 1. Make the group folder in the git repository. Do not put `.c64-re-tools/` in it.
162
+ 2. Ask the user before you move a project folder. Then move the current project into `<game>/v1/`. The project knowledge keeps its paths relative to the project folder. Thus the knowledge stays valid after the move.
163
+ 3. Make a project folder for the new version, for example `<game>/v2/`. Start at stage 2 with the file of that release.
164
+ 4. Keep the releases with the same layout in one version. Record them as releases with switches. For example, `v2` holds a base release and a second release from a different crack.
165
+ 5. Save the routines of `v1` to the routine library in `<game>/library/`. In stage 7 of `v2`, match the program against that library. Then `v2` gets the names of `v1` for the same routines.
166
+ 6. Use the same folders in each version, for example `src` and `docs/reference`.
167
+ 7. From the group folder, give `--project v1` or `--project v2` to each script.
168
+ 8. Write the facts that the versions share one time, in the pages of the group folder. The pages of each version tell only how that version works.
169
+
147
170
  ## Knowledge
148
171
 
149
172
  Read:
package/src/project.ts CHANGED
@@ -130,6 +130,52 @@ export function namedProject(folder: string, cwd: string = process.cwd()): strin
130
130
  return path;
131
131
  }
132
132
 
133
+ /**
134
+ * A group folder: a folder of a git repository, in no project, that holds
135
+ * projects, for example one project for each version of a game. Its pages can
136
+ * link into each project, and a page of a project into the other projects.
137
+ */
138
+ export interface ProjectGroup {
139
+ root: string;
140
+ /** The absolute folder of each project in the group, by its folder name, sorted. */
141
+ projects: Map<string, string>;
142
+ }
143
+
144
+ /** True when `folder` or a folder above it holds .git. */
145
+ function inRepository(folder: string): boolean {
146
+ return foldersUpFrom(folder).some((each) => existsSync(join(each, ".git")));
147
+ }
148
+
149
+ /**
150
+ * The group at `folder`: its folders that are projects and are not a git
151
+ * repository of their own. Undefined when `folder` is the home folder, is in a
152
+ * project, is in no git repository, or holds no project.
153
+ */
154
+ export function groupAt(folder: string): ProjectGroup | undefined {
155
+ const root = resolve(folder);
156
+ if (root === homedir() || dirname(root) === root) return undefined;
157
+ if (foldersUpFrom(root).some(isProject) || !inRepository(root)) return undefined;
158
+ let entries;
159
+ try {
160
+ entries = readdirSync(root, { withFileTypes: true });
161
+ } catch {
162
+ return undefined;
163
+ }
164
+ const projects = new Map<string, string>();
165
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
166
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
167
+ const path = join(root, entry.name);
168
+ if (isProject(path) && !existsSync(join(path, ".git"))) projects.set(entry.name, path);
169
+ }
170
+ return projects.size === 0 ? undefined : { root, projects };
171
+ }
172
+
173
+ /** The group of the project `root`: the folder above it, when that is a group that holds the project. */
174
+ export function groupOf(root: string): ProjectGroup | undefined {
175
+ const group = groupAt(dirname(resolve(root)));
176
+ return group?.projects.get(basename(resolve(root))) === resolve(root) ? group : undefined;
177
+ }
178
+
133
179
  /**
134
180
  * The folder of a new project that `folder` names, relative to the project
135
181
  * `currentRoot` or absolute, and the zip file beside it (`<folder>.zip`). The