]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - scripts/i18n/xliff2json.ts
Fix i18n generation
[github/Chocobozzz/PeerTube.git] / scripts / i18n / xliff2json.ts
... / ...
CommitLineData
1import { registerTSPaths } from '../../server/helpers/register-ts-paths'
2registerTSPaths()
3
4import * as xliff12ToJs from 'xliff/xliff12ToJs'
5import { readFileSync, unlink, writeFile } from 'fs-extra'
6import { join } from 'path'
7import { buildFileLocale, I18N_LOCALES, isDefaultLocale } from '../../shared/models/i18n/i18n'
8import { eachSeries } from 'async'
9
10const sources: string[] = []
11const availableLocales = Object.keys(I18N_LOCALES)
12 .filter(l => isDefaultLocale(l) === false)
13 .map(l => buildFileLocale(l))
14
15for (const file of [ 'player', 'server', 'iso639' ]) {
16 for (const locale of availableLocales) {
17 sources.push(join(__dirname, '../../../client/src/locale/target/', `${file}_${locale}.xml`))
18 }
19}
20
21eachSeries(sources, (source, cb) => {
22 xliffFile2JSON(source, cb)
23}, err => {
24 if (err) return handleError(err)
25
26 mergeISO639InServer(err => {
27 if (err) return handleError(err)
28
29 process.exit(0)
30 })
31})
32
33function handleError (err: any) {
34 console.error(err)
35 process.exit(-1)
36}
37
38function xliffFile2JSON (filePath: string, cb) {
39 const fileTarget = filePath.replace('.xml', '.json')
40
41 // Remove the two first lines our xliff module does not like
42 let fileContent = readFileSync(filePath).toString()
43 fileContent = removeFirstLine(fileContent)
44 fileContent = removeFirstLine(fileContent)
45
46 xliff12ToJs(fileContent, (err, res) => {
47 if (err) return cb(err)
48
49 const json = createJSONString(res)
50 writeFile(fileTarget, json, err => {
51 if (err) return cb(err)
52
53 return unlink(filePath, cb)
54 })
55 })
56}
57
58function mergeISO639InServer (cb) {
59 eachSeries(availableLocales, (locale, eachCallback) => {
60 const serverPath = join(__dirname, '../../../client/src/locale/target/', `server_${locale}.json`)
61 const iso639Path = join(__dirname, '../../../client/src/locale/target/', `iso639_${locale}.json`)
62
63 const resServer = readFileSync(serverPath).toString()
64 const resISO639 = readFileSync(iso639Path).toString()
65
66 const jsonServer = JSON.parse(resServer)
67 const jsonISO639 = JSON.parse(resISO639)
68
69 Object.assign(jsonServer, jsonISO639)
70 const serverString = JSON.stringify(jsonServer)
71
72 writeFile(serverPath, serverString, err => {
73 if (err) return eachCallback(err)
74
75 return unlink(iso639Path, eachCallback)
76 })
77 }, cb)
78}
79
80function removeFirstLine (str: string) {
81 return str.substring(str.indexOf('\n') + 1)
82}
83
84function createJSONString (obj: any) {
85 const res: any = {}
86 const strings = obj.resources['']
87
88 Object.keys(strings).forEach(k => res[k] = strings[k].target)
89
90 return JSON.stringify(res)
91}