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: Removed mercurial commands Created May 17, 2018, 5:23 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
« README.md ('K') | « 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 /*
saroyanm 2018/05/24 17:00:59 In some stage of import/export This "\u00A0" speci
Thomas Greiner 2018/05/25 10:23:28 Based on what I see in https://gitlab.com/eyeo/adb
saroyanm 2018/05/28 13:37:08 Yes, it's there because I've added them manually.
Thomas Greiner 2018/05/28 17:12:46 No particular reason. It was just easier to write
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.csv";
38
39 /**
40 * Export existing translation - files into CSV file
41 */
42 function exportTranslations()
43 {
44 glob(`${localesDir}/**/*.json`).then((filePaths) =>
45 {
46 // Reading all existing translations files
47 return Promise.all(filePaths.map((filePath) => readJsonPromised(filePath)));
48 }).then(csvFromJsonFileObjects);
49 }
50
51 /**
52 * Creating Matrix which reflects output CSV file
53 * @param {Object[]} fileObjects - array of file objects created by readJson
54 */
55 function csvFromJsonFileObjects(fileObjects)
56 {
57 let locales = [];
58 // Create Object tree from the Objects array, for easier search
59 // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}}
60 let dataTreeObj = Object.create(null);
61 for (let fileObject of fileObjects)
62 {
63 const {fileName, locale, strings} = fileObject;
64
65 if (!locales.includes(locale))
66 locales.push(locale);
67
68 if (!dataTreeObj[fileName])
69 dataTreeObj[fileName] = {};
70 if (!dataTreeObj[fileName][locale])
71 dataTreeObj[fileName][locale] = {};
72 dataTreeObj[fileName][locale] = strings;
73 }
74
75 let fileNames = Object.keys(dataTreeObj);
76 if (filesFilter.length)
77 fileNames = fileNames.filter((item) => filesFilter.includes(item));
78
79 locales = locales.filter((locale) => locale != defaultLocale).sort();
Thomas Greiner 2018/06/12 14:50:41 Is there no need for sorting locales anymore?
saroyanm 2018/06/12 15:22:49 If you mean default strings: See -> https://gitlab
80 // Create two dimensional strings array that reflects CSV structure
81 let csvArray = [headers.concat(locales)];
82 for (let fileName of fileNames)
83 {
84 let strings = dataTreeObj[fileName][defaultLocale];
85 for (let stringID of Object.keys(strings))
86 {
87 let fileObj = dataTreeObj[fileName];
88 let {description, message, placeholders} = strings[stringID];
89 let row = [fileName, stringID, description || "",
90 JSON.stringify(placeholders), message];
91
92 for (let locale of locales)
93 {
94 let localeFileObj = fileObj[locale];
95 let isTranslated = !!(localeFileObj && localeFileObj[stringID]);
96 row.push(isTranslated ? localeFileObj[stringID].message : "");
97 }
98 csvArray.push(row);
99 }
100 }
101 arrayToCsv(csvArray);
102 }
103
104 /**
105 * Import strings from the CSV file
106 * @param {string} filePath - CSV file path to import from
107 */
108 function importTranslations(filePath)
109 {
110 readFile(filePath, "utf8").then((fileObjects) =>
111 {
112 return csvParser(fileObjects);
saroyanm 2018/05/24 16:40:02 I think there might a bug in csvParser -> https://
113 }).then((dataMatrix) =>
114 {
115 let headLocales = dataMatrix.shift().slice(4);
116 let dataTreeObj = {};
117 for (let rowId in dataMatrix)
118 {
119 let row = dataMatrix[rowId];
120 let [currentFilename, stringId, description, placeholder, ...messages] =
121 row;
122 if (!stringId)
123 continue;
124
125 stringId = stringId.trim();
126 // Check if it's the filename row
127 if (!dataTreeObj[currentFilename])
128 dataTreeObj[currentFilename] = {};
129
130 description = description.trim();
131 for (let i = 0; i < headLocales.length; i++)
132 {
133 let locale = headLocales[i].trim();
134 let message = messages[i].trim();
135 if (!message)
136 continue;
137
138 // Create Object tree from the Objects array, for easier search
139 // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}}
140 if (!dataTreeObj[currentFilename][locale])
141 dataTreeObj[currentFilename][locale] = {};
142
143 let localeObj = dataTreeObj[currentFilename][locale];
144 localeObj[stringId] = {};
145 let stringObj = localeObj[stringId];
146
147 // We keep string descriptions only in default locale files
148 if (locale == defaultLocale)
saroyanm 2018/05/24 13:29:26 I've changed this into if (locale == defaultLocale
Thomas Greiner 2018/05/24 13:49:42 I think your suggested solution (i.e. only include
149 stringObj.description = description;
150
151 stringObj.message = message;
152 if (placeholder)
153 stringObj.placeholders = JSON.parse(placeholder);
154 }
155 }
156 writeJson(dataTreeObj);
157 });
158 }
159
160 /**
161 * Write locale files according to dataTreeObj
162 * @param {Object} dataTreeObj - ex.:
163 * {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}}
164 */
165 function writeJson(dataTreeObj)
166 {
167 for (let fileName in dataTreeObj)
168 {
169 for (let locale in dataTreeObj[fileName])
170 {
171 let filePath = path.join(localesDir, locale, fileName);
172 let sortedJSON = orderJSON(dataTreeObj[fileName][locale]);
saroyanm 2018/05/24 15:29:54 Sorting the Default locale produce an unreadable d
Thomas Greiner 2018/05/24 15:46:46 I understand. In that case let's sort the default
saroyanm 2018/06/05 15:03:47 I've created a gitlab issue in order to discuss th
173 let fileString = JSON.stringify(sortedJSON, null, 2);
174
175 // Newline at end of file to match Coding Style
176 if (locale == defaultLocale)
177 fileString += "\n";
178 fs.writeFile(filePath, fileString, "utf8", (err) =>
179 {
180 if (err)
181 {
182 console.error(err);
183 }
184 else
185 {
186 console.log(`Updated: ${filePath}`);
187 }
188 });
189 }
190 }
191 }
192
193 /**
194 * This function currently relies on V8 to sort the object by keys
195 * @param {Object} unordered - json object
196 * @returns {Object}
197 */
198 function orderJSON(unordered)
199 {
200 const ordered = {};
201 for (let key of Object.keys(unordered).sort())
202 {
203 ordered[key] = unordered[key];
204 if (unordered[key].placeholders)
205 ordered[key].placeholders = orderJSON(unordered[key].placeholders);
206
207 ordered[key] = unordered[key];
208 }
209 return ordered;
210 }
211
212 /**
213 * Convert two dimensional array to the CSV file
214 * @param {Object[]} csvArray - array to convert from
215 */
216 function arrayToCsv(csvArray)
217 {
218 csv.stringify(csvArray, (err, output) =>
219 {
220 fs.writeFile(outputFileName, output, "utf8", (error) =>
221 {
222 if (!error)
223 console.log(`${outputFileName} is created`);
224 else
225 console.error(error);
226 });
227 });
228 }
229
230 /**
231 * Reads JSON file and assign filename and locale to it
232 * @param {string} filePath - ex.: "locales/en_US/desktop-options.json"
233 * @param {function} callback - fileName, locale and strings of locale file
234 * Parameters:
235 * * Error message
236 * * Object containing fileName, locale and strings
237 */
238 function readJson(filePath, callback)
239 {
240 let {dir, base} = path.parse(filePath);
241 fs.readFile(filePath, "utf8", (err, data) =>
242 {
243 if (err)
244 {
245 callback(err);
246 }
247 else
248 {
249 let locale = dir.split(path.sep).pop();
250 let strings = JSON.parse(data);
251 callback(null, {fileName: base, locale, strings});
252 }
253 });
254 }
255
256 /**
257 * Exit process and log error message
258 * @param {String} error error message
259 */
260 function exitProcess(error)
261 {
262 console.error(error);
263 process.exit(1);
264 }
265
266 // CLI
267 let helpText = `
268 About: Converts locale files between CSV and JSON formats
269 Usage: csv-export.js [option] [argument]
270 Options:
271 -f [FILENAME] Name of the files to be exported ex.: -f firstRun.json
272 option can be used multiple times.
273 If omitted all files are being exported
274
275 -o [FILENAME] Output filename ex.:
276 -f firstRun.json -o {hash}-firstRun.csv
277 Placeholders:
278 {hash} - Mercurial current revision hash
279 {repo} - Name of the "Default" repository
Thomas Greiner 2018/05/22 17:22:50 Detail: These placeholders no longer exist.
saroyanm 2018/06/05 15:03:47 Done.
280 If omitted the output fileName is set to
281 translations-{repo}-{hash}.csv
282
283 -i [FILENAME] Import file path ex: -i issue-reporter.csv
284 `;
285
286 let argv = process.argv.slice(2);
287 let stopExportScript = false;
288 // Filter to be used export to the fileNames inside
289 let filesFilter = [];
290
291 for (let i = 0; i < argv.length; i++)
292 {
293 switch (argv[i])
294 {
295 case "-h":
296 console.log(helpText);
297 stopExportScript = true;
298 break;
299 case "-f":
300 if (!argv[i + 1])
301 {
302 exitProcess("Please specify the input filename");
303 }
304 filesFilter.push(argv[i + 1]);
305 break;
306 case "-o":
307 if (!argv[i + 1])
308 {
309 exitProcess("Please specify the output filename");
310 }
311 outputFileName = argv[i + 1];
312 break;
313 case "-i":
314 if (!argv[i + 1])
315 {
316 exitProcess("Please specify the import file");
317 }
318 let importFile = argv[i + 1];
319 importTranslations(importFile);
320 stopExportScript = true;
321 break;
322 }
323 }
324
325 if (!stopExportScript)
326 exportTranslations(filesFilter);
OLDNEW
« README.md ('K') | « README.md ('k') | package.json » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld