// SPDX-License-Identifier: LGPL-2.1-or-later import fs from 'node:fs'; import path from 'node:path'; import process from 'node:process'; import gettext_parser from "gettext-parser"; const config = {}; const DEFAULT_WRAPPER = 'cockpit.locale(PO_DATA);'; const RTL_LANGS = new Set(["ar", "fa", "he", "ur"]); function get_po_files() { const poDir = path.resolve(config.srcdir, 'po'); try { return fs.readdirSync(poDir) .filter(file => file.endsWith('.po')) .map(file => path.join(poDir, file)); } catch (error) { return []; } } function get_plural_expr(statement) { const expr = statement.replace(/nplurals=[1-9]; plural=([^;]*);?$/, '(n) => $1'); if (expr === statement) { console.error("bad plural forms: " + statement); process.exit(1); } return expr; } function parsePo(po_file) { // Read the PO file, remove fuzzy/disabled lines to avoid tripping up the validator const po_data = fs.readFileSync(po_file, 'utf8') .split('\n') .filter(line => !line.startsWith('#~')) .join('\n'); const parsed = gettext_parser.po.parse(po_data, { defaultCharset: 'utf8', validation: true }); delete parsed.translations[""][""]; // second header copy const dir = RTL_LANGS.has(parsed.headers.Language) ? "rtl" : "ltr"; return { parsed, dir }; } function buildFile(data, subdir, filename, filter) { const parsed = data.parsed; const dir = data.dir; // cockpit.js only looks at "plural-forms" and "language" const chunks = [ '{\n', ' "": {\n', ` "plural-forms": ${get_plural_expr(parsed.headers['Plural-Forms'])},\n`, ` "language": "${parsed.headers.Language}",\n`, ` "language-direction": "${dir}"\n`, ' }' ]; for (const [msgctxt, context] of Object.entries(parsed.translations)) { const context_prefix = msgctxt ? msgctxt + '\u0004' : ''; /* for cockpit.ngettext */ for (const [msgid, translation] of Object.entries(context)) { /* Only include msgids which appear in this source directory */ const references = translation.comments.reference.split(/\s/); if (!references.some(str => str.startsWith(`pkg/${subdir}`) || str.startsWith(config.src_directory) || str.startsWith(`pkg/lib`))) continue; if (translation.comments.flag?.match(/\bfuzzy\b/)) continue; if (!references.some(filter)) continue; const key = JSON.stringify(context_prefix + msgid); // cockpit.js always ignores the first item chunks.push(`,\n ${key}: [\n null`); for (const str of translation.msgstr) { chunks.push(',\n ' + JSON.stringify(str)); } chunks.push('\n ]'); } } chunks.push('\n}'); const wrapper = config.wrapper?.(subdir) || DEFAULT_WRAPPER; const output = wrapper.replace('PO_DATA', chunks.join('')) + '\n'; const out_path = path.join(subdir ? (subdir + '/') : '', filename); fs.writeFileSync(path.resolve(config.outdir, out_path), output); } function init(options) { config.srcdir = process.env.SRCDIR || './'; config.subdirs = options.subdirs || ['']; config.src_directory = options.src_directory || 'src'; config.wrapper = options.wrapper; config.outdir = options.outdir || './dist'; } function run() { const parsedPoFiles = get_po_files().map(po_file => ({ data: parsePo(po_file), lang: path.basename(po_file).slice(0, -3), })); for (const subdir of config.subdirs) { for (const { data, lang } of parsedPoFiles) { // Separate translations for the manifest.json file and normal pages buildFile(data, subdir, `po.${lang}.js`, str => !str.includes('manifest.json')); buildFile(data, subdir, `po.manifest.${lang}.js`, str => str.includes('manifest.json')); } } } export const cockpitPoEsbuildPlugin = options => ({ name: 'cockpitPoEsbuildPlugin', setup(build) { init({ ...options, outdir: build.initialOptions.outdir }); build.onEnd(result => { result.errors.length === 0 && run() }); }, });