This repository has been archived by the owner on Jun 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
mergeTranslations.js
executable file
·58 lines (44 loc) · 1.93 KB
/
mergeTranslations.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* eslint-env node */
/* eslint-disable no-console, curly */
const fs = require('fs');
const path = require('path');
const basePath = './src/features/translations';
const tempFolder = `${basePath}/temp`;
const targetFolder = basePath;
const tempDir = path.resolve(__dirname, tempFolder);
const targetDir = path.resolve(__dirname, targetFolder);
const getLocalesMap = files => {
const localesMap = new Map();
files.map(file => {
const locale = file.split('.')[1];
const storedLocale = localesMap.get(locale);
const matchingfiles = storedLocale ? [...storedLocale, file] : [file];
localesMap.set(locale, matchingfiles);
});
return localesMap;
};
const readDir = dir =>
new Promise((resolve, reject) => fs.readdir(dir, (err, files) => (err ? reject(err) : resolve(files))));
const readFile = filePath =>
new Promise((resolve, reject) => fs.readFile(filePath, 'utf8', (err, data) => (err ? reject(err) : resolve(data))));
const writeFile = (filePath, content) =>
new Promise((resolve, reject) => fs.writeFile(filePath, content, 'utf8', err => (err ? reject(err) : resolve())));
const getJsonFileContent = async file => JSON.parse(await readFile(`${tempDir}/${file}`));
const mergeByLocale = async (locale, localesMap) => {
const filesToMerge = localesMap.get(locale);
const mergedContent = await Promise.all(filesToMerge.map(getJsonFileContent));
let fileContent = {};
mergedContent.map(item => {
fileContent = { ...fileContent, ...item };
});
const targetFile = `${targetDir}/${locale}.json`;
console.log(`Write file: ${targetFile}`);
//console.log(fileContent);
writeFile(targetFile, JSON.stringify(fileContent, null, 4));
};
(async () => {
const tempFiles = await readDir(tempDir);
const localesMap = getLocalesMap(tempFiles);
const localesList = Array.from(localesMap.keys());
localesList.map(locale => mergeByLocale(locale, localesMap));
})();