|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | + |
| 4 | +const REPO_PREFIX = |
| 5 | + 'https://github.com/datocms/structured-text/blob/main/packages/utils/'; |
| 6 | + |
| 7 | +const readmePath = path.join(process.cwd(), 'README.md'); |
| 8 | +let readme = fs.readFileSync(readmePath, 'utf-8'); |
| 9 | + |
| 10 | +// Matches: [`symbol`](https://.../file#L123) |
| 11 | +const linkRegex = new RegExp( |
| 12 | + '\\[`([^`]+)`\\]\\(' + REPO_PREFIX + '([^#)]+)#L\\d+\\)', |
| 13 | + 'g', |
| 14 | +); |
| 15 | + |
| 16 | +function findLineNumber(filePath, symbol) { |
| 17 | + const content = fs.readFileSync(filePath, 'utf-8').split('\n'); |
| 18 | + |
| 19 | + // Look for `function foo`, `class Foo`, or `const foo =` |
| 20 | + const regex = new RegExp( |
| 21 | + `\\b(?:function|class|const|let|var)\\s+${symbol}\\b`, |
| 22 | + ); |
| 23 | + |
| 24 | + for (let i = 0; i < content.length; i++) { |
| 25 | + if (regex.test(content[i])) { |
| 26 | + return i + 1; // GitHub is 1-indexed |
| 27 | + } |
| 28 | + } |
| 29 | + return null; |
| 30 | +} |
| 31 | + |
| 32 | +readme = readme.replace(linkRegex, (full, symbol, file) => { |
| 33 | + const absPath = path.join(process.cwd(), file); |
| 34 | + if (!fs.existsSync(absPath)) { |
| 35 | + console.warn(`⚠️ File not found: ${file}`); |
| 36 | + return full; |
| 37 | + } |
| 38 | + |
| 39 | + const newLine = findLineNumber(absPath, symbol); |
| 40 | + if (!newLine) { |
| 41 | + console.warn(`⚠️ Could not locate ${symbol} in ${file}`); |
| 42 | + return full; |
| 43 | + } |
| 44 | + |
| 45 | + return `[\`${symbol}\`](${REPO_PREFIX}${file}#L${newLine})`; |
| 46 | +}); |
| 47 | + |
| 48 | +fs.writeFileSync(readmePath, readme); |
| 49 | +console.log('✅ README GitHub links updated!'); |
0 commit comments