Index: csv-export.js |
=================================================================== |
new file mode 100644 |
--- /dev/null |
+++ b/csv-export.js |
@@ -0,0 +1,392 @@ |
+/* |
+ * This file is part of Adblock Plus <https://adblockplus.org/>, |
+ * Copyright (C) 2006-present eyeo GmbH |
+ * |
+ * Adblock Plus is free software: you can redistribute it and/or modify |
+ * it under the terms of the GNU General Public License version 3 as |
+ * published by the Free Software Foundation. |
+ * |
+ * Adblock Plus is distributed in the hope that it will be useful, |
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of |
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
+ * GNU General Public License for more details. |
+ * |
+ * You should have received a copy of the GNU General Public License |
+ * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. |
+ */ |
+ |
+const fs = require("fs"); |
+const {exec} = require("child_process"); |
+const path = require("path"); |
+const csv = require("csv"); |
+const {promisify} = require("util"); |
+const csvParser = promisify(csv.parse); |
+ |
+ |
+const localesDir = "locale"; |
+const defaultLocale = "en_US"; |
+ |
+// ex.: desktop-options.json |
+let fileNames = []; |
+// List of all available locale codes |
+let locales = []; |
+ |
+let headers = ["StringID", "Description", "Placeholders", defaultLocale]; |
+let outputFileName = "translations-{repo}-{hash}.csv"; |
+ |
+/** |
+ * Export existing translation - files into CSV file |
+ * @param {string[]} [filesFilter] - fileNames filter, if omitted all files |
+ * will be exported |
+ */ |
+function exportTranslations(filesFilter) |
+{ |
+ let mercurialCommands = []; |
+ // Get Hash |
+ mercurialCommands.push(executeMercurial(["id", "-i"])); |
+ // Get repo path |
+ mercurialCommands.push(executeMercurial(["paths", "default"])); |
+ Promise.all(mercurialCommands).then((outputs) => |
+ { |
+ // Remove line endings and "+" sign from the end of the hash |
+ let [hash, filePath] = outputs.map((item) => item.replace(/\+\n|\n$/, "")); |
+ // Update name of the file to be output |
+ outputFileName = outputFileName.replace("{hash}", hash); |
+ outputFileName = outputFileName.replace("{repo}", path.basename(filePath)); |
+ |
+ // Read all available locales and default files |
+ return Promise.all([readDir(path.join(localesDir, defaultLocale)), |
+ readDir(localesDir)]); |
+ }).then((files) => |
+ { |
+ [fileNames, locales] = files; |
+ // Filter files |
+ if (filesFilter.length) |
+ fileNames = fileNames.filter((item) => filesFilter.includes(item)); |
+ |
+ let readJsonPromises = []; |
+ for(let fileName of fileNames) |
+ { |
+ for(let locale of locales) |
+ { |
+ readJsonPromises.push(readJson(locale, fileName)); |
+ } |
+ } |
+ |
+ // Reading all existing translations files |
+ return Promise.all(readJsonPromises); |
+ }).then(csvFromJsonFileObjects); |
+} |
+ |
+/** |
+ * Creating Matrix which reflects output CSV file |
+ * @param {Array} fileObjects - array of file objects created by readJson |
+ * @return {Array} Matrix |
+ */ |
+function csvFromJsonFileObjects(fileObjects) |
+{ |
+ // Create Object tree from the Objects array, for easier search |
+ // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}} |
+ let dataTreeObj = fileObjects.reduce((accumulator, fileObject) => |
+ { |
+ if (!fileObject) |
+ return accumulator; |
+ |
+ let {fileName, locale} = fileObject; |
+ if (!accumulator[fileName]) |
+ { |
+ accumulator[fileName] = {}; |
+ } |
+ accumulator[fileName][locale] = fileObject.strings; |
+ return accumulator; |
+ }, {}); |
+ |
+ // Create two dimensional strings array that reflects CSV structure |
+ let translationLocales = locales.filter((locale) => locale != defaultLocale); |
+ let csvArray = [headers.concat(translationLocales)]; |
+ for (let fileName of fileNames) |
+ { |
+ csvArray.push([fileName]); |
+ let strings = dataTreeObj[fileName][defaultLocale]; |
+ for (let stringID of Object.keys(strings)) |
+ { |
+ let fileObj = dataTreeObj[fileName]; |
+ let {description, message, placeholders} = strings[stringID]; |
+ let row = [stringID, description || "", JSON.stringify(placeholders), |
+ message]; |
+ |
+ for (let locale of translationLocales) |
+ { |
+ let localeFileObj = fileObj[locale]; |
+ let isTranslated = !!(localeFileObj && localeFileObj[stringID]); |
+ row.push(isTranslated ? localeFileObj[stringID].message : ""); |
+ } |
+ csvArray.push(row); |
+ } |
+ } |
+ arrayToCsv(csvArray); |
+} |
+ |
+/** |
+ * Import strings from the CSV file |
+ * @param {string} filePath - CSV file path to import from |
+ */ |
+function importTranslations(filePath) |
+{ |
+ readFile(filePath).then((fileObjects) => |
+ { |
+ return csvParser(fileObjects, {relax_column_count: true}); |
+ }).then((dataMatrix) => |
+ { |
+ let headers = dataMatrix.shift(); |
+ let [headId, headDescription, headPlaceholder, ...headLocales] = headers; |
+ let dataTreeObj = {}; |
+ let currentFilename = ""; |
+ for(let rowId in dataMatrix) |
+ { |
+ let row = dataMatrix[rowId]; |
+ let [stringId, description, placeholder, ...messages] = row; |
+ if (!stringId) |
+ continue; |
+ |
+ stringId = stringId.trim(); |
+ // Check if it's the filename row |
+ if (stringId.endsWith(".json")) |
+ { |
+ currentFilename = stringId; |
+ dataTreeObj[currentFilename] = {}; |
+ continue; |
+ } |
+ |
+ description = description.trim(); |
+ for (let i = 0; i < headLocales.length; i++) |
+ { |
+ let locale = headLocales[i].trim(); |
+ let message = messages[i].trim(); |
+ if (!message) |
+ continue; |
+ |
+ // Create Object tree from the Objects array, for easier search |
+ // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}} |
+ if (!dataTreeObj[currentFilename][locale]) |
+ dataTreeObj[currentFilename][locale] = {}; |
+ |
+ let localeObj = dataTreeObj[currentFilename][locale]; |
+ localeObj[stringId] = {}; |
+ |
+ // We keep string descriptions only in default locale files |
+ if (locale == defaultLocale) |
+ localeObj[stringId].description = description; |
+ |
+ localeObj[stringId].message = message; |
+ |
+ if (placeholder) |
+ localeObj[stringId].placeholders = JSON.parse(placeholder); |
+ } |
+ } |
+ writeJson(dataTreeObj); |
+ }); |
+} |
+ |
+/** |
+ * Write locale files according to dataTreeObj |
+ * @param {Object} dataTreeObj - ex.: |
+ * {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}} |
+ */ |
+function writeJson(dataTreeObj) |
+{ |
+ for (let fileName in dataTreeObj) |
+ { |
+ for (let locale in dataTreeObj[fileName]) |
+ { |
+ let filePath = path.join(localesDir, locale, fileName); |
+ let fileString = JSON.stringify(dataTreeObj[fileName][locale], null, 2); |
+ |
+ // Newline at end of file to match Coding Style |
+ if (locale == defaultLocale) |
+ fileString += "\n"; |
+ fs.writeFile(filePath, fileString, "utf8", (err) => |
+ { |
+ if (err) |
+ { |
+ console.error(err); |
+ } |
+ else |
+ { |
+ console.log(`Updated: ${filePath}`); |
+ } |
+ }); |
+ } |
+ } |
+} |
+ |
+/** |
+ * Convert two dimensional array to the CSV file |
+ * @param {string[][]} csvArray - array to convert from |
+ */ |
+function arrayToCsv(csvArray) |
+{ |
+ csv.stringify(csvArray, (err, output) => |
+ { |
+ fs.writeFile(outputFileName, output, "utf8", function (err) |
+ { |
+ if (!err) |
+ console.log(`${outputFileName} is created`); |
+ }); |
+ }); |
+} |
+ |
+/** |
+ * Reads JSON file and assign filename and locale to it |
+ * @param {string} locale - ex.: "en_US", "de"... |
+ * @param {string} file - ex.: "desktop-options.json" |
+ * @return {Promise<Object>} fileName, locale and Strings of locale file |
+ */ |
+function readJson(locale, fileName) |
+{ |
+ return new Promise((resolve, reject) => |
+ { |
+ let filePath = path.join(localesDir, locale, fileName); |
+ fs.readFile(filePath, (err, data) => |
+ { |
+ if (err) |
+ { |
+ reject(err); |
+ } |
+ else |
+ { |
+ resolve({fileName, locale, strings: JSON.parse(data)}); |
+ } |
+ }); |
+ // Continue Promise.All even if rejected. |
+ }).catch(reason => {}); |
+} |
+ |
+/** |
+ * Reads file |
+ * @param {string} filePath |
+ * @return {Promise<Object>} contents of file in given location |
+ */ |
+function readFile(filePath) |
+{ |
+ return new Promise((resolve, reject) => |
+ { |
+ fs.readFile(filePath, "utf8", (err, data) => |
+ { |
+ if (err) |
+ reject(err); |
+ else |
+ resolve(data); |
+ }); |
+ }); |
+} |
+ |
+/** |
+ * Read files and folder names inside of the directory |
+ * @param {string} dir - path of the folder |
+ * @return {Promise<Object>} array of folders |
+ */ |
+function readDir(dir) |
+{ |
+ return new Promise((resolve, reject) => |
+ { |
+ fs.readdir(dir, (err, folders) => |
+ { |
+ if (err) |
+ reject(err); |
+ else |
+ resolve(folders); |
+ }); |
+ }); |
+} |
+ |
+/** |
+ * Executing mercurial commands on the system level |
+ * @param {string} command - mercurial command ex.:"hg ..." |
+ * @return {Promise<Object>} output of the command |
+ */ |
+function executeMercurial(commands) |
+{ |
+ return new Promise((resolve, reject) => |
+ { |
+ exec(`hg ${commands.join(" ")}`, (err, output) => |
+ { |
+ if (err) |
+ reject(err); |
+ else |
+ resolve(output); |
+ }); |
+ }); |
+} |
+ |
+// CLI |
+let helpText = ` |
+About: Converts locale files between CSV and JSON formats |
+Usage: csv-export.js [option] [argument] |
+Options: |
+ -f [FILENAME] Name of the files to be exported ex.: -f firstRun.json |
+ option can be used multiple times. |
+ If omitted all files are being exported |
+ |
+ -o [FILENAME] Output filename ex.: |
+ -f firstRun.json -o {hash}-firstRun.csv |
+ Placeholders: |
+ {hash} - Mercurial current revision hash |
+ {repo} - Name of the "Default" repository |
+ If omitted the output fileName is set to |
+ translations-{repo}-{hash}.csv |
+ |
+ -i [FILENAME] Import file path ex: -i issue-reporter.csv |
+`; |
+ |
+let arguments = process.argv.slice(2); |
+let stopExportScript = false; |
+// Filter to be used export to the fileNames inside |
+let filesFilter = []; |
+ |
+for (let i = 0; i < arguments.length; i++) |
+{ |
+ switch (arguments[i]) |
+ { |
+ case "-h": |
+ console.log(helpText); |
+ stopExportScript = true; |
+ break; |
+ case "-f": |
+ // check if argument following option is specified |
+ if (!arguments[i + 1]) |
+ { |
+ process.exit("Please specify the input filename"); |
+ } |
+ else |
+ { |
+ filesFilter.push(arguments[i + 1]); |
+ } |
+ break; |
+ case "-o": |
+ if (!arguments[i + 1]) |
+ { |
+ process.exit("Please specify the output filename"); |
+ } |
+ else |
+ { |
+ outputFileName = arguments[i + 1]; |
+ } |
+ break; |
+ case "-i": |
+ if (!arguments[i + 1]) |
+ { |
+ process.exit("Please specify the import file"); |
+ } |
+ else |
+ { |
+ let importFile = arguments[i + 1]; |
+ importTranslations(importFile); |
+ stopExportScript = true; |
+ } |
+ break; |
+ } |
+} |
+ |
+if (!stopExportScript) |
+ exportTranslations(filesFilter); |