@inixiative/atlas 0.4.0 → 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.
@@ -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, an optional `?` tentative
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 BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
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 OPENS_ATLAS = /(^|\n)\s*\*?\s*@atlas\b/;
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
- // Locate the first block comment that opens with `@atlas`, returning its text
37
- // and character span so the patcher can splice a regenerated block in place.
38
- export const locateAtlasBlock = (
39
- source: string,
40
- ): { start: number; end: number; text: string } | null => {
41
- BLOCK_COMMENT.lastIndex = 0;
42
- for (let m = BLOCK_COMMENT.exec(source); m !== null; m = BLOCK_COMMENT.exec(source)) {
43
- if (OPENS_ATLAS.test(m[0])) {
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
- // Parse the first block comment that opens with `@atlas`. Returns null if the
51
- // file carries no atlas block. Parsing is scoped to that block, so a stray
52
- // `@uses` in code or prose elsewhere never false-matches.
53
- export const parseAtlasBlock = (source: string): AtlasAnnotation | null => {
54
- const located = locateAtlasBlock(source);
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
- // split on \r?\n so CRLF files don't leave a trailing \r polluting values.
68
- for (const line of atlasBlock.split(/\r?\n/)) {
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;
@@ -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 line = (axis: string, values: string[]): string => ` * @${axis} ${values.join(', ')}`;
28
-
29
- // Render a canonical `@atlas` block. Axis order is fixed for diff-stability.
30
- export const renderBlock = (spec: BlockSpec): string => {
31
- const lines = ['/**', spec.pinned ? ' * @atlas pin' : ' * @atlas'];
32
- if (spec.kind?.length) lines.push(line('kind', spec.kind));
33
- if (spec.partOf?.length) lines.push(line('partOf', spec.partOf));
34
- if (spec.usesState === 'none') lines.push(' * @uses none');
35
- else if (spec.usesState === 'proposed' && spec.uses?.length) lines.push(line('uses?', spec.uses));
36
- else if (spec.usesState === 'values' && spec.uses?.length) lines.push(line('uses', spec.uses));
37
- if (spec.constructs?.length) lines.push(line('constructs', spec.constructs));
38
- lines.push(' */');
39
- return lines.join('\n');
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 existing = parseAtlasBlock(source);
66
- const located = locateAtlasBlock(source);
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
- // but below a shebang so an executable file keeps working.
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
- const block = renderWithEol(spec, eol);
80
- const shebang = SHEBANG.exec(source)?.[0];
81
- const content = shebang
82
- ? shebang + block + eol + source.slice(shebang.length)
83
- : block + eol + source;
84
- return { content, changed: true };
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),
@@ -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
+ };