@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.
@@ -0,0 +1,260 @@
1
+ // How each language writes the comment an @atlas block lives in. Languages are grouped by
2
+ // comment style; one table maps a file to its style, and the parser, the stamper, the walker
3
+ // and the hooks all read it. A file with no style here (.json, .txt, images) can't carry a
4
+ // block: the stamp rules tag it by its path instead.
5
+
6
+ // How a fresh block is placed, for the languages that need more than the style says:
7
+ // blankAfter — a blank line follows the block (reST ends a comment only at a blank line; in Go
8
+ // a comment touching `package` becomes the package doc)
9
+ // placeAfter — a block can only go below this opening (a PHP file that starts as HTML would
10
+ // print a `/* */` block to the page, so it gets none)
11
+ type Placement = { blankAfter?: boolean; placeAfter?: RegExp };
12
+
13
+ // `block` styles wrap the axis lines in an opener and a closer; `line` styles prefix each one.
14
+ export type CommentStyle = Placement &
15
+ (
16
+ | {
17
+ shape: 'block';
18
+ // how a block opens and closes when reading (`/*` also finds `/**`) and when writing
19
+ open: string;
20
+ close: string;
21
+ writeOpen: string;
22
+ writeClose: string;
23
+ // written before each axis line (` * `); AXIS_LINE reads past a leading `*`
24
+ line: string;
25
+ }
26
+ // writePrefix: the form written when it differs from the shortest one read (`;;` in Lisp)
27
+ | { shape: 'line'; prefix: string; writePrefix?: string }
28
+ );
29
+
30
+ // Plain `/* */` is written for the C family because no language gives it a meaning, while `/**`
31
+ // is a doc comment in Rust (an error before `//!`), C#, Dart, Java and Go. JS/TS keep `/**`, the
32
+ // established convention (see LANGUAGE_RULES).
33
+ export const COMMENT_STYLES = {
34
+ c: { shape: 'block', open: '/*', close: '*/', writeOpen: '/*', writeClose: ' */', line: ' * ' },
35
+ html: {
36
+ shape: 'block',
37
+ open: '<!--',
38
+ close: '-->',
39
+ writeOpen: '<!--',
40
+ writeClose: '-->',
41
+ line: '',
42
+ },
43
+ // MDX 2+ rejects `<!-- -->`; its comment is a JS expression
44
+ mdx: { shape: 'block', open: '{/*', close: '*/}', writeOpen: '{/*', writeClose: '*/}', line: '' },
45
+ hash: { shape: 'line', prefix: '#' },
46
+ slash: { shape: 'line', prefix: '//' },
47
+ dash: { shape: 'line', prefix: '--' },
48
+ semicolon: { shape: 'line', prefix: ';', writePrefix: ';;' },
49
+ dotdot: { shape: 'line', prefix: '..', blankAfter: true },
50
+ } as const satisfies Record<string, CommentStyle>;
51
+
52
+ export type CommentStyleName = keyof typeof COMMENT_STYLES;
53
+
54
+ // Which files use each style. An entry starting with `.` is an extension (or a dotfile's whole
55
+ // name); anything else is an exact file name. Matching ignores case. Extend it from
56
+ // `.atlas/config.ts` with `comments: { hash: ['.nix'] }`.
57
+ export type CommentTable = Partial<Record<CommentStyleName, string[]>>;
58
+
59
+ export const COMMENT_TABLE: Required<CommentTable> = {
60
+ c: [
61
+ '.ts',
62
+ '.tsx',
63
+ '.mts',
64
+ '.cts',
65
+ '.js',
66
+ '.jsx',
67
+ '.mjs',
68
+ '.cjs',
69
+ '.go',
70
+ '.java',
71
+ '.kt',
72
+ '.kts',
73
+ '.rs',
74
+ '.c',
75
+ '.h',
76
+ '.cc',
77
+ '.cpp',
78
+ '.hpp',
79
+ '.cs',
80
+ '.swift',
81
+ '.scala',
82
+ '.dart',
83
+ '.groovy',
84
+ '.proto',
85
+ '.css',
86
+ '.scss',
87
+ '.less',
88
+ '.php',
89
+ ],
90
+ html: ['.md', '.markdown', '.html', '.htm', '.xml', '.vue', '.svelte'],
91
+ mdx: ['.mdx'],
92
+ hash: [
93
+ '.py',
94
+ '.pyi',
95
+ '.rb',
96
+ '.sh',
97
+ '.bash',
98
+ '.zsh',
99
+ '.fish',
100
+ '.yaml',
101
+ '.yml',
102
+ '.toml',
103
+ '.ex',
104
+ '.exs',
105
+ '.r',
106
+ '.pl',
107
+ '.pm',
108
+ '.tf',
109
+ '.nix',
110
+ '.cmake',
111
+ '.ps1',
112
+ '.dockerfile',
113
+ 'Dockerfile',
114
+ 'Containerfile',
115
+ 'Makefile',
116
+ 'GNUmakefile',
117
+ 'Gemfile',
118
+ 'Rakefile',
119
+ 'Justfile',
120
+ 'Procfile',
121
+ ],
122
+ slash: ['.zig'],
123
+ dash: ['.sql', '.lua', '.hs', '.elm'],
124
+ semicolon: ['.clj', '.cljs', '.cljc', '.edn', '.lisp', '.el', '.scm', '.rkt'],
125
+ dotdot: ['.rst'],
126
+ };
127
+
128
+ // Per table entry, where a language needs more than its style.
129
+ const JS_DOC = { writeOpen: '/**' } as const;
130
+ const LANGUAGE_RULES: Record<string, Placement & { writeOpen?: string }> = {
131
+ '.ts': JS_DOC,
132
+ '.tsx': JS_DOC,
133
+ '.mts': JS_DOC,
134
+ '.cts': JS_DOC,
135
+ '.js': JS_DOC,
136
+ '.jsx': JS_DOC,
137
+ '.mjs': JS_DOC,
138
+ '.cjs': JS_DOC,
139
+ '.go': { blankAfter: true },
140
+ '.php': { placeAfter: /^<\?php\b/m },
141
+ };
142
+
143
+ // The table a repo runs with: atlas's, plus whatever `.atlas/config.ts` adds. An entry the repo
144
+ // lists under another style moves there (in any case, as matching ignores case).
145
+ export const mergeCommentTable = (extra: CommentTable = {}): Required<CommentTable> => {
146
+ const moved = new Set(
147
+ Object.values(extra)
148
+ .flat()
149
+ .map((entry) => entry.toLowerCase()),
150
+ );
151
+ const merged = {} as Required<CommentTable>;
152
+ for (const name of Object.keys(COMMENT_TABLE) as CommentStyleName[]) {
153
+ merged[name] = [
154
+ ...COMMENT_TABLE[name].filter((entry) => !moved.has(entry.toLowerCase())),
155
+ ...(extra[name] ?? []),
156
+ ];
157
+ }
158
+ return merged;
159
+ };
160
+
161
+ const basename = (path: string): string => path.slice(path.lastIndexOf('/') + 1);
162
+
163
+ // The table entry a file matches (its style, and the `.ext` or name that decided it), or null
164
+ // when the file can't hold a comment. An exact file name wins, then the longest extension (so a
165
+ // later `.blade.php` entry can beat `.php`).
166
+ export const entryFor = (
167
+ path: string,
168
+ table: Required<CommentTable> = COMMENT_TABLE,
169
+ ): { style: CommentStyleName; entry: string } | null => {
170
+ const name = basename(path).toLowerCase();
171
+ let best: { style: CommentStyleName; entry: string } | null = null;
172
+ for (const style of Object.keys(table) as CommentStyleName[]) {
173
+ for (const entry of table[style]) {
174
+ const lower = entry.toLowerCase();
175
+ if (lower === name) return { style, entry };
176
+ if (lower.startsWith('.') && name.endsWith(lower)) {
177
+ if (!best || entry.length > best.entry.length) best = { style, entry };
178
+ }
179
+ }
180
+ }
181
+ return best;
182
+ };
183
+
184
+ export const styleNameFor = (
185
+ path: string,
186
+ table: Required<CommentTable> = COMMENT_TABLE,
187
+ ): CommentStyleName | null => entryFor(path, table)?.style ?? null;
188
+
189
+ // The style a file is written in, with its language's rules applied, or null when it can't hold
190
+ // a comment.
191
+ export const styleFor = (
192
+ path: string,
193
+ table: Required<CommentTable> = COMMENT_TABLE,
194
+ ): CommentStyle | null => {
195
+ const match = entryFor(path, table);
196
+ if (!match) return null;
197
+ const rules = LANGUAGE_RULES[match.entry.toLowerCase()];
198
+ const style: CommentStyle = COMMENT_STYLES[match.style];
199
+ return rules ? ({ ...style, ...rules } as CommentStyle) : style;
200
+ };
201
+
202
+ // Lines that must stay first in a file, so a fresh block goes below them. Each applies once, in
203
+ // this order, at the position the previous one left. A line may end the file with no newline.
204
+ type Preamble = { applies: (name: string) => boolean; pattern: RegExp };
205
+
206
+ const extensionOf = (name: string): string => {
207
+ const dot = name.lastIndexOf('.');
208
+ return dot > 0 ? name.slice(dot).toLowerCase() : '';
209
+ };
210
+ const anyFile = (): boolean => true;
211
+ const withExtension =
212
+ (...extensions: string[]) =>
213
+ (name: string): boolean =>
214
+ extensions.includes(extensionOf(name));
215
+ const isDockerfile = (name: string): boolean =>
216
+ /^(docker|container)file\b/i.test(name) || extensionOf(name) === '.dockerfile';
217
+
218
+ const PREAMBLES: Preamble[] = [
219
+ // `#!` but not Rust's `#![attribute]`
220
+ { applies: anyFile, pattern: /^#!(?!\[)[^\n]*(?:\n|$)/ },
221
+ // Emacs file variables (`-*- lexical-binding: t -*-`) only count on the first line. Only a
222
+ // line that is whole on its own: `/* -*- mode: c -*-` opening a longer comment is not skipped,
223
+ // or the block would land inside that comment.
224
+ {
225
+ applies: anyFile,
226
+ pattern: /^(?![^\n]*(?:\/\*|<!--)(?![^\n]*(?:\*\/|-->)))[^\n]*-\*-[^\n]*-\*-[^\n]*(?:\n|$)/,
227
+ },
228
+ // Python's and Ruby's encoding line must be the first or second line
229
+ {
230
+ applies: withExtension('.py', '.pyi', '.rb'),
231
+ pattern: /^#[^\n]*coding[:=][^\n]*(?:\n|$)/,
232
+ },
233
+ { applies: isDockerfile, pattern: /^(?:#[ \t]*[a-z]+=[^\n]*(?:\n|$))+/i },
234
+ // Go build constraints: `// +build` must be preceded only by blank lines and line comments
235
+ // (a copyright header), so a `/* */` block above it would switch it off. Everything up to the
236
+ // last constraint line stays first; a file without one matches nothing here.
237
+ {
238
+ applies: withExtension('.go'),
239
+ pattern:
240
+ /^(?:(?:[ \t]*(?:\/\/[^\n]*)?\r?\n)*?(?:\/\/(?:go:build|[ \t]*\+build)[^\n]*(?:\r?\n|$))+)+(?:[ \t]*\r?\n)?/,
241
+ },
242
+ {
243
+ applies: withExtension('.md', '.mdx', '.markdown'),
244
+ pattern: /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/,
245
+ },
246
+ { applies: anyFile, pattern: /^<\?xml[^\n]*\?>[ \t]*(?:\r?\n|$)/ },
247
+ { applies: withExtension('.php'), pattern: /^<\?php\b[^\n]*(?:\n|$)/ },
248
+ { applies: withExtension('.css', '.scss', '.less'), pattern: /^@charset[^\n]*(?:\n|$)/ },
249
+ ];
250
+
251
+ // Where a fresh block is inserted: the offset just past the file's preamble.
252
+ export const preambleEnd = (path: string, source: string): number => {
253
+ const name = basename(path);
254
+ let at = 0;
255
+ for (const { applies, pattern } of PREAMBLES) {
256
+ if (!applies(name)) continue;
257
+ at += pattern.exec(source.slice(at))?.[0].length ?? 0;
258
+ }
259
+ return at;
260
+ };