@inixiative/atlas 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -20
- package/examples/atlas-config/README.md +4 -3
- package/examples/atlas-config/config.ts +10 -2
- package/examples/ci/README.md +2 -2
- package/examples/ci/github-actions-incremental.yml +14 -12
- package/examples/ci/github-actions.yml +8 -7
- package/examples/ci/pre-commit +14 -12
- package/package.json +5 -5
- package/src/analyze.ts +120 -7
- package/src/cli.ts +72 -17
- package/src/commands/check.ts +10 -2
- package/src/commands/coverage.ts +8 -1
- package/src/commands/init.ts +78 -0
- package/src/commands/report.ts +0 -0
- package/src/commands/setup.ts +66 -22
- package/src/commands/stamp.ts +99 -31
- package/src/config/defineConfig.ts +10 -2
- package/src/config/load.ts +58 -2
- package/src/fs/walk.ts +90 -17
- package/src/hook/cachedGraph.ts +4 -1
- package/src/hook/claudeCode.ts +1 -1
- package/src/hook/neighbourhood.ts +3 -3
- package/src/index.ts +21 -1
- package/src/parse/parseAtlasBlock.ts +102 -20
- package/src/stamp/patcher.ts +46 -31
- package/src/syntax/comments.ts +260 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ConceptRegistry, Thesaurus } from '../registry/types.ts';
|
|
2
|
+
import type { CommentTable } from '../syntax/comments.ts';
|
|
2
3
|
|
|
3
4
|
// `partOfFor` is a LAZY descriptor, not a value. The consumer's config.ts can
|
|
4
5
|
// reference it before the concept registry is loaded; the stamp engine resolves it
|
|
@@ -49,17 +50,24 @@ export type ReferenceResolver = (value: string) => string;
|
|
|
49
50
|
type ConfigDefaults = {
|
|
50
51
|
stamp: StampRule[]; // path → tag rules
|
|
51
52
|
ignore: string[]; // files exempt from presence + stamping (tests, barrels)
|
|
52
|
-
include: string[]; // file globs atlas considers (default: common source files)
|
|
53
53
|
references: Record<string, ReferenceResolver>;
|
|
54
54
|
};
|
|
55
55
|
|
|
56
|
-
export type AtlasConfigInput = Partial<ConfigDefaults
|
|
56
|
+
export type AtlasConfigInput = Partial<ConfigDefaults> & {
|
|
57
|
+
// file globs atlas considers. Unset: every file in a comment style atlas knows, plus every
|
|
58
|
+
// file a stamp rule tags by its path.
|
|
59
|
+
include?: string[];
|
|
60
|
+
// more files per comment style: `{ hash: ['.nix', 'Tiltfile'] }` (`.ext` or an exact name)
|
|
61
|
+
comments?: CommentTable;
|
|
62
|
+
};
|
|
57
63
|
|
|
58
64
|
export const defineConfig = (config: AtlasConfigInput): AtlasConfigInput => config;
|
|
59
65
|
|
|
60
66
|
// What the loader hands the engine once defaults are applied and vocab/registry
|
|
61
67
|
// are loaded from the sibling .atlas/ files.
|
|
62
68
|
export type LoadedConfig = ConfigDefaults & {
|
|
69
|
+
include: string[] | null; // null: the default (see AtlasConfigInput.include)
|
|
70
|
+
comments: Required<CommentTable>; // atlas's table merged with the repo's additions
|
|
63
71
|
kinds: readonly string[];
|
|
64
72
|
concepts: ConceptRegistry;
|
|
65
73
|
thesaurus: Thesaurus;
|
package/src/config/load.ts
CHANGED
|
@@ -1,9 +1,48 @@
|
|
|
1
1
|
import { resolve } from 'node:path';
|
|
2
|
-
import { DEFAULT_INCLUDE } from '../fs/walk.ts';
|
|
3
2
|
import type { ConceptRegistry, Thesaurus } from '../registry/types.ts';
|
|
3
|
+
import { COMMENT_STYLES, type CommentTable, mergeCommentTable } from '../syntax/comments.ts';
|
|
4
4
|
import { DEFAULT_KINDS } from '../vocab/kinds.ts';
|
|
5
5
|
import type { AtlasConfigInput, LoadedConfig } from './defineConfig.ts';
|
|
6
6
|
|
|
7
|
+
// `.atlas/**/*.ts` imports `@inixiative/atlas` (defineConfig, partOfFor, DEFAULT_KINDS). Bind those
|
|
8
|
+
// imports to the atlas that is running, so the config loads in a repo with no package.json or
|
|
9
|
+
// node_modules (`bunx @inixiative/atlas check` in a Python repo) and never against another
|
|
10
|
+
// installed version. Bun's runtime plugins ignore onResolve for bare imports, so the specifier
|
|
11
|
+
// is rewritten on load.
|
|
12
|
+
const SELF: Record<string, string> = {
|
|
13
|
+
'@inixiative/atlas': resolve(import.meta.dir, '../index.ts'),
|
|
14
|
+
'@inixiative/atlas/config': resolve(import.meta.dir, './defineConfig.ts'),
|
|
15
|
+
};
|
|
16
|
+
// only a module specifier: `from '…'`, `import '…'`, `import('…')`, never another string literal
|
|
17
|
+
const ATLAS_IMPORT = /(\bfrom\s*|\bimport\s*\(?\s*)(['"])(@inixiative\/atlas(?:\/config)?)\2/g;
|
|
18
|
+
|
|
19
|
+
// Rewrite a config file's atlas imports to `paths`. The path is spliced into the file's own
|
|
20
|
+
// string literal, so it is written with forward slashes (a Windows `\` would be read as an
|
|
21
|
+
// escape: `C:\Users\node_modules` → `C:Users<newline>ode_modules`; Bun accepts `C:/…`) and the
|
|
22
|
+
// literal's quote is escaped (an install under `O'Brien/`).
|
|
23
|
+
export const bindAtlasImports = (source: string, paths: Record<string, string> = SELF): string =>
|
|
24
|
+
source.replace(ATLAS_IMPORT, (match, keyword: string, quote: string, specifier: string) => {
|
|
25
|
+
const path = paths[specifier];
|
|
26
|
+
if (!path) return match;
|
|
27
|
+
return `${keyword}${quote}${path.replaceAll('\\', '/').replaceAll(quote, `\\${quote}`)}${quote}`;
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
let bound = false;
|
|
31
|
+
const bindSelfImports = (): void => {
|
|
32
|
+
if (bound) return;
|
|
33
|
+
bound = true;
|
|
34
|
+
Bun.plugin({
|
|
35
|
+
name: 'atlas-config-self',
|
|
36
|
+
target: 'bun',
|
|
37
|
+
setup(build) {
|
|
38
|
+
build.onLoad({ filter: /[\\/]\.atlas[\\/].+\.[cm]?ts$/ }, async ({ path }) => ({
|
|
39
|
+
loader: 'ts',
|
|
40
|
+
contents: bindAtlasImports(await Bun.file(path).text()),
|
|
41
|
+
}));
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
};
|
|
45
|
+
|
|
7
46
|
// Import a `.atlas/` file if it exists; missing files are optional (atlas ships
|
|
8
47
|
// defaults for vocab), but a present file with a real error propagates.
|
|
9
48
|
const loadModule = async (path: string): Promise<Record<string, unknown> | null> => {
|
|
@@ -24,10 +63,26 @@ const named = <T>(
|
|
|
24
63
|
throw new Error(`.atlas/${file} exists but exports none of: ${names.join(', ')}`);
|
|
25
64
|
};
|
|
26
65
|
|
|
66
|
+
// `comments` names styles atlas has; a typo would silently tag nothing, so refuse it.
|
|
67
|
+
const validComments = (comments: CommentTable | undefined): CommentTable | undefined => {
|
|
68
|
+
for (const [style, entries] of Object.entries(comments ?? {})) {
|
|
69
|
+
if (!(style in COMMENT_STYLES))
|
|
70
|
+
throw new Error(
|
|
71
|
+
`.atlas/config.ts: comments.${style} is not a comment style (${Object.keys(COMMENT_STYLES).join(', ')})`,
|
|
72
|
+
);
|
|
73
|
+
if (!Array.isArray(entries) || entries.some((e) => typeof e !== 'string' || e === ''))
|
|
74
|
+
throw new Error(
|
|
75
|
+
`.atlas/config.ts: comments.${style} must list '.ext' extensions or file names`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
return comments;
|
|
79
|
+
};
|
|
80
|
+
|
|
27
81
|
// Load the consumer's `.atlas/` config: kinds → concepts → thesaurus → config (no
|
|
28
82
|
// evaluation-order coupling, since partOfFor is a lazy descriptor). atlas ships
|
|
29
83
|
// the kinds defaults; the repo OWNS concepts.ts and the optional thesaurus.ts.
|
|
30
84
|
export const loadConfig = async (root: string): Promise<LoadedConfig> => {
|
|
85
|
+
bindSelfImports();
|
|
31
86
|
const dir = resolve(root, '.atlas');
|
|
32
87
|
const [kindsMod, conceptsMod, thesaurusMod, configMod] = await Promise.all([
|
|
33
88
|
loadModule(resolve(dir, 'kinds.ts')),
|
|
@@ -71,12 +126,13 @@ export const loadConfig = async (root: string): Promise<LoadedConfig> => {
|
|
|
71
126
|
}
|
|
72
127
|
|
|
73
128
|
return {
|
|
129
|
+
include: cfg.include ?? null,
|
|
130
|
+
comments: mergeCommentTable(validComments(cfg.comments)),
|
|
74
131
|
kinds,
|
|
75
132
|
concepts,
|
|
76
133
|
thesaurus,
|
|
77
134
|
stamp: cfg.stamp ?? [],
|
|
78
135
|
ignore: cfg.ignore ?? [],
|
|
79
|
-
include: cfg.include ?? DEFAULT_INCLUDE,
|
|
80
136
|
references: cfg.references ?? {},
|
|
81
137
|
};
|
|
82
138
|
};
|
package/src/fs/walk.ts
CHANGED
|
@@ -1,26 +1,99 @@
|
|
|
1
|
+
import { existsSync, lstatSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
1
3
|
import { Glob } from 'bun';
|
|
2
4
|
import { matchesAny } from '../config/glob.ts';
|
|
3
5
|
|
|
4
|
-
|
|
6
|
+
// Never considered, whatever the config says. Dotdirs are walked (`.claude/`, `.github/` carry
|
|
7
|
+
// real work); these aren't. `.atlas/` is the config itself; MAP.md, COVERAGE.md and atlas.html
|
|
8
|
+
// are what `generate` and `report` write (stamping one would fight the next generate); a pnpm
|
|
9
|
+
// lockfile is generated and pnpm strips comments from it.
|
|
10
|
+
export const ALWAYS_IGNORE = [
|
|
11
|
+
'**/node_modules/**',
|
|
12
|
+
'**/.git/**',
|
|
13
|
+
'**/dist/**',
|
|
14
|
+
'**/.atlas/**',
|
|
15
|
+
'MAP.md', // generate writes it at the root only
|
|
16
|
+
'**/COVERAGE.md', // report writes these wherever --out points
|
|
17
|
+
'**/atlas.html',
|
|
18
|
+
'**/pnpm-lock.yaml',
|
|
19
|
+
];
|
|
5
20
|
|
|
6
|
-
|
|
7
|
-
|
|
21
|
+
const git = async (root: string, args: string[]) => {
|
|
22
|
+
let proc: ReturnType<typeof Bun.spawn>;
|
|
23
|
+
try {
|
|
24
|
+
// LC_ALL=C: git's messages are read below, and a translated git words them differently
|
|
25
|
+
proc = Bun.spawn(['git', ...args], {
|
|
26
|
+
cwd: root,
|
|
27
|
+
stdout: 'pipe',
|
|
28
|
+
stderr: 'pipe',
|
|
29
|
+
env: { ...process.env, LC_ALL: 'C' },
|
|
30
|
+
});
|
|
31
|
+
} catch {
|
|
32
|
+
throw new Error('atlas lists files with git, and git is not installed');
|
|
33
|
+
}
|
|
34
|
+
const [out, err, code] = await Promise.all([
|
|
35
|
+
new Response(proc.stdout as ReadableStream).text(),
|
|
36
|
+
new Response(proc.stderr as ReadableStream).text(),
|
|
37
|
+
proc.exited,
|
|
38
|
+
]);
|
|
39
|
+
return { out, err: err.trim(), code };
|
|
40
|
+
};
|
|
8
41
|
|
|
9
|
-
//
|
|
10
|
-
//
|
|
42
|
+
// What git would commit: tracked files plus untracked ones that aren't ignored, so a new file is
|
|
43
|
+
// seen before it's added and generated output under .gitignore never is. Null when the root is
|
|
44
|
+
// not part of a repo: outside any work tree, or a folder the enclosing repo ignores (a scratch
|
|
45
|
+
// dir). Any other git failure (`safe.directory`, a broken index) is an error, never a silent
|
|
46
|
+
// switch to listing every file.
|
|
47
|
+
const gitFiles = async (root: string): Promise<string[] | null> => {
|
|
48
|
+
const inside = await git(root, ['rev-parse', '--is-inside-work-tree']);
|
|
49
|
+
if (inside.code !== 0) {
|
|
50
|
+
if (/not a git repository/i.test(inside.err)) return null;
|
|
51
|
+
throw new Error(`git rev-parse failed in ${root}: ${inside.err}`);
|
|
52
|
+
}
|
|
53
|
+
if (inside.out.trim() !== 'true') return null; // inside a .git dir or a bare repo
|
|
54
|
+
if ((await git(root, ['check-ignore', '-q', '.'])).code === 0) return null;
|
|
55
|
+
const listed = await git(root, ['ls-files', '-z', '--cached', '--others', '--exclude-standard']);
|
|
56
|
+
if (listed.code !== 0) throw new Error(`git ls-files failed in ${root}: ${listed.err}`);
|
|
57
|
+
// An untracked nested repo or worktree is listed as `dir/`; it isn't a file of this repo.
|
|
58
|
+
// A submodule is a gitlink, not a file, so its contents aren't walked either.
|
|
59
|
+
return [...new Set(listed.out.split('\0'))].filter((p) => p !== '' && !p.endsWith('/'));
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// A directory that isn't part of a repo (a fixture, an unpacked tarball, a fresh docs folder):
|
|
63
|
+
// every file in it.
|
|
64
|
+
const allFiles = async (root: string): Promise<string[]> => {
|
|
65
|
+
const files: string[] = [];
|
|
66
|
+
for await (const entry of new Glob('**/*').scan({ cwd: root, onlyFiles: true, dot: true }))
|
|
67
|
+
files.push(entry.replaceAll('\\', '/'));
|
|
68
|
+
return files;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// A regular file, not a symlink: a link may point outside the repo (stamp would write there) or
|
|
72
|
+
// at another listed file (stamped twice). Deleted-but-indexed files are skipped too.
|
|
73
|
+
const isFile = (root: string, path: string): boolean => {
|
|
74
|
+
try {
|
|
75
|
+
return lstatSync(resolve(root, path)).isFile();
|
|
76
|
+
} catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// Repo-relative files not ignored, sorted for deterministic output. `keep` decides which of the
|
|
82
|
+
// rest atlas considers (an include list, or the default in analyze.ts).
|
|
11
83
|
export const walkFiles = async (
|
|
12
84
|
root: string,
|
|
13
|
-
|
|
14
|
-
|
|
85
|
+
ignore: string[],
|
|
86
|
+
keep: (path: string) => boolean,
|
|
15
87
|
): Promise<string[]> => {
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
88
|
+
if (!existsSync(root)) throw new Error(`no such directory: ${root}`);
|
|
89
|
+
const listed = (await gitFiles(root)) ?? (await allFiles(root));
|
|
90
|
+
return listed
|
|
91
|
+
.filter(
|
|
92
|
+
(path) =>
|
|
93
|
+
!matchesAny(ALWAYS_IGNORE, path) &&
|
|
94
|
+
!matchesAny(ignore, path) &&
|
|
95
|
+
keep(path) &&
|
|
96
|
+
isFile(root, path),
|
|
97
|
+
)
|
|
98
|
+
.sort();
|
|
26
99
|
};
|
package/src/hook/cachedGraph.ts
CHANGED
|
@@ -20,9 +20,12 @@ const cachePathFor = (root: string, cacheDir: string, version: string): string =
|
|
|
20
20
|
);
|
|
21
21
|
|
|
22
22
|
// A `.atlas/` edit (new concept, new rule) makes the cached graph wrong before the TTL does.
|
|
23
|
+
// Every file under `.atlas/`, helpers in subfolders included (their imports load too).
|
|
23
24
|
const configNewerThan = (root: string, mtimeMs: number): boolean => {
|
|
24
25
|
const dir = join(root, '.atlas');
|
|
25
|
-
return readdirSync(dir
|
|
26
|
+
return readdirSync(dir, { recursive: true }).some(
|
|
27
|
+
(entry) => statSync(join(dir, String(entry))).mtimeMs > mtimeMs,
|
|
28
|
+
);
|
|
26
29
|
};
|
|
27
30
|
|
|
28
31
|
// The hooks fire on every Read/Grep and a full analyze walks the whole tree (seconds on a
|
package/src/hook/claudeCode.ts
CHANGED
|
@@ -20,7 +20,7 @@ export const toAdditionalContext = (text: string): string => {
|
|
|
20
20
|
if (trimmed === '') return '';
|
|
21
21
|
const body =
|
|
22
22
|
trimmed.length > MAX_CHARS
|
|
23
|
-
? `${trimmed.slice(0, MAX_CHARS)}\n… (truncated; bunx atlas query --partOf <concept> lists the rest)`
|
|
23
|
+
? `${trimmed.slice(0, MAX_CHARS)}\n… (truncated; bunx @inixiative/atlas query --partOf <concept> lists the rest)`
|
|
24
24
|
: trimmed;
|
|
25
25
|
return JSON.stringify({
|
|
26
26
|
suppressOutput: true,
|
|
@@ -73,7 +73,7 @@ export const renderNeighbourhood = (
|
|
|
73
73
|
siblings.length > SIBLING_SAMPLE ? [` … ${siblings.length - SIBLING_SAMPLE} more`] : [];
|
|
74
74
|
const consumers = graph.usesConsumers[concept]?.length ?? 0;
|
|
75
75
|
return [
|
|
76
|
-
`${concept} — ${siblings.length} other file(s)${consumers > 0 ? `, ${consumers} consumer(s) via @uses` : ''}; \`bunx atlas query --partOf ${concept}\` lists all`,
|
|
76
|
+
`${concept} — ${siblings.length} other file(s)${consumers > 0 ? `, ${consumers} consumer(s) via @uses` : ''}; \`bunx @inixiative/atlas query --partOf ${concept}\` lists all`,
|
|
77
77
|
...sample,
|
|
78
78
|
...more,
|
|
79
79
|
].join('\n');
|
|
@@ -81,7 +81,7 @@ export const renderNeighbourhood = (
|
|
|
81
81
|
const usesBlock =
|
|
82
82
|
membership.uses.length > 0
|
|
83
83
|
? [
|
|
84
|
-
`@uses ${membership.uses.join(', ')} — load-bearing dependencies; \`bunx atlas query --partOf <concept>\` shows what implements each`,
|
|
84
|
+
`@uses ${membership.uses.join(', ')} — load-bearing dependencies; \`bunx @inixiative/atlas query --partOf <concept>\` shows what implements each`,
|
|
85
85
|
]
|
|
86
86
|
: [];
|
|
87
87
|
const kinds = kindLines(graph, relPath, membership.partOf, options.kinds ?? REACH_KINDS);
|
|
@@ -230,7 +230,7 @@ const conceptBlock = (graph: Graph, concept: string, label: string): string => {
|
|
|
230
230
|
const consumers = graph.usesConsumers[concept]?.length ?? 0;
|
|
231
231
|
const doc = graph.thesaurus[concept]?.doc;
|
|
232
232
|
return [
|
|
233
|
-
`${concept}${label} — ${files.length} file(s)${consumers > 0 ? `, ${consumers} consumer(s) via @uses` : ''}; \`bunx atlas query --partOf ${concept}\` lists all`,
|
|
233
|
+
`${concept}${label} — ${files.length} file(s)${consumers > 0 ? `, ${consumers} consumer(s) via @uses` : ''}; \`bunx @inixiative/atlas query --partOf ${concept}\` lists all`,
|
|
234
234
|
...(doc ? [` read: ${doc}`] : []),
|
|
235
235
|
...sample,
|
|
236
236
|
...more,
|
package/src/index.ts
CHANGED
|
@@ -4,8 +4,10 @@ export type { Graph } from './commands/graph.ts';
|
|
|
4
4
|
export {
|
|
5
5
|
atlasHookEntry,
|
|
6
6
|
CLAUDE_SETTINGS,
|
|
7
|
+
type HookRunner,
|
|
7
8
|
hookCommandFor,
|
|
8
9
|
mergeAtlasHooks,
|
|
10
|
+
runnerFor,
|
|
9
11
|
type SetupReport,
|
|
10
12
|
setupClaudeHooks,
|
|
11
13
|
} from './commands/setup.ts';
|
|
@@ -35,7 +37,13 @@ export {
|
|
|
35
37
|
renderConceptMatches,
|
|
36
38
|
renderNeighbourhood,
|
|
37
39
|
} from './hook/neighbourhood.ts';
|
|
38
|
-
export {
|
|
40
|
+
export {
|
|
41
|
+
type AtlasAnnotation,
|
|
42
|
+
type LocatedBlock,
|
|
43
|
+
locateAtlasBlock,
|
|
44
|
+
parseAtlasBlock,
|
|
45
|
+
type UsesState,
|
|
46
|
+
} from './parse/parseAtlasBlock.ts';
|
|
39
47
|
export { invert } from './registry/invert.ts';
|
|
40
48
|
export {
|
|
41
49
|
type ConceptEntry,
|
|
@@ -45,4 +53,16 @@ export {
|
|
|
45
53
|
type Thesaurus,
|
|
46
54
|
type ThesaurusEntry,
|
|
47
55
|
} from './registry/types.ts';
|
|
56
|
+
export {
|
|
57
|
+
COMMENT_STYLES,
|
|
58
|
+
COMMENT_TABLE,
|
|
59
|
+
type CommentStyle,
|
|
60
|
+
type CommentStyleName,
|
|
61
|
+
type CommentTable,
|
|
62
|
+
entryFor,
|
|
63
|
+
mergeCommentTable,
|
|
64
|
+
preambleEnd,
|
|
65
|
+
styleFor,
|
|
66
|
+
styleNameFor,
|
|
67
|
+
} from './syntax/comments.ts';
|
|
48
68
|
export { DEFAULT_KINDS, type DefaultKind } from './vocab/kinds.ts';
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { CommentStyle } from '../syntax/comments.ts';
|
|
2
|
+
|
|
1
3
|
// @uses carries curation state — its absence is meaningful (uncurated) and
|
|
2
4
|
// distinct from an explicit empty (curated-empty), which is distinct from a
|
|
3
5
|
// patcher proposal awaiting human acceptance.
|
|
@@ -16,10 +18,10 @@ export type AtlasAnnotation = {
|
|
|
16
18
|
axes: Record<string, string[]>;
|
|
17
19
|
};
|
|
18
20
|
|
|
19
|
-
// Each axis line: optional leading `*`, the @tag,
|
|
20
|
-
// marker, then the comma-separated values.
|
|
21
|
+
// Each axis line, once its comment decoration is stripped: an optional leading `*`, the @tag,
|
|
22
|
+
// an optional `?` tentative marker, then the comma-separated values.
|
|
21
23
|
const AXIS_LINE = /^\s*\*?\s*@([a-zA-Z][\w]*)(\??)[ \t]*(.*)$/;
|
|
22
|
-
const
|
|
24
|
+
const OPENS_ATLAS = /^\s*\*?\s*@atlas\b/;
|
|
23
25
|
|
|
24
26
|
const dedupe = (values: string[]): string[] => [...new Set(values)];
|
|
25
27
|
|
|
@@ -31,29 +33,109 @@ const splitValues = (raw: string): string[] =>
|
|
|
31
33
|
.filter((v) => v.length > 0),
|
|
32
34
|
);
|
|
33
35
|
|
|
34
|
-
const
|
|
36
|
+
const escapeRegex = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
37
|
+
|
|
38
|
+
type BlockStyle = Extract<CommentStyle, { shape: 'block' }>;
|
|
39
|
+
type LineStyle = Extract<CommentStyle, { shape: 'line' }>;
|
|
40
|
+
|
|
41
|
+
export type LocatedBlock = { start: number; end: number; text: string };
|
|
42
|
+
|
|
43
|
+
// A line comment: the prefix, any repeats of its last character (`;;`, `##`, `---`, `///`), then
|
|
44
|
+
// the text the axis grammar reads.
|
|
45
|
+
const lineComment = (style: LineStyle): RegExp =>
|
|
46
|
+
new RegExp(
|
|
47
|
+
`^[ \\t]*${escapeRegex(style.prefix)}${escapeRegex(style.prefix.slice(-1))}*(.*?)\\r?$`,
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
// A one-line block holding only `@atlas` (`<!-- @atlas -->`, `/** @atlas pin */`) is a block
|
|
51
|
+
// waiting for its axes. A block a formatter collapsed onto one line (`/** * @atlas * @kind x */`)
|
|
52
|
+
// is not: it stays unreadable, and `check` reports it instead of reading a block with no tags.
|
|
53
|
+
const ONLY_OPENER = /^\s*\*?\s*@atlas(?:[ \t]+pin)?\s*$/;
|
|
54
|
+
|
|
55
|
+
// The lines of a comment as the axis grammar reads them. Line comments lose their prefix. Block
|
|
56
|
+
// comments keep their lines as written (AXIS_LINE reads past a ` * `), each axis on its own line.
|
|
57
|
+
export const commentBody = (text: string, style: CommentStyle): string[] => {
|
|
58
|
+
if (style.shape === 'line') {
|
|
59
|
+
const comment = lineComment(style);
|
|
60
|
+
return text.split(/\r?\n/).map((raw) => comment.exec(raw)?.[1] ?? raw);
|
|
61
|
+
}
|
|
62
|
+
if (!text.includes('\n') && text.startsWith(style.open) && text.endsWith(style.close)) {
|
|
63
|
+
const inner = text.slice(style.open.length, -style.close.length).replace(/^\*+/, '');
|
|
64
|
+
if (ONLY_OPENER.test(inner)) return [inner];
|
|
65
|
+
}
|
|
66
|
+
return text.split(/\r?\n/);
|
|
67
|
+
};
|
|
35
68
|
|
|
36
|
-
//
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
for (let m =
|
|
43
|
-
if (
|
|
69
|
+
// Block styles: the first comment with an `@atlas` line.
|
|
70
|
+
const locateInBlocks = (source: string, style: BlockStyle): LocatedBlock | null => {
|
|
71
|
+
const comment = new RegExp(
|
|
72
|
+
`${escapeRegex(style.open)}[\\s\\S]*?${escapeRegex(style.close)}`,
|
|
73
|
+
'g',
|
|
74
|
+
);
|
|
75
|
+
for (let m = comment.exec(source); m !== null; m = comment.exec(source)) {
|
|
76
|
+
if (commentBody(m[0], style).some((line) => OPENS_ATLAS.test(line))) {
|
|
44
77
|
return { start: m.index, end: m.index + m[0].length, text: m[0] };
|
|
45
78
|
}
|
|
46
79
|
}
|
|
47
80
|
return null;
|
|
48
81
|
};
|
|
49
82
|
|
|
50
|
-
//
|
|
51
|
-
//
|
|
52
|
-
//
|
|
53
|
-
|
|
54
|
-
|
|
83
|
+
// The axes the stamper writes back. A line block continues only through these, so a doc tag on
|
|
84
|
+
// the next line (LuaLS `---@class`, YARD `# @deprecated`, `-- @name` in SQL) is never absorbed
|
|
85
|
+
// into the block and dropped on the next stamp.
|
|
86
|
+
const WRITTEN_AXIS = /^\s*@(?:kind|partOf|uses\??|constructs)\b/;
|
|
87
|
+
|
|
88
|
+
// Line styles: the first comment line reading `@atlas`, then the axis lines after it (an empty
|
|
89
|
+
// comment line between two axis lines is bridged). The block ends at its last axis line and stops
|
|
90
|
+
// at the first other line, so prose comments next to it are never part of it, and the stamper
|
|
91
|
+
// never rewrites them.
|
|
92
|
+
const locateInLines = (source: string, style: LineStyle): LocatedBlock | null => {
|
|
93
|
+
const comment = lineComment(style);
|
|
94
|
+
let offset = 0;
|
|
95
|
+
let start = -1;
|
|
96
|
+
let end = -1;
|
|
97
|
+
for (const line of source.split('\n')) {
|
|
98
|
+
const body = comment.exec(line)?.[1];
|
|
99
|
+
const lineEnd = offset + line.replace(/\r$/, '').length;
|
|
100
|
+
if (start < 0) {
|
|
101
|
+
if (body !== undefined && OPENS_ATLAS.test(body)) {
|
|
102
|
+
start = offset;
|
|
103
|
+
end = lineEnd;
|
|
104
|
+
}
|
|
105
|
+
} else if (body !== undefined && WRITTEN_AXIS.test(body)) {
|
|
106
|
+
end = lineEnd;
|
|
107
|
+
} else if (body === undefined || body.trim() !== '') break;
|
|
108
|
+
offset += line.length + 1;
|
|
109
|
+
}
|
|
110
|
+
return start < 0 ? null : { start, end, text: source.slice(start, end) };
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// Does a comment in the file's own style name `@atlas`? When one does but no block parses from
|
|
114
|
+
// it (collapsed onto one line, mangled by hand), the stamper must not add a second block.
|
|
115
|
+
const NAMES_ATLAS = /(?:^|[\s*])@atlas\b/;
|
|
116
|
+
export const mentionsAtlas = (source: string, style: CommentStyle): boolean => {
|
|
117
|
+
if (style.shape === 'line') {
|
|
118
|
+
const comment = lineComment(style);
|
|
119
|
+
return source.split('\n').some((line) => NAMES_ATLAS.test(comment.exec(line)?.[1] ?? ''));
|
|
120
|
+
}
|
|
121
|
+
const comment = new RegExp(
|
|
122
|
+
`${escapeRegex(style.open)}[\\s\\S]*?${escapeRegex(style.close)}`,
|
|
123
|
+
'g',
|
|
124
|
+
);
|
|
125
|
+
return [...source.matchAll(comment)].some((m) => NAMES_ATLAS.test(m[0].slice(style.open.length)));
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
// Locate the first comment that opens with `@atlas`, in the file's comment style, returning its
|
|
129
|
+
// text and character span so the patcher can splice a regenerated block in place.
|
|
130
|
+
export const locateAtlasBlock = (source: string, style: CommentStyle): LocatedBlock | null =>
|
|
131
|
+
style.shape === 'block' ? locateInBlocks(source, style) : locateInLines(source, style);
|
|
132
|
+
|
|
133
|
+
// Parse the first comment that opens with `@atlas`, in the file's comment style. Returns null if
|
|
134
|
+
// the file carries no atlas block. Parsing is scoped to that block, so a stray `@uses` in code or
|
|
135
|
+
// prose elsewhere never false-matches.
|
|
136
|
+
export const parseAtlasBlock = (source: string, style: CommentStyle): AtlasAnnotation | null => {
|
|
137
|
+
const located = locateAtlasBlock(source, style);
|
|
55
138
|
if (!located) return null;
|
|
56
|
-
const atlasBlock = located.text;
|
|
57
139
|
|
|
58
140
|
const axes: Record<string, string[]> = {};
|
|
59
141
|
let pinned = false;
|
|
@@ -64,8 +146,8 @@ export const parseAtlasBlock = (source: string): AtlasAnnotation | null => {
|
|
|
64
146
|
let usesProposed = false;
|
|
65
147
|
const usesValues: string[] = [];
|
|
66
148
|
|
|
67
|
-
//
|
|
68
|
-
for (const line of
|
|
149
|
+
// commentBody splits on \r?\n, so CRLF files don't leave a trailing \r polluting values.
|
|
150
|
+
for (const line of commentBody(located.text, style)) {
|
|
69
151
|
const m = AXIS_LINE.exec(line);
|
|
70
152
|
if (!m) continue;
|
|
71
153
|
const [, name, tentative, rest] = m;
|
package/src/stamp/patcher.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
type AtlasAnnotation,
|
|
3
3
|
locateAtlasBlock,
|
|
4
|
+
mentionsAtlas,
|
|
4
5
|
parseAtlasBlock,
|
|
5
6
|
type UsesState,
|
|
6
7
|
} from '../parse/parseAtlasBlock.ts';
|
|
8
|
+
import { type CommentStyle, preambleEnd } from '../syntax/comments.ts';
|
|
7
9
|
|
|
8
10
|
export type BlockSpec = {
|
|
9
11
|
kind?: string[];
|
|
@@ -24,19 +26,21 @@ export type StampInput = {
|
|
|
24
26
|
|
|
25
27
|
export type StampMode = 'additive' | 'overwrite';
|
|
26
28
|
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
// Render a canonical `@atlas` block. Axis order is fixed for
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if (spec.
|
|
34
|
-
if (spec.
|
|
35
|
-
|
|
36
|
-
else if (spec.usesState === '
|
|
37
|
-
if (spec.
|
|
38
|
-
|
|
39
|
-
|
|
29
|
+
const axis = (name: string, values: string[]): string => `@${name} ${values.join(', ')}`;
|
|
30
|
+
|
|
31
|
+
// Render a canonical `@atlas` block in the file's comment style. Axis order is fixed for
|
|
32
|
+
// diff-stability.
|
|
33
|
+
export const renderBlock = (spec: BlockSpec, style: CommentStyle): string => {
|
|
34
|
+
const axes = [spec.pinned ? '@atlas pin' : '@atlas'];
|
|
35
|
+
if (spec.kind?.length) axes.push(axis('kind', spec.kind));
|
|
36
|
+
if (spec.partOf?.length) axes.push(axis('partOf', spec.partOf));
|
|
37
|
+
if (spec.usesState === 'none') axes.push('@uses none');
|
|
38
|
+
else if (spec.usesState === 'proposed' && spec.uses?.length) axes.push(axis('uses?', spec.uses));
|
|
39
|
+
else if (spec.usesState === 'values' && spec.uses?.length) axes.push(axis('uses', spec.uses));
|
|
40
|
+
if (spec.constructs?.length) axes.push(axis('constructs', spec.constructs));
|
|
41
|
+
if (style.shape === 'line')
|
|
42
|
+
return axes.map((a) => `${style.writePrefix ?? style.prefix} ${a}`).join('\n');
|
|
43
|
+
return [style.writeOpen, ...axes.map((a) => `${style.line}${a}`), style.writeClose].join('\n');
|
|
40
44
|
};
|
|
41
45
|
|
|
42
46
|
const union = (a: string[] = [], b: string[] = []): string[] => [...new Set([...a, ...b])];
|
|
@@ -45,29 +49,34 @@ const detectEol = (source: string): string => (source.includes('\r\n') ? '\r\n'
|
|
|
45
49
|
|
|
46
50
|
// Renders the canonical (LF) block, then matches the file's existing EOL so a
|
|
47
51
|
// CRLF file round-trips without churn or mixed endings.
|
|
48
|
-
const renderWithEol = (spec: BlockSpec, eol: string): string =>
|
|
49
|
-
eol === '\n' ? renderBlock(spec) : renderBlock(spec).replaceAll('\n', eol);
|
|
50
|
-
|
|
51
|
-
// A fresh block belongs at the top, but below a shebang (moving it above would
|
|
52
|
-
// break an executable script).
|
|
53
|
-
const SHEBANG = /^#![^\n]*\n/;
|
|
52
|
+
const renderWithEol = (spec: BlockSpec, style: CommentStyle, eol: string): string =>
|
|
53
|
+
eol === '\n' ? renderBlock(spec, style) : renderBlock(spec, style).replaceAll('\n', eol);
|
|
54
54
|
|
|
55
55
|
const carryUses = (existing: AtlasAnnotation | null): Pick<BlockSpec, 'uses' | 'usesState'> =>
|
|
56
56
|
existing ? { uses: existing.uses, usesState: existing.usesState } : {};
|
|
57
57
|
|
|
58
|
+
// Why a file atlas would stamp was left alone: it already has an `@atlas` comment no block
|
|
59
|
+
// parses from (a second block would hide it), its language allows none where atlas would put it
|
|
60
|
+
// (a PHP file that starts as HTML), or its bytes aren't valid in its encoding (writing the text
|
|
61
|
+
// back would replace them with U+FFFD).
|
|
62
|
+
export type StampSkip = 'unreadable' | 'no-place' | 'encoding';
|
|
63
|
+
|
|
58
64
|
// Merge a stamp into a file's source per mode. Returns the new content and
|
|
59
65
|
// whether anything changed (idempotent: a no-op re-stamp reports changed=false).
|
|
66
|
+
// `path` decides where a fresh block goes (below the file's preamble).
|
|
60
67
|
export const applyStamp = (
|
|
61
68
|
source: string,
|
|
62
69
|
resolved: StampInput,
|
|
70
|
+
file: { path: string; style: CommentStyle },
|
|
63
71
|
mode: StampMode = 'additive',
|
|
64
|
-
): { content: string; changed: boolean } => {
|
|
65
|
-
const
|
|
66
|
-
const
|
|
72
|
+
): { content: string; changed: boolean; skipped?: StampSkip } => {
|
|
73
|
+
const { style } = file;
|
|
74
|
+
const existing = parseAtlasBlock(source, style);
|
|
75
|
+
const located = locateAtlasBlock(source, style);
|
|
67
76
|
const eol = detectEol(source);
|
|
68
77
|
|
|
69
|
-
// No block yet — insert a fresh one at the top (uses omitted = uncurated),
|
|
70
|
-
//
|
|
78
|
+
// No block yet — insert a fresh one at the top (uses omitted = uncurated), but below
|
|
79
|
+
// the lines that must stay first (a shebang, front matter, `<?php`; see preambleEnd).
|
|
71
80
|
if (!existing || !located) {
|
|
72
81
|
const spec: BlockSpec = {
|
|
73
82
|
kind: resolved.kind ?? [],
|
|
@@ -76,12 +85,18 @@ export const applyStamp = (
|
|
|
76
85
|
};
|
|
77
86
|
const hasAny = [spec.kind, spec.partOf, spec.constructs].some((v) => v && v.length);
|
|
78
87
|
if (!hasAny) return { content: source, changed: false };
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
88
|
+
if (mentionsAtlas(source, style))
|
|
89
|
+
return { content: source, changed: false, skipped: 'unreadable' };
|
|
90
|
+
const at = preambleEnd(file.path, source);
|
|
91
|
+
const head = source.slice(0, at);
|
|
92
|
+
const rest = source.slice(at);
|
|
93
|
+
if (style.placeAfter && !style.placeAfter.test(head))
|
|
94
|
+
return { content: source, changed: false, skipped: 'no-place' };
|
|
95
|
+
// a preamble that ends the file without a newline still gets one before the block
|
|
96
|
+
const before = head !== '' && !head.endsWith('\n') ? eol : '';
|
|
97
|
+
const blank = style.blankAfter && rest !== '' && !/^\r?\n/.test(rest) ? eol : '';
|
|
98
|
+
const block = renderWithEol(spec, style, eol);
|
|
99
|
+
return { content: head + before + block + eol + blank + rest, changed: true };
|
|
85
100
|
}
|
|
86
101
|
|
|
87
102
|
// Overwrite is exempt on a pinned block — the hand-curated overload wins.
|
|
@@ -111,7 +126,7 @@ export const applyStamp = (
|
|
|
111
126
|
// @partOf is sorted so a merged block matches a freshly-stamped one (stampFor sorts).
|
|
112
127
|
merged.partOf = [...(merged.partOf ?? [])].sort();
|
|
113
128
|
|
|
114
|
-
const block = renderWithEol(merged, eol);
|
|
129
|
+
const block = renderWithEol(merged, style, eol);
|
|
115
130
|
if (block === located.text) return { content: source, changed: false };
|
|
116
131
|
return {
|
|
117
132
|
content: source.slice(0, located.start) + block + source.slice(located.end),
|