UNPKG

crowdfree

Version:

A crowdin compatible tool for translation and localisation of websites and applications

73 lines (68 loc) 2.7 kB
const fs = require("fs").promises const path = require("path") async function saveLocale(translations, localeFolder) { // Turn translations into locales const locales = [] translations.forEach(translation => { // For each localization of the translation for (let localeKey in translation.value) { let locale = locales.find(x => x.locale === localeKey) if (!locale) { // Create new locale if missing locale = { locale: localeKey, files: [] } locales.push(locale) } // Check for existence of file if (!locale.files.find(x => x.name === translation.file)) { locale.files.push({ name: translation.file, content: {} }) } // Add translation to file content locale.files.find(x => x.name === translation.file).content[translation.key] = translation.value[localeKey].value || "" } }) // Ensure folder structure exists for (let locale of locales) { await fs.mkdir(path.join(localeFolder, locale.locale), { recursive: true }) } // Write locale files for (let locale of locales) { for (let file of locale.files) { let filepath = path.join(localeFolder, locale.locale, file.name) let content = JSON.stringify(file.content, null, 4) let original = await fs.readFile(filepath) if (original !== content) await fs.writeFile(filepath, content) } } } async function findLocaleFolder(directory, folder) { let foundLocaleFolder = false return findLocaleFolderRecurse(directory, folder) async function findLocaleFolderRecurse(directory, folder) { if (foundLocaleFolder || !folder || ["node_modules", ".git", "dist", "build"].includes(folder)) { return false } else if (folder == "locale") { return path.join(directory, "locale") } else { // Recurse try { var dirs = await fs.readdir(path.join(directory, folder)) } catch (e) { // No permission or probably a file return false } let results = await Promise.all(dirs.map(dir => findLocaleFolderRecurse(path.join(directory, folder), dir))) // console.log(dirs, results) return results.find(locale_path => locale_path) } } } module.exports = { saveLocale, findLocaleFolder, }