Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: build/csv-export.js

Issue 29636585: Issue 6171 - create CSV exporter and importer for translations (Closed)
Patch Set: Addressed Thomas comments Created May 16, 2018, 5:05 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « README.md ('k') | package.json » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 * Copyright (C) 2006-present eyeo GmbH
4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation.
8 *
9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 /* globals process */
19
20 "use strict";
21
22 const fs = require("fs");
23 const path = require("path");
24 const csv = require("csv");
25 const {promisify} = require("util");
26 const execFile = promisify(require("child_process").execFile);
27 const csvParser = promisify(csv.parse);
28 const readFile = promisify(fs.readFile);
29 const glob = promisify(require("glob").glob);
30 const readJsonPromised = promisify(readJson);
31
32 const localesDir = "locale";
33 const defaultLocale = "en_US";
34
35 let headers = ["Filename", "StringID", "Description", "Placeholders",
36 defaultLocale];
37 let outputFileName = "translations-{repo}-{hash}.csv";
38
39 /**
40 * Export existing translation - files into CSV file
41 */
42 function exportTranslations()
43 {
44 let mercurialCommands = [];
45 // Get Hash
46 mercurialCommands.push(execFile("hg", ["id", "-i"]));
47 // Get repo path
48 mercurialCommands.push(execFile("hg", ["paths", "default"]));
49 Promise.all(mercurialCommands).then((outputs) =>
50 {
51 // Remove line endings and "+" sign from the end of the hash
52 let [hash, filePath] = outputs.map((output) =>
53 output.stdout.replace(/\+\n|\n$/, ""));
54 // Update name of the file to be output
55 outputFileName = outputFileName.replace("{hash}", hash);
56 outputFileName = outputFileName.replace("{repo}", path.basename(filePath));
57
58 // Read all available locales and default files
59 return glob(`${localesDir}/**/*.json`);
60 }).then((filePaths) =>
61 {
62 // Reading all existing translations files
63 return Promise.all(filePaths.map((filePath) => readJsonPromised(filePath)));
64 }).then(csvFromJsonFileObjects);
65 }
66
67 /**
68 * Creating Matrix which reflects output CSV file
69 * @param {Object[]} fileObjects - array of file objects created by readJson
70 */
71 function csvFromJsonFileObjects(fileObjects)
72 {
73 let locales = [];
74 // Create Object tree from the Objects array, for easier search
75 // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}}
76 let dataTreeObj = Object.create(null);
77 for (let fileObject of fileObjects)
78 {
79 const {fileName, locale, strings} = fileObject;
80
81 if (!locales.includes(locale))
82 locales.push(locale);
83
84 if (!dataTreeObj[fileName])
85 dataTreeObj[fileName] = {};
86 if (!dataTreeObj[fileName][locale])
87 dataTreeObj[fileName][locale] = {};
88 dataTreeObj[fileName][locale] = strings;
89 }
90
91 let fileNames = Object.keys(dataTreeObj);
92 if (filesFilter.length)
93 fileNames = fileNames.filter((item) => filesFilter.includes(item));
94
95 locales = locales.filter((locale) => locale != defaultLocale).sort();
96 // Create two dimensional strings array that reflects CSV structure
97 let csvArray = [headers.concat(locales)];
98 for (let fileName of fileNames)
99 {
100 let strings = dataTreeObj[fileName][defaultLocale];
101 for (let stringID of Object.keys(strings))
102 {
103 let fileObj = dataTreeObj[fileName];
104 let {description, message, placeholders} = strings[stringID];
105 let row = [fileName, stringID, description || "",
106 JSON.stringify(placeholders), message];
107
108 for (let locale of locales)
109 {
110 let localeFileObj = fileObj[locale];
111 let isTranslated = !!(localeFileObj && localeFileObj[stringID]);
112 row.push(isTranslated ? localeFileObj[stringID].message : "");
113 }
114 csvArray.push(row);
115 }
116 }
117 arrayToCsv(csvArray);
118 }
119
120 /**
121 * Import strings from the CSV file
122 * @param {string} filePath - CSV file path to import from
123 */
124 function importTranslations(filePath)
125 {
126 readFile(filePath, "utf8").then((fileObjects) =>
127 {
128 return csvParser(fileObjects);
129 }).then((dataMatrix) =>
130 {
131 let headLocales = dataMatrix.shift().slice(4);
132 let dataTreeObj = {};
133 for (let rowId in dataMatrix)
134 {
135 let row = dataMatrix[rowId];
136 let [currentFilename, stringId, description, placeholder, ...messages] =
137 row;
138 if (!stringId)
139 continue;
140
141 stringId = stringId.trim();
142 // Check if it's the filename row
143 if (!dataTreeObj[currentFilename])
144 dataTreeObj[currentFilename] = {};
145
146 description = description.trim();
147 for (let i = 0; i < headLocales.length; i++)
148 {
149 let locale = headLocales[i].trim();
150 let message = messages[i].trim();
151 if (!message)
152 continue;
153
154 // Create Object tree from the Objects array, for easier search
155 // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}}
156 if (!dataTreeObj[currentFilename][locale])
157 dataTreeObj[currentFilename][locale] = {};
158
159 let localeObj = dataTreeObj[currentFilename][locale];
160 localeObj[stringId] = {};
161 let stringObj = localeObj[stringId];
162
163 // We keep string descriptions only in default locale files
164 if (locale == defaultLocale)
165 stringObj.description = description;
166
167 stringObj.message = message;
168 if (placeholder)
169 stringObj.placeholders = JSON.parse(placeholder);
170 }
171 }
172 writeJson(dataTreeObj);
173 });
174 }
175
176 /**
177 * Write locale files according to dataTreeObj
178 * @param {Object} dataTreeObj - ex.:
179 * {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}}
180 */
181 function writeJson(dataTreeObj)
182 {
183 for (let fileName in dataTreeObj)
184 {
185 for (let locale in dataTreeObj[fileName])
186 {
187 let filePath = path.join(localesDir, locale, fileName);
188 let sortedJSON = orderJSON(dataTreeObj[fileName][locale]);
189 let fileString = JSON.stringify(sortedJSON, null, 2);
190
191 // Newline at end of file to match Coding Style
192 if (locale == defaultLocale)
193 fileString += "\n";
194 fs.writeFile(filePath, fileString, "utf8", (err) =>
195 {
196 if (err)
197 {
198 console.error(err);
199 }
200 else
201 {
202 console.log(`Updated: ${filePath}`);
203 }
204 });
205 }
206 }
207 }
208
209 /**
210 * This function currently relies on V8 to sort the object by keys
211 * @param {Object} unordered - json object
212 * @returns {Object}
213 */
214 function orderJSON(unordered)
215 {
216 const ordered = {};
217 for (let key of Object.keys(unordered).sort())
218 {
219 ordered[key] = unordered[key];
220 if (unordered[key].placeholders)
221 ordered[key].placeholders = orderJSON(unordered[key].placeholders);
222
223 ordered[key] = unordered[key];
224 }
225 return ordered;
226 }
227
228 /**
229 * Convert two dimensional array to the CSV file
230 * @param {Object[]} csvArray - array to convert from
231 */
232 function arrayToCsv(csvArray)
233 {
234 csv.stringify(csvArray, (err, output) =>
235 {
236 fs.writeFile(outputFileName, output, "utf8", (error) =>
237 {
238 if (!error)
239 console.log(`${outputFileName} is created`);
240 else
241 console.error(error);
242 });
243 });
244 }
245
246 /**
247 * Reads JSON file and assign filename and locale to it
248 * @param {string} filePath - ex.: "locales/en_US/desktop-options.json"
249 * @param {function} callback - fileName, locale and strings of locale file
250 * Parameters:
251 * * Error message
252 * * Object containing fileName, locale and strings
253 */
254 function readJson(filePath, callback)
255 {
256 let {dir, base} = path.parse(filePath);
257 fs.readFile(filePath, "utf8", (err, data) =>
258 {
259 if (err)
260 {
261 callback(err);
262 }
263 else
264 {
265 let locale = dir.split(path.sep).pop();
266 let strings = JSON.parse(data);
267 callback(null, {fileName: base, locale, strings});
268 }
269 });
270 }
271
272 /**
273 * Exit process and log error message
274 * @param {String} error error message
275 */
276 function exitProcess(error)
277 {
278 console.error(error);
279 process.exit(1);
280 }
281
282 // CLI
283 let helpText = `
284 About: Converts locale files between CSV and JSON formats
285 Usage: csv-export.js [option] [argument]
286 Options:
287 -f [FILENAME] Name of the files to be exported ex.: -f firstRun.json
288 option can be used multiple times.
289 If omitted all files are being exported
290
291 -o [FILENAME] Output filename ex.:
292 -f firstRun.json -o {hash}-firstRun.csv
293 Placeholders:
294 {hash} - Mercurial current revision hash
295 {repo} - Name of the "Default" repository
296 If omitted the output fileName is set to
297 translations-{repo}-{hash}.csv
298
299 -i [FILENAME] Import file path ex: -i issue-reporter.csv
300 `;
301
302 let argv = process.argv.slice(2);
303 let stopExportScript = false;
304 // Filter to be used export to the fileNames inside
305 let filesFilter = [];
306
307 for (let i = 0; i < argv.length; i++)
308 {
309 switch (argv[i])
310 {
311 case "-h":
312 console.log(helpText);
313 stopExportScript = true;
314 break;
315 case "-f":
316 if (!argv[i + 1])
317 {
318 exitProcess("Please specify the input filename");
319 }
320 filesFilter.push(argv[i + 1]);
321 break;
322 case "-o":
323 if (!argv[i + 1])
324 {
325 exitProcess("Please specify the output filename");
326 }
327 outputFileName = argv[i + 1];
328 break;
329 case "-i":
330 if (!argv[i + 1])
331 {
332 exitProcess("Please specify the import file");
333 }
334 let importFile = argv[i + 1];
335 importTranslations(importFile);
336 stopExportScript = true;
337 break;
338 }
339 }
340
341 if (!stopExportScript)
342 exportTranslations(filesFilter);
OLDNEW
« no previous file with comments | « README.md ('k') | package.json » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld