@nera-static/stan 1.0.1 → 1.1.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/CHANGELOG.md +16 -0
- package/README.md +147 -15
- package/canonical/editorconfig +12 -0
- package/canonical/github/FUNDING.yml +13 -0
- package/canonical/github/dependabot.yml +20 -0
- package/canonical/github/workflows/publish.yml +64 -0
- package/canonical/github/workflows/test.yml +37 -0
- package/canonical/husky/pre-push +1 -0
- package/canonical/variants/chokidar-major/github/dependabot.yml +25 -0
- package/canonical/variants/desktop-release/github/workflows/publish.yml +104 -0
- package/canonical/variants/dist-check/github/workflows/test.yml +43 -0
- package/canonical/variants/image-cache/github/workflows/publish.yml +73 -0
- package/canonical/variants/image-cache/github/workflows/test.yml +46 -0
- package/canonical/variants/validate-templates/github/workflows/publish.yml +64 -0
- package/canonical/variants/validate-templates/github/workflows/test.yml +40 -0
- package/canonical/variants/windows-smoke/github/workflows/test.yml +57 -0
- package/canonical/vitest.config.js +3 -0
- package/package.json +24 -12
- package/src/bem.js +35 -0
- package/src/checks/canonical.js +368 -0
- package/src/checks/css.js +131 -0
- package/src/checks/docs.js +405 -0
- package/src/checks/package.js +352 -0
- package/src/checks/pug.js +369 -0
- package/src/checks/tree.js +544 -0
- package/src/cli.js +49 -39
- package/src/eslint/check.js +64 -0
- package/src/eslint/config.js +45 -28
- package/src/eslint/files.js +37 -0
- package/src/markdown.js +60 -0
- package/src/repo-files.js +62 -1
- package/src/settings.js +136 -0
- package/src/stylelint/config.js +122 -0
- package/src/stylelint/index.js +15 -0
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
|
|
5
|
+
import { escapeRegExp } from '@nera-static/plugin-utils/html'
|
|
6
|
+
import { isPlainObject } from '@nera-static/plugin-utils/values'
|
|
7
|
+
import * as espree from 'espree'
|
|
8
|
+
|
|
9
|
+
import { listFiles } from '../eslint/files.js'
|
|
10
|
+
import { kindOf } from '../kind.js'
|
|
11
|
+
import { OUTSIDE_REPO, repoFile, writeInside } from '../repo-files.js'
|
|
12
|
+
import { CONFIG_KEY, VARIANTS } from '../settings.js'
|
|
13
|
+
import { KEY_ORDER, STRUCTURE_PREFIX, keyLines, serialize } from './package.js'
|
|
14
|
+
|
|
15
|
+
/** The rule ids the canonical check reports. */
|
|
16
|
+
export const CANONICAL_RULES = Object.freeze({
|
|
17
|
+
canonicalFile: `${STRUCTURE_PREFIX}canonical-file`,
|
|
18
|
+
testScripts: `${STRUCTURE_PREFIX}test-scripts`,
|
|
19
|
+
testLayout: `${STRUCTURE_PREFIX}test-layout`,
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
/** The folder of the canonical copies inside this package (D8). */
|
|
23
|
+
export const CANONICAL_DIR = fileURLToPath(new URL('../../canonical/', import.meta.url))
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The canonical files every repo carries: `file` its path in the repo, `source` its copy under
|
|
27
|
+
* `canonical/` (without leading dots, so npm ships it). A site carries only the files marked
|
|
28
|
+
* `site`; `publish.yml` belongs to a published package (no `"private": true`) only. The copies
|
|
29
|
+
* are the fleet majority of 4-tooling-themes §1.4 and the target files of the repo templates
|
|
30
|
+
* (`generator/scripts/templates/common/`).
|
|
31
|
+
*/
|
|
32
|
+
export const CANONICAL_FILES = Object.freeze([
|
|
33
|
+
{ file: '.editorconfig', source: 'editorconfig', site: true },
|
|
34
|
+
{ file: 'vitest.config.js', source: 'vitest.config.js' },
|
|
35
|
+
{ file: '.husky/pre-push', source: 'husky/pre-push' },
|
|
36
|
+
{ file: '.github/workflows/test.yml', source: 'github/workflows/test.yml' },
|
|
37
|
+
{ file: '.github/workflows/publish.yml', source: 'github/workflows/publish.yml', published: true },
|
|
38
|
+
{ file: '.github/dependabot.yml', source: 'github/dependabot.yml', site: true },
|
|
39
|
+
{ file: '.github/FUNDING.yml', source: 'github/FUNDING.yml', site: true },
|
|
40
|
+
].map(Object.freeze))
|
|
41
|
+
|
|
42
|
+
/** The scripts every repo with tests has (3-tests §4.3). */
|
|
43
|
+
export const TEST_SCRIPTS = Object.freeze({ 'test': 'vitest run', 'test:watch': 'vitest' })
|
|
44
|
+
|
|
45
|
+
/** In a variant copy, a part of a line that may hold anything, e.g. a cache `path:`. */
|
|
46
|
+
export const WILDCARD = '{{any}}'
|
|
47
|
+
|
|
48
|
+
/** The module the vitest preset comes from, and its export (3-tests §4.2). */
|
|
49
|
+
const PRESET_MODULE = '@nera-static/test-utils/vitest'
|
|
50
|
+
const PRESET = 'neraConfig'
|
|
51
|
+
/** The package that ships the preset; its own config imports the preset from its source. */
|
|
52
|
+
const TEST_UTILS = '@nera-static/test-utils'
|
|
53
|
+
const VITEST_CONFIG = 'vitest.config.js'
|
|
54
|
+
const PACKAGE = 'package.json'
|
|
55
|
+
const INSTALLED = 'node_modules/@nera-static/stan/canonical'
|
|
56
|
+
const COMMENT_LINE = /^\s*#/
|
|
57
|
+
/** A `test`/`test:watch` value that only runs vitest, so `--fix` may replace it. */
|
|
58
|
+
const PLAIN_VITEST = /^vitest(?: (?:run|--run|watch|--watch))?$/
|
|
59
|
+
/** Every file that looks like a test, wherever it is. */
|
|
60
|
+
const TEST_LIKE = '**/*.{test,spec}.{js,mjs,cjs}'
|
|
61
|
+
const TEST_NAME = /^(?<name>.+?)(?:\.(?<infix>unit|integration|template))?\.(?<kind>test|spec)\.(?<ext>[cm]?js)$/
|
|
62
|
+
const TEST_DIR = 'test/'
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The canonical check: the canonical files against the copies in `canonical/` (or the variant a
|
|
66
|
+
* repo names under `nera-stan.variants`), compared without full-line `#` comments (D8);
|
|
67
|
+
* `vitest.config.js` against the test-utils preset; the `test`/`test:watch` scripts; and the
|
|
68
|
+
* test layout. `--fix` (D7) writes a missing or differing canonical file, a missing
|
|
69
|
+
* `vitest.config.js` and the test scripts when they only ran vitest; it writes inside the repo
|
|
70
|
+
* only. A variant with an open part (`{{any}}`) and a `vitest.config.js` with its own options
|
|
71
|
+
* are fixed by hand. A site gets only the files marked `site`.
|
|
72
|
+
*/
|
|
73
|
+
export const canonicalCheck = Object.freeze({
|
|
74
|
+
name: 'canonical',
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Every rule id this check can report.
|
|
78
|
+
*
|
|
79
|
+
* @returns {string[]}
|
|
80
|
+
*/
|
|
81
|
+
rules() {
|
|
82
|
+
return Object.values(CANONICAL_RULES)
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Check the repo's canonical files, test scripts and test layout.
|
|
87
|
+
*
|
|
88
|
+
* A rule under `nera-stan.skip` neither reports nor fixes.
|
|
89
|
+
*
|
|
90
|
+
* @param {{ root: string, pkg: object, settings: object, fix: boolean }} context
|
|
91
|
+
* @returns {Promise<{ findings: { file: string, line: number, rule: string, message: string,
|
|
92
|
+
* fixable: boolean }[] }>}
|
|
93
|
+
*/
|
|
94
|
+
async run(context) {
|
|
95
|
+
const { root, pkg, settings } = context
|
|
96
|
+
const fix = context.fix === true
|
|
97
|
+
const active = (rule) => !Object.hasOwn(settings.skip, rule)
|
|
98
|
+
const site = kindOf(pkg) === 'site'
|
|
99
|
+
const files = CANONICAL_FILES
|
|
100
|
+
.filter((entry) => !site || entry.site)
|
|
101
|
+
.filter((entry) => !entry.published || pkg.private !== true)
|
|
102
|
+
const fixFiles = fix && active(CANONICAL_RULES.canonicalFile)
|
|
103
|
+
|
|
104
|
+
const findings = files.flatMap((entry) => (entry.file === VITEST_CONFIG
|
|
105
|
+
? vitestConfig(root, pkg, fixFiles)
|
|
106
|
+
: canonicalFile(root, entry, settings.variants[entry.file], fixFiles)))
|
|
107
|
+
if (!site) {
|
|
108
|
+
findings.push(...testScripts(root, fix && active(CANONICAL_RULES.testScripts)))
|
|
109
|
+
findings.push(...await testLayout(context))
|
|
110
|
+
}
|
|
111
|
+
return { findings }
|
|
112
|
+
},
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* `structure/canonical-file` for one file: present and, without full-line comments, equal to
|
|
117
|
+
* the canonical copy or the named variant line by line.
|
|
118
|
+
*/
|
|
119
|
+
function canonicalFile(root, { file, source }, variant, fix) {
|
|
120
|
+
const rule = CANONICAL_RULES.canonicalFile
|
|
121
|
+
const copy = variant ? `variants/${variant}/${source}` : source
|
|
122
|
+
const canonical = readFileSync(path.join(CANONICAL_DIR, copy), 'utf8')
|
|
123
|
+
const open = canonical.includes(WILDCARD)
|
|
124
|
+
const what = variant ? `the "${variant}" variant of nera-stan's canonical ${file}` : `nera-stan's canonical ${file}`
|
|
125
|
+
const byHand = `write it as ${INSTALLED}/${copy} shows, filling in the parts marked ${WILDCARD}`
|
|
126
|
+
const actual = readText(root, file)
|
|
127
|
+
|
|
128
|
+
const tried = fix && !open
|
|
129
|
+
if (actual === null) {
|
|
130
|
+
if (tried && writeInside(root, file, canonical)) {
|
|
131
|
+
return []
|
|
132
|
+
}
|
|
133
|
+
const todo = open ? byHand : fixHint(tried, 'run nera-stan --fix to write it')
|
|
134
|
+
return [{ file, line: 1, rule, fixable: !open, message: `"${file}" is missing: ${todo}` }]
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const difference = firstDifference(contentLines(canonical), contentLines(actual))
|
|
138
|
+
if (difference === null) {
|
|
139
|
+
return []
|
|
140
|
+
}
|
|
141
|
+
if (tried && writeInside(root, file, canonical)) {
|
|
142
|
+
return []
|
|
143
|
+
}
|
|
144
|
+
const { line, expected, found } = difference
|
|
145
|
+
const others = (VARIANTS[file] ?? []).filter((name) => name !== variant)
|
|
146
|
+
const alternative = others.length > 0
|
|
147
|
+
? `, or name one of its variants (${others.map((name) => `"${name}"`).join(', ')}) under "${CONFIG_KEY}.variants"`
|
|
148
|
+
: ''
|
|
149
|
+
const todo = open ? byHand : fixHint(tried, `run nera-stan --fix to write ${what}${alternative}`)
|
|
150
|
+
return [{
|
|
151
|
+
file,
|
|
152
|
+
line: line ?? lineCount(actual),
|
|
153
|
+
rule,
|
|
154
|
+
fixable: !open,
|
|
155
|
+
message: `the file differs from ${what}: expected ${quoted(expected)}, found ${quoted(found)}; ${todo}`,
|
|
156
|
+
}]
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The lines that count: without full-line `#` comments and trailing blank lines (D8). */
|
|
160
|
+
function contentLines(text) {
|
|
161
|
+
const lines = text.split(/\r?\n/)
|
|
162
|
+
.map((content, index) => ({ content, line: index + 1 }))
|
|
163
|
+
.filter(({ content }) => !COMMENT_LINE.test(content))
|
|
164
|
+
while (lines.length > 0 && lines.at(-1).content.trim() === '') {
|
|
165
|
+
lines.pop()
|
|
166
|
+
}
|
|
167
|
+
return lines
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The first line where `actual` leaves `expected`, `null` when they match. */
|
|
171
|
+
function firstDifference(expected, actual) {
|
|
172
|
+
const length = Math.max(expected.length, actual.length)
|
|
173
|
+
for (let index = 0; index < length; index++) {
|
|
174
|
+
const want = expected[index]
|
|
175
|
+
const have = actual[index]
|
|
176
|
+
if (!want || !have || !lineMatches(want.content, have.content)) {
|
|
177
|
+
return { line: have?.line, expected: want?.content, found: have?.content }
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return null
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** A canonical line matches itself, or, with a `{{any}}`, any text in its place. */
|
|
184
|
+
function lineMatches(expected, actual) {
|
|
185
|
+
if (!expected.includes(WILDCARD)) {
|
|
186
|
+
return expected === actual
|
|
187
|
+
}
|
|
188
|
+
const source = expected.split(WILDCARD).map(escapeRegExp).join('.*')
|
|
189
|
+
return new RegExp(`^${source}$`).test(actual)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* `structure/canonical-file` for `vitest.config.js`: it builds the config with the test-utils
|
|
194
|
+
* preset, `export default neraConfig()` with at most one object of the repo's own options.
|
|
195
|
+
*/
|
|
196
|
+
function vitestConfig(root, pkg, fix) {
|
|
197
|
+
const rule = CANONICAL_RULES.canonicalFile
|
|
198
|
+
const file = VITEST_CONFIG
|
|
199
|
+
const source = readText(root, file)
|
|
200
|
+
if (source === null) {
|
|
201
|
+
if (fix && writeInside(root, file, readFileSync(path.join(CANONICAL_DIR, file), 'utf8'))) {
|
|
202
|
+
return []
|
|
203
|
+
}
|
|
204
|
+
const todo = fixHint(fix, 'run nera-stan --fix to write the preset config')
|
|
205
|
+
return [{ file, line: 1, rule, fixable: true, message: `"${file}" is missing: ${todo} ` +
|
|
206
|
+
'(and add @nera-static/test-utils to devDependencies)' }]
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const preset = `"import { ${PRESET} } from '${PRESET_MODULE}'" and "export default ${PRESET}()"`
|
|
210
|
+
let ast
|
|
211
|
+
try {
|
|
212
|
+
ast = espree.parse(source, { ecmaVersion: 'latest', sourceType: 'module', loc: true })
|
|
213
|
+
} catch (error) {
|
|
214
|
+
return [{ file, line: error.lineNumber ?? 1, rule, fixable: false, message: 'the file cannot be parsed ' +
|
|
215
|
+
`(${error.message}): fix it, then build the config with ${preset}` }]
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const modules = presetModules(pkg)
|
|
219
|
+
const local = ast.body
|
|
220
|
+
.filter((node) => node.type === 'ImportDeclaration' && modules.includes(moduleId(node.source.value)))
|
|
221
|
+
.flatMap((node) => node.specifiers)
|
|
222
|
+
.find((specifier) => specifier.type === 'ImportSpecifier' && specifier.imported.name === PRESET)?.local.name
|
|
223
|
+
const exported = ast.body.find((node) => node.type === 'ExportDefaultDeclaration')
|
|
224
|
+
const call = exported?.declaration
|
|
225
|
+
const usesPreset = local !== undefined && call?.type === 'CallExpression' &&
|
|
226
|
+
call.callee.type === 'Identifier' && call.callee.name === local &&
|
|
227
|
+
call.arguments.length <= 1 && call.arguments.every((argument) => argument.type === 'ObjectExpression')
|
|
228
|
+
if (usesPreset) {
|
|
229
|
+
return []
|
|
230
|
+
}
|
|
231
|
+
return [{
|
|
232
|
+
file,
|
|
233
|
+
line: exported?.loc.start.line ?? 1,
|
|
234
|
+
rule,
|
|
235
|
+
fixable: false,
|
|
236
|
+
message: `the config does not use the test-utils preset: write ${preset}, passing only the options ` +
|
|
237
|
+
`the repo needs (each with a comment why) as one object, e.g. ${PRESET}({ testTimeout: 30000 })`,
|
|
238
|
+
}]
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* The modules a `vitest.config.js` may import the preset from: the test-utils subpath, and in
|
|
243
|
+
* test-utils itself the file its `./vitest` export names, since a package cannot install itself.
|
|
244
|
+
*/
|
|
245
|
+
function presetModules(pkg) {
|
|
246
|
+
const own = pkg.name === TEST_UTILS && isPlainObject(pkg.exports) && typeof pkg.exports['./vitest'] === 'string'
|
|
247
|
+
? [moduleId(pkg.exports['./vitest'])]
|
|
248
|
+
: []
|
|
249
|
+
return [PRESET_MODULE, ...own]
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** A module specifier with a relative path written one way: `./src/x.js` and `./src/../src/x.js` alike. */
|
|
253
|
+
function moduleId(specifier) {
|
|
254
|
+
return specifier.startsWith('.') ? `./${path.posix.normalize(specifier)}` : specifier
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* `structure/test-scripts`: `test` is `vitest run` and `test:watch` is `vitest`. `--fix` sets
|
|
259
|
+
* a missing script and one that only ran vitest; any other value is the repo's to change.
|
|
260
|
+
*/
|
|
261
|
+
function testScripts(root, fix) {
|
|
262
|
+
const rule = CANONICAL_RULES.testScripts
|
|
263
|
+
const file = path.join(root, PACKAGE)
|
|
264
|
+
const text = readFileSync(file, 'utf8')
|
|
265
|
+
const pkg = JSON.parse(text)
|
|
266
|
+
const scripts = isPlainObject(pkg.scripts) ? pkg.scripts : {}
|
|
267
|
+
const wrong = Object.entries(TEST_SCRIPTS).filter(([name, value]) => scripts[name] !== value)
|
|
268
|
+
const fixable = (name) => scripts[name] === undefined || PLAIN_VITEST.test(scripts[name])
|
|
269
|
+
|
|
270
|
+
const tried = fix && wrong.some(([name]) => fixable(name))
|
|
271
|
+
if (tried) {
|
|
272
|
+
const fixed = { ...scripts }
|
|
273
|
+
for (const [name, value] of wrong.filter(([script]) => fixable(script))) {
|
|
274
|
+
fixed[name] = value
|
|
275
|
+
}
|
|
276
|
+
if (writeInside(root, PACKAGE, serialize(withScripts(pkg, orderScripts(fixed)), text))) {
|
|
277
|
+
return testScripts(root, false)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const lineOf = keyLines(text)
|
|
282
|
+
return wrong.map(([name, value]) => {
|
|
283
|
+
const found = scripts[name] === undefined ? 'is missing' : `is ${JSON.stringify(scripts[name])}`
|
|
284
|
+
const todo = fixable(name) ? fixHint(tried, 'run nera-stan --fix') : `set it to ${JSON.stringify(value)}`
|
|
285
|
+
return {
|
|
286
|
+
file: PACKAGE,
|
|
287
|
+
line: lineOf('scripts', name),
|
|
288
|
+
rule,
|
|
289
|
+
fixable: fixable(name),
|
|
290
|
+
message: `the script "${name}" ${found}, but must be ${JSON.stringify(value)} ` +
|
|
291
|
+
`(npm test runs the tests once, npm run test:watch watches): ${todo}`,
|
|
292
|
+
}
|
|
293
|
+
})
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The scripts with `test:watch` right after `test`, everything else in place. */
|
|
297
|
+
function orderScripts(scripts) {
|
|
298
|
+
const entries = Object.entries(scripts).filter(([name]) => name !== 'test:watch')
|
|
299
|
+
const at = entries.findIndex(([name]) => name === 'test') + 1
|
|
300
|
+
entries.splice(at, 0, ['test:watch', scripts['test:watch']])
|
|
301
|
+
return Object.fromEntries(entries)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** The manifest with `scripts` replaced, or inserted at its place in `KEY_ORDER`. */
|
|
305
|
+
function withScripts(pkg, scripts) {
|
|
306
|
+
if (Object.hasOwn(pkg, 'scripts')) {
|
|
307
|
+
return { ...pkg, scripts }
|
|
308
|
+
}
|
|
309
|
+
const later = KEY_ORDER.slice(KEY_ORDER.indexOf('scripts') + 1)
|
|
310
|
+
const entries = Object.entries(pkg)
|
|
311
|
+
const at = entries.findIndex(([key]) => later.includes(key))
|
|
312
|
+
entries.splice(at === -1 ? entries.length : at, 0, ['scripts', scripts])
|
|
313
|
+
return Object.fromEntries(entries)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* `structure/test-layout` (3-tests §4.1): every test lives under `test/` and is named
|
|
318
|
+
* `<module>.test.js`, without a `.unit.`/`.integration.`/`.template.` infix and not `.spec.`.
|
|
319
|
+
* Nothing is fixed: moving a test changes its relative imports.
|
|
320
|
+
*/
|
|
321
|
+
async function testLayout(context) {
|
|
322
|
+
const rule = CANONICAL_RULES.testLayout
|
|
323
|
+
const files = (await listFiles(context, TEST_LIKE)).map((file) => repoFile(context.root, file))
|
|
324
|
+
return files.flatMap((file) => {
|
|
325
|
+
const { name, infix, kind, ext } = TEST_NAME.exec(path.posix.basename(file)).groups
|
|
326
|
+
const reasons = [
|
|
327
|
+
...(file.startsWith(TEST_DIR) ? [] : ['it lies outside test/']),
|
|
328
|
+
...(infix ? [`its name carries the infix ".${infix}."`] : []),
|
|
329
|
+
...(kind === 'spec' ? ['it is named .spec. instead of .test.'] : []),
|
|
330
|
+
...(ext === 'js' ? [] : [`it ends in .${ext} instead of .js`]),
|
|
331
|
+
]
|
|
332
|
+
if (reasons.length === 0) {
|
|
333
|
+
return []
|
|
334
|
+
}
|
|
335
|
+
const folder = file.startsWith(TEST_DIR) ? path.posix.dirname(file) : 'test'
|
|
336
|
+
const target = `${folder}/${name}.test.js`
|
|
337
|
+
const hint = infix === 'integration' ? ' (the end-to-end test through core or the CLI is test/integration.test.js)' : ''
|
|
338
|
+
return [{
|
|
339
|
+
file,
|
|
340
|
+
line: 1,
|
|
341
|
+
rule,
|
|
342
|
+
fixable: false,
|
|
343
|
+
message: `the test is not where or how a Nera test is named, since ${reasons.join(' and ')}: ` +
|
|
344
|
+
`rename it to "${target}"${hint} and fix its relative imports`,
|
|
345
|
+
}]
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** What to do about a fixable finding; after `--fix` refused to write it, that is by hand. */
|
|
350
|
+
function fixHint(tried, hint) {
|
|
351
|
+
return tried ? OUTSIDE_REPO : hint
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function readText(root, file) {
|
|
355
|
+
const target = path.join(root, file)
|
|
356
|
+
return existsSync(target) ? readFileSync(target, 'utf8') : null
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function lineCount(text) {
|
|
360
|
+
return Math.max(1, text.replace(/\r?\n$/, '').split(/\r?\n/).length)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function quoted(line) {
|
|
364
|
+
if (line === undefined) {
|
|
365
|
+
return 'the end of the file'
|
|
366
|
+
}
|
|
367
|
+
return line.trim() === '' ? 'an empty line' : JSON.stringify(line)
|
|
368
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
|
|
4
|
+
import stylelint from 'stylelint'
|
|
5
|
+
|
|
6
|
+
import { ALWAYS_IGNORED } from '../eslint/config.js'
|
|
7
|
+
import { listFiles } from '../eslint/files.js'
|
|
8
|
+
import { repoFile } from '../repo-files.js'
|
|
9
|
+
import { CSS_PREFIX, OWN_IDS, createStylelintConfig } from '../stylelint/config.js'
|
|
10
|
+
|
|
11
|
+
/** The files the CSS check reads. */
|
|
12
|
+
const CSS_FILES = '**/*.css'
|
|
13
|
+
|
|
14
|
+
/** The report id of a file stylelint cannot parse. */
|
|
15
|
+
export const CSS_PARSE_ERROR = OWN_IDS.CssSyntaxError.id
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The CSS check: stylelint with the shipped config. A repo's own stylelint config and
|
|
19
|
+
* `.stylelintignore` are never read; `.gitignore`, `ALWAYS_IGNORED` and `nera-stan.ignores`
|
|
20
|
+
* apply. The files come from `listFiles`, as for every other check: stylelint's own glob
|
|
21
|
+
* walks into ignored folders and follows a symlink loop there until the path is too long.
|
|
22
|
+
* A file whose real path lies outside the repo (a symlink out of it) is neither reported
|
|
23
|
+
* nor fixed. Every rule id carries the `css/` prefix (D4).
|
|
24
|
+
*/
|
|
25
|
+
export const cssCheck = Object.freeze({
|
|
26
|
+
name: 'css',
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Every rule id this check can report for the repo.
|
|
30
|
+
*
|
|
31
|
+
* @param {{ root: string, pkg: object }} context
|
|
32
|
+
* @returns {Promise<string[]>}
|
|
33
|
+
*/
|
|
34
|
+
async rules({ root, pkg }) {
|
|
35
|
+
const config = await stylelint.resolveConfig(path.join(root, 'nera-stan.css'), {
|
|
36
|
+
config: createStylelintConfig({ pkg }),
|
|
37
|
+
cwd: root,
|
|
38
|
+
})
|
|
39
|
+
return [...Object.keys(config?.rules ?? {}), ...Object.keys(OWN_IDS)].map(reportId)
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Check the repo's CSS.
|
|
44
|
+
*
|
|
45
|
+
* @param {{ root: string, pkg: object, settings: object, fix: boolean }} context
|
|
46
|
+
* @returns {Promise<{ findings: { file: string, line: number, column: number, rule: string,
|
|
47
|
+
* message: string, fixable: boolean }[] }>}
|
|
48
|
+
*/
|
|
49
|
+
async run({ root, pkg, settings, fix }) {
|
|
50
|
+
const options = {
|
|
51
|
+
config: createStylelintConfig({ pkg, settings }),
|
|
52
|
+
cwd: root,
|
|
53
|
+
// Naming the repo's .gitignore keeps stylelint from reading a .stylelintignore.
|
|
54
|
+
ignorePath: path.join(root, '.gitignore'),
|
|
55
|
+
ignorePattern: [...ALWAYS_IGNORED, ...settings.ignores],
|
|
56
|
+
}
|
|
57
|
+
const findings = []
|
|
58
|
+
for (const source of await listFiles({ root, settings }, CSS_FILES)) {
|
|
59
|
+
const file = repoFile(root, source)
|
|
60
|
+
const fixed = await fixedSource(source, options)
|
|
61
|
+
if (fix && fixed.code !== fixed.original) {
|
|
62
|
+
writeFileSync(source, fixed.code)
|
|
63
|
+
}
|
|
64
|
+
const warnings = fix
|
|
65
|
+
? fixed.warnings
|
|
66
|
+
: markFixable(await checkedSource(fixed.original, source, options), fixed.warnings)
|
|
67
|
+
findings.push(...warnings.map((warning) => ({
|
|
68
|
+
file,
|
|
69
|
+
line: warning.line ?? 1,
|
|
70
|
+
column: warning.column ?? 1,
|
|
71
|
+
rule: reportId(warning.rule),
|
|
72
|
+
message: warning.text.endsWith(` (${warning.rule})`)
|
|
73
|
+
? warning.text.slice(0, -` (${warning.rule})`.length)
|
|
74
|
+
: warning.text,
|
|
75
|
+
fixable: warning.fixable === true,
|
|
76
|
+
})))
|
|
77
|
+
}
|
|
78
|
+
return { findings }
|
|
79
|
+
},
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
/** Lint a file's text as it is: the warnings. */
|
|
83
|
+
async function checkedSource(code, file, options) {
|
|
84
|
+
const { results: [result] } = await stylelint.lint({ ...options, code, codeFilename: file })
|
|
85
|
+
return result.warnings
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Lint a file's text with `fix` on, in memory: the fixed text and the warnings left after it.
|
|
90
|
+
* nera-stan writes the text itself, so stylelint never writes a file.
|
|
91
|
+
*/
|
|
92
|
+
async function fixedSource(file, options) {
|
|
93
|
+
const original = readFileSync(file, 'utf8')
|
|
94
|
+
const { results: [result], code } = await stylelint.lint({
|
|
95
|
+
...options,
|
|
96
|
+
code: original,
|
|
97
|
+
codeFilename: file,
|
|
98
|
+
fix: true,
|
|
99
|
+
})
|
|
100
|
+
return { original, code: code ?? original, warnings: result.warnings }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Mark as fixable as many warnings of each rule as `--fix` removes: the count before
|
|
105
|
+
* the fix minus the count after it. stylelint reports no per-warning fix when one fix
|
|
106
|
+
* changes a node another rule fixes too, so the counts are compared instead.
|
|
107
|
+
*/
|
|
108
|
+
function markFixable(before, after) {
|
|
109
|
+
const left = new Map()
|
|
110
|
+
for (const warning of after) {
|
|
111
|
+
left.set(warning.rule, (left.get(warning.rule) ?? 0) + 1)
|
|
112
|
+
}
|
|
113
|
+
const removed = new Map()
|
|
114
|
+
for (const warning of before) {
|
|
115
|
+
removed.set(warning.rule, (removed.get(warning.rule) ?? 0) + 1)
|
|
116
|
+
}
|
|
117
|
+
for (const [rule, count] of left) {
|
|
118
|
+
removed.set(rule, Math.max(0, (removed.get(rule) ?? 0) - count))
|
|
119
|
+
}
|
|
120
|
+
return before.map((warning) => {
|
|
121
|
+
const fixable = removed.get(warning.rule) > 0
|
|
122
|
+
if (fixable) {
|
|
123
|
+
removed.set(warning.rule, removed.get(warning.rule) - 1)
|
|
124
|
+
}
|
|
125
|
+
return { ...warning, fixable }
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function reportId(rule) {
|
|
130
|
+
return OWN_IDS[rule]?.id ?? `${CSS_PREFIX}${rule}`
|
|
131
|
+
}
|