Skip to content

Instantly share code, notes, and snippets.

@dohaki
Created November 28, 2019 16:56
Show Gist options
  • Save dohaki/127005faa6c0048e939ecfcf104b990e to your computer and use it in GitHub Desktop.
Save dohaki/127005faa6c0048e939ecfcf104b990e to your computer and use it in GitHub Desktop.
script to migrate from i18n.js to fbt in trustlines mobileapp
const fs = require("fs")
const srcDir = `${__dirname}/../src/shared/`
const translations = require(`${srcDir}i18n/en.json`)
function getJSFileNames(dir, prevFiles = []) {
const files = fs.readdirSync(dir)
files.forEach(file => {
const name = dir + "/" + file
if (fs.statSync(name).isDirectory()) {
getJSFileNames(name, prevFiles)
} else {
if (name.endsWith(".js")) {
prevFiles.push(name)
}
}
})
return prevFiles
}
function findAndReplace(jsFileContent, translations) {
const oldImport = `import { translate as t } from "lib/i18n"`
const newImport = `import { fbt } from "fbt-runtime"`
const translateMatches = [
...jsFileContent.matchAll(new RegExp(/t\("\w+\.(\w+|\.)*\w"\)/, "g")),
].map(match => match[0])
const matchToTranslation = translateMatches.map(match => {
const translateKey = match.match(new RegExp(/\w+\.(\w+|\.)*\w/, "g"))[0]
const props = translateKey.split(".")
const translation = getTranslation(translations, props)
return {
match,
translateKey,
translation,
}
})
const fbtReplaced = matchToTranslation.reduce((result, m2T) => {
return result.replace(
m2T.match,
`fbt("${m2T.translation}", "${m2T.translateKey}")`
)
}, jsFileContent)
const importAndFbtReplaced = fbtReplaced.replace(oldImport, newImport)
return importAndFbtReplaced
}
function getTranslation(translation, props) {
if (props.length === 1) {
return translation[props[0]]
}
return getTranslation(translation[props[0]], props.splice(1, props.length))
}
const jsFileNames = getJSFileNames(srcDir)
jsFileNames.forEach(jsFileName => {
const jsFileContent = fs.readFileSync(jsFileName)
const newJSFileContent = findAndReplace(
jsFileContent.toString(),
translations
)
fs.writeFileSync(jsFileName, newJSFileContent)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment