This repository has been archived by the owner on Feb 15, 2019. It is now read-only.
/
to-csv.js
91 lines (82 loc) · 2.47 KB
/
to-csv.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import fs from 'fs';
import path from 'path';
import csvStringify from 'csv-stringify';
import eol from 'eol';
import denodeify from 'denodeify';
import map from 'lodash/map';
import parseJsonFromJsFile from './utils/parse-json-from-js-file';
const readdir = denodeify(fs.readdir);
const stat = denodeify(fs.stat);
const writeFile = denodeify(fs.writeFile);
const stringify = denodeify(csvStringify);
export default function(localesPath, csvPath, { onlyMissing } = {}) {
return readdir(localesPath).then(locales => {
let prmoises = locales.map(locale => {
let filePath = path.resolve(localesPath, locale, 'translations.js');
return stat(filePath).then(() => {
return {
locale,
filePath
};
}).catch(() => false);
});
return Promise.all(prmoises).then(results => {
results = results.filter(result => result);
return {
locales: map(results, 'locale'),
filePaths: map(results, 'filePath')
};
});
}).then(({ locales, filePaths }) => {
let keys = [];
let rows = [];
function recurse(json, columnIndex, rowIndex, currentKey) {
for (let key in json) {
let value = json[key];
let newKey = currentKey;
if (newKey) {
newKey += '.';
}
newKey += key;
if (typeof value === 'object') {
rowIndex = recurse(value, columnIndex, rowIndex, newKey);
} else {
let row;
let index = keys.indexOf(newKey);
if (index !== -1) {
row = rows[index];
} else {
row = [];
rows.splice(rowIndex, 0, row);
keys.splice(rowIndex, 0, newKey);
}
for (let i in locales) {
if (i === columnIndex) {
row[i] = value;
} else if (!row[i]) {
row[i] = '';
}
}
rowIndex++;
}
}
return rowIndex;
}
for (let columnIndex in filePaths) {
let filePath = filePaths[columnIndex];
let json = parseJsonFromJsFile(filePath);
recurse(json, columnIndex, 0, '');
}
let lines = [];
lines.push(['key'].concat(locales.map(locale => locale.replace('.js', ''))));
for (let i in keys) {
if (!onlyMissing || rows[i].indexOf('') > -1) {
lines.push([keys[i]].concat(rows[i]));
}
}
return stringify(lines);
}).then(csv => {
let normalized = eol.auto(csv);
return writeFile(csvPath, normalized);
});
}