PeerTube/scripts/i18n/xliff2json.ts

63 lines
1.7 KiB
TypeScript
Raw Normal View History

2018-06-06 07:23:40 -05:00
import * as xliff12ToJs from 'xliff/xliff12ToJs'
2018-06-06 09:46:42 -05:00
import { unlink, readFileSync, writeFile } from 'fs'
2018-06-06 07:23:40 -05:00
import { join } from 'path'
2018-06-06 10:37:13 -05:00
import { buildFileLocale, I18N_LOCALES, isDefaultLocale, LOCALE_FILES } from '../../shared/models/i18n/i18n'
2018-06-06 09:46:42 -05:00
import { eachSeries } from 'async'
2018-06-06 07:23:40 -05:00
2018-06-06 09:46:42 -05:00
const sources: string[] = []
const availableLocales = Object.keys(I18N_LOCALES)
.filter(l => isDefaultLocale(l) === false)
.map(l => buildFileLocale(l))
2018-06-06 07:23:40 -05:00
2018-06-06 10:37:13 -05:00
for (const file of LOCALE_FILES) {
2018-06-06 09:46:42 -05:00
for (const locale of availableLocales) {
sources.push(join(__dirname, '../../../client/src/locale/target/', `${file}_${locale}.xml`))
2018-06-06 07:23:40 -05:00
}
2018-06-06 09:46:42 -05:00
}
2018-06-06 07:23:40 -05:00
2018-06-06 09:46:42 -05:00
eachSeries(sources, (source, cb) => {
xliffFile2JSON(source, cb)
}, err => {
if (err) return handleError(err)
2018-06-06 07:23:40 -05:00
2018-06-06 09:46:42 -05:00
process.exit(0)
2018-06-06 07:23:40 -05:00
})
2018-06-06 09:46:42 -05:00
function handleError (err: any) {
console.error(err)
process.exit(-1)
}
function xliffFile2JSON (filePath: string, cb) {
const fileTarget = filePath.replace('.xml', '.json')
// Remove the two first lines our xliff module does not like
let fileContent = readFileSync(filePath).toString()
fileContent = removeFirstLine(fileContent)
fileContent = removeFirstLine(fileContent)
xliff12ToJs(fileContent, (err, res) => {
if (err) return cb(err)
const json = createJSONString(res)
writeFile(fileTarget, json, err => {
if (err) return cb(err)
return unlink(filePath, cb)
})
})
}
2018-06-06 07:23:40 -05:00
function removeFirstLine (str: string) {
return str.substring(str.indexOf('\n') + 1)
}
function createJSONString (obj: any) {
const res: any = {}
const strings = obj.resources['']
Object.keys(strings).forEach(k => res[k] = strings[k].target)
return JSON.stringify(res)
}