|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +import fs from 'fs'; |
| 4 | +import { glob } from 'glob'; |
| 5 | + |
| 6 | +function getLine(txt, index) { |
| 7 | + |
| 8 | + let line = 1; |
| 9 | + |
| 10 | + for (let i = 0; i < index; i++) { |
| 11 | + if (txt[i] === '\n') { |
| 12 | + line += 1; |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + return line; |
| 17 | + |
| 18 | +} |
| 19 | + |
| 20 | +export function findBadLinebreaks(file, fix = false) { |
| 21 | + |
| 22 | + let contents = fs.readFileSync(file, 'utf8').toString(); |
| 23 | + |
| 24 | + const re = /(?<=[\w\d ])\n(?=[\w\d])/g; |
| 25 | + const matches = Array.from(contents.matchAll(re)); |
| 26 | + |
| 27 | + for (const m of matches) { |
| 28 | + |
| 29 | + if (fix) { |
| 30 | + contents = `${contents.slice(0, m.index).trimEnd()} ${contents.slice(m.index + 1)}`; |
| 31 | + } else { |
| 32 | + |
| 33 | + const start = Math.max(0, m.index - 33); |
| 34 | + const end = Math.min(contents.length - 1, m.index + 33); |
| 35 | + |
| 36 | + console.log(`found erroneous linebreak at line ${getLine(contents, m.index)}:\n${contents.slice(start, end)}\n`); |
| 37 | + |
| 38 | + } |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + if (matches.length > 0) { |
| 43 | + |
| 44 | + if (fix) { |
| 45 | + fs.writeFileSync(file, contents); |
| 46 | + console.log(`fixed ${matches.length} erroneous linebreaks`); |
| 47 | + } else { |
| 48 | + process.exitCode = 1; |
| 49 | + } |
| 50 | + |
| 51 | + } |
| 52 | + |
| 53 | +} |
| 54 | + |
| 55 | +// patterns match what is in package.json mdlint scripts |
| 56 | +const files = await glob( |
| 57 | + '**/*.md', |
| 58 | + { |
| 59 | + ignore: [ |
| 60 | + 'node_modules/**', |
| 61 | + 'meetings/201*/*.md', |
| 62 | + 'meetings/202[0-2]*/*.md', |
| 63 | + 'meetings/2023-0[1-3]/*.md', |
| 64 | + ] |
| 65 | + } |
| 66 | +); |
| 67 | + |
| 68 | +const fix = process.argv?.[2] === 'fix'; |
| 69 | + |
| 70 | +for (const f of files) { |
| 71 | + findBadLinebreaks(f, fix); |
| 72 | +} |
0 commit comments