|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +// [start-readme] |
| 4 | +// |
| 5 | +// Run this script to fix known frontmatter errors by copying values from english file |
| 6 | +// Translatable properties are designated in the frontmatter JSON schema |
| 7 | +// |
| 8 | +// [end-readme] |
| 9 | + |
| 10 | +const { execSync } = require('child_process') |
| 11 | +const fs = require('fs') |
| 12 | +const path = require('path') |
| 13 | +const readFileAsync = require('../../lib/readfile-async') |
| 14 | +const fm = require('../../lib/frontmatter') |
| 15 | +const matter = require('gray-matter') |
| 16 | + |
| 17 | +const extractFrontmatter = async (path) => { |
| 18 | + const fileContents = await readFileAsync(path, 'utf8') |
| 19 | + return fm(fileContents) |
| 20 | +} |
| 21 | + |
| 22 | +// Find all content files that differ from the default branch |
| 23 | +// TODO: make sure this will work in an Actions workflow |
| 24 | +const cmd = 'git -c diff.renameLimit=10000 diff --name-only origin/main' |
| 25 | +const changedFilesRelPaths = execSync(cmd) |
| 26 | + .toString() |
| 27 | + .split('\n') |
| 28 | + .filter(filename => { |
| 29 | + return filename.startsWith('translations/') && |
| 30 | + filename.includes('/content/') && |
| 31 | + !filename.endsWith('README.md') |
| 32 | + }) |
| 33 | + |
| 34 | +changedFilesRelPaths.forEach(async (relPath) => { |
| 35 | + const localisedAbsPath = path.join(__dirname, '../..', relPath) |
| 36 | + // find the corresponding english file by removing the first 2 path segments: /translations/<language code> |
| 37 | + const engAbsPath = path.join(__dirname, '../..', relPath.split(path.sep).slice(2).join(path.sep)) |
| 38 | + |
| 39 | + const localisedFrontmatter = await extractFrontmatter(localisedAbsPath) |
| 40 | + if (!localisedFrontmatter) return |
| 41 | + |
| 42 | + // Load frontmatter from the source english file |
| 43 | + const englishFrontmatter = await extractFrontmatter(engAbsPath) |
| 44 | + |
| 45 | + // Look for differences between the english and localised non-translatable properties |
| 46 | + let overWroteSomething = false |
| 47 | + for (const prop in englishFrontmatter.data) { |
| 48 | + if (!fm.schema.properties[prop].translatable && localisedFrontmatter.data[prop] !== englishFrontmatter.data[prop]) { |
| 49 | + localisedFrontmatter.data[prop] = englishFrontmatter.data[prop] |
| 50 | + overWroteSomething = true |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // rewrite the localised file, if it changed |
| 55 | + if (overWroteSomething) { |
| 56 | + const toWrite = matter.stringify(localisedFrontmatter.content, localisedFrontmatter.data, { lineWidth: 10000, forceQuotes: true }) |
| 57 | + fs.writeFileSync(localisedAbsPath, toWrite) |
| 58 | + } |
| 59 | +}) |
0 commit comments