|
| 1 | +// [start-readme] |
| 2 | +// |
| 3 | +// Print a list of all the YAML-powered table files in ./data/tables/ that |
| 4 | +// can't be found mentioned in any source file (content, data & code), along |
| 5 | +// with their paired schema files. Mirrors find-orphaned-assets.ts. |
| 6 | +// |
| 7 | +// Tables are referenced from Liquid like: |
| 8 | +// |
| 9 | +// {% data tables.<group>.<name> %} |
| 10 | +// {% for entry in tables.<group>.<name> %} |
| 11 | +// |
| 12 | +// so a table file `data/tables/<group>/<name>.yml` is "used" if the string |
| 13 | +// `tables.<group>.<name>` appears anywhere. A deeper reference such as |
| 14 | +// `tables.<group>.<name>.<subkey>` also counts, because the file key is a |
| 15 | +// prefix of it. |
| 16 | +// |
| 17 | +// [end-readme] |
| 18 | + |
| 19 | +import fs from 'fs' |
| 20 | +import path from 'path' |
| 21 | +import { pathToFileURL } from 'url' |
| 22 | +import { program } from 'commander' |
| 23 | +import walk from 'walk-sync' |
| 24 | + |
| 25 | +import walkFiles from '@/workflows/walk-files' |
| 26 | +import languages from '@/languages/lib/languages-server' |
| 27 | + |
| 28 | +const TABLES_DIR = 'data/tables' |
| 29 | +const SCHEMAS_DIR = 'src/data-directory/lib/data-schemas/tables' |
| 30 | + |
| 31 | +// Tables that are referenced dynamically (not via Liquid) and must never be |
| 32 | +// flagged as orphans. Add an entry here (the dotted key, e.g. `copilot.foo`) |
| 33 | +// if a table is loaded by code rather than mentioned in content. |
| 34 | +const EXCEPTIONS = new Set<string>([]) |
| 35 | + |
| 36 | +export type TableFile = { |
| 37 | + // Repo-relative path to the YAML file, e.g. data/tables/copilot/model-multipliers.yml |
| 38 | + yml: string |
| 39 | + // Repo-relative path to the paired schema, if it exists on disk. |
| 40 | + schema?: string |
| 41 | + // Dotted key used in Liquid, e.g. copilot.model-multipliers |
| 42 | + key: string |
| 43 | +} |
| 44 | + |
| 45 | +function getTableFiles(): TableFile[] { |
| 46 | + if (!fs.existsSync(TABLES_DIR)) return [] |
| 47 | + return walk(TABLES_DIR, { includeBasePath: true, directories: false }) |
| 48 | + .filter((filePath) => filePath.endsWith('.yml')) |
| 49 | + .map((ymlPath) => { |
| 50 | + const relative = path.relative(TABLES_DIR, ymlPath) |
| 51 | + const key = relative.slice(0, -'.yml'.length).split(path.sep).join('.') |
| 52 | + const schemaPath = path.join(SCHEMAS_DIR, relative.replace(/\.yml$/, '.ts')) |
| 53 | + return { |
| 54 | + yml: ymlPath, |
| 55 | + schema: fs.existsSync(schemaPath) ? schemaPath : undefined, |
| 56 | + key, |
| 57 | + } |
| 58 | + }) |
| 59 | +} |
| 60 | + |
| 61 | +program |
| 62 | + .description('Print all tables in ./data/tables/ not found in any source file') |
| 63 | + .option('-e, --exit', 'Exit script by count of orphans (useful for CI)') |
| 64 | + .option('-v, --verbose', 'Verbose outputs') |
| 65 | + .option('--json', 'Output in JSON format') |
| 66 | + .option('--exclude-translations', "Don't search in translations/") |
| 67 | + |
| 68 | +type MainOptions = { |
| 69 | + json: boolean |
| 70 | + verbose: boolean |
| 71 | + exit: boolean |
| 72 | + excludeTranslations: boolean |
| 73 | +} |
| 74 | + |
| 75 | +// Given the table files and the contents of every source file, return the |
| 76 | +// tables whose Liquid key is never mentioned. Pulled out of main() so it can |
| 77 | +// be unit tested without touching the filesystem. |
| 78 | +export function getOrphanedTables( |
| 79 | + tables: TableFile[], |
| 80 | + sourceContents: Iterable<string>, |
| 81 | +): TableFile[] { |
| 82 | + const orphans = new Map(tables.map((table) => [table.key, table])) |
| 83 | + for (const content of sourceContents) { |
| 84 | + if (orphans.size === 0) break |
| 85 | + for (const [key] of orphans) { |
| 86 | + if (EXCEPTIONS.has(key) || content.includes(`tables.${key}`)) { |
| 87 | + orphans.delete(key) |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + return [...orphans.values()].sort((a, b) => a.yml.localeCompare(b.yml)) |
| 92 | +} |
| 93 | + |
| 94 | +// Only parse argv and run when invoked directly (e.g. via `npm run |
| 95 | +// find-orphaned-tables`), not when imported by a test. |
| 96 | +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { |
| 97 | + program.parse(process.argv) |
| 98 | + main(program.opts()) |
| 99 | +} |
| 100 | + |
| 101 | +async function main(opts: MainOptions) { |
| 102 | + const { json, verbose, exit, excludeTranslations } = opts |
| 103 | + |
| 104 | + const englishFiles: string[] = [] |
| 105 | + englishFiles.push(...walkFiles(path.join(languages.en.dir, 'content'), ['.md'])) |
| 106 | + englishFiles.push(...walkFiles(path.join(languages.en.dir, 'data'), ['.md', '.yml'])) |
| 107 | + |
| 108 | + const sourceFiles: string[] = [...englishFiles] |
| 109 | + |
| 110 | + if (!excludeTranslations) { |
| 111 | + // Translations are often behind English. A table can still be referenced |
| 112 | + // in a translation even when no English content references it, so we must |
| 113 | + // search translations too. We only look at files that also exist in |
| 114 | + // English, because translations rarely delete renamed/removed files. |
| 115 | + const englishRelativeFiles = new Set( |
| 116 | + englishFiles.map((englishFile) => path.relative(languages.en.dir, englishFile)), |
| 117 | + ) |
| 118 | + for (const [language, { dir }] of Object.entries(languages)) { |
| 119 | + if (language === 'en') continue |
| 120 | + if (!fs.existsSync(dir)) { |
| 121 | + throw new Error( |
| 122 | + `${dir} does not exist. Get around this by using the flag \`--exclude-translations\`.`, |
| 123 | + ) |
| 124 | + } |
| 125 | + const languageFiles: string[] = [] |
| 126 | + languageFiles.push(...walkFiles(path.join(dir, 'content'), ['.md'])) |
| 127 | + languageFiles.push(...walkFiles(path.join(dir, 'data'), ['.md', '.yml'])) |
| 128 | + sourceFiles.push( |
| 129 | + ...languageFiles.filter((languageFile) => |
| 130 | + englishRelativeFiles.has(path.relative(dir, languageFile)), |
| 131 | + ), |
| 132 | + ) |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + // Tables can also be referenced from code (e.g. table-rendering helpers), so |
| 137 | + // search src and contributing as well. Searching more files only ever marks |
| 138 | + // a table as used, never as an orphan, so it errs on the safe side. |
| 139 | + for (const root of ['contributing', 'src']) { |
| 140 | + if (!fs.existsSync(root)) continue |
| 141 | + sourceFiles.push( |
| 142 | + ...walk(root, { |
| 143 | + includeBasePath: true, |
| 144 | + directories: false, |
| 145 | + globs: ['!**/*.+(png|jpe?g|csv|graphql|json|svg)'], |
| 146 | + }), |
| 147 | + ) |
| 148 | + } |
| 149 | + |
| 150 | + if (verbose) { |
| 151 | + console.error(`${sourceFiles.length.toLocaleString()} source files found in total.`) |
| 152 | + } |
| 153 | + |
| 154 | + const tables = getTableFiles() |
| 155 | + if (verbose) { |
| 156 | + console.error(`${tables.length.toLocaleString()} table files found in total.`) |
| 157 | + } |
| 158 | + |
| 159 | + // Read files lazily so we can stop early once every table is accounted for. |
| 160 | + function* readContents(): Generator<string> { |
| 161 | + for (const sourceFile of sourceFiles) { |
| 162 | + yield fs.readFileSync(sourceFile, 'utf-8') |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + const orphanTables = getOrphanedTables(tables, readContents()) |
| 167 | + |
| 168 | + // Safety net: if every table looks orphaned, the detection is almost |
| 169 | + // certainly broken (e.g. content wasn't checked out). Refuse to suggest |
| 170 | + // deleting everything. |
| 171 | + if (tables.length > 0 && orphanTables.length === tables.length) { |
| 172 | + console.error( |
| 173 | + 'Every table was flagged as orphaned, which is almost certainly a bug. ' + |
| 174 | + 'Refusing to output anything. Was the content checked out?', |
| 175 | + ) |
| 176 | + process.exit(1) |
| 177 | + } |
| 178 | + |
| 179 | + if (verbose && orphanTables.length) { |
| 180 | + console.error('The following tables are not mentioned anywhere in any source file:') |
| 181 | + } |
| 182 | + |
| 183 | + if (json) { |
| 184 | + console.log(JSON.stringify(orphanTables, undefined, 2)) |
| 185 | + } else { |
| 186 | + const filesToRemove: string[] = [] |
| 187 | + for (const table of orphanTables) { |
| 188 | + filesToRemove.push(table.yml) |
| 189 | + if (table.schema) filesToRemove.push(table.schema) |
| 190 | + } |
| 191 | + for (const filePath of filesToRemove) { |
| 192 | + console.log(filePath) |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + if (verbose) { |
| 197 | + console.error(`${orphanTables.length.toLocaleString()} orphan tables left.`) |
| 198 | + } |
| 199 | + |
| 200 | + if (exit) { |
| 201 | + process.exit(orphanTables.length) |
| 202 | + } |
| 203 | +} |
0 commit comments