Left: | ||
Right: |
LEFT | RIGHT |
---|---|
1 /* | 1 /* |
Thomas Greiner
2018/01/22 19:49:52
While we're waiting for the final results from the
saroyanm
2018/02/28 20:57:33
I'll address this in a separate patch. Moving this
| |
2 * This file is part of Adblock Plus <https://adblockplus.org/>, | 2 * This file is part of Adblock Plus <https://adblockplus.org/>, |
saroyanm
2018/02/28 20:57:34
Moving this file to the buildtools directory still
Thomas Greiner
2018/03/19 18:28:04
What does this have to do with buildtools? I was t
Thomas Greiner
2018/03/19 18:54:13
Mind mentioning this script in the README? Preferr
saroyanm
2018/04/26 17:53:52
Acknowledged, I'll move this to the "build" direct
saroyanm
2018/04/26 17:53:52
Good point. I'll add information in the README as
saroyanm
2018/05/04 13:51:10
Done.
saroyanm
2018/05/04 13:51:10
Done.
| |
3 * Copyright (C) 2006-present eyeo GmbH | 3 * Copyright (C) 2006-present eyeo GmbH |
4 * | 4 * |
5 * Adblock Plus is free software: you can redistribute it and/or modify | 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 | 6 * it under the terms of the GNU General Public License version 3 as |
7 * published by the Free Software Foundation. | 7 * published by the Free Software Foundation. |
8 * | 8 * |
9 * Adblock Plus is distributed in the hope that it will be useful, | 9 * Adblock Plus is distributed in the hope that it will be useful, |
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of | 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of |
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
12 * GNU General Public License for more details. | 12 * GNU General Public License for more details. |
13 * | 13 * |
14 * You should have received a copy of the GNU General Public License | 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/>. | 15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. |
16 */ | 16 */ |
17 | 17 |
18 const fs = require("fs"); | 18 const fs = require("fs"); |
19 const {exec} = require("child_process"); | 19 const {exec} = require("child_process"); |
20 const path = require("path"); | |
21 const csv = require("csv"); | |
22 const {promisify} = require("util"); | |
23 const csvParser = promisify(csv.parse); | |
24 | |
20 | 25 |
21 const localesDir = "locale"; | 26 const localesDir = "locale"; |
22 const defaultLocale = "en_US"; | 27 const defaultLocale = "en_US"; |
23 | 28 |
24 let filesNames = []; // ex.: desktop-options.json | 29 // ex.: desktop-options.json |
Thomas Greiner
2018/01/22 19:49:52
Detail: Usually you'd call this variable "fileName
saroyanm
2018/02/28 20:48:26
Done.
| |
25 let locales = []; // List of all available locale codes | 30 let fileNames = []; |
Thomas Greiner
2018/01/22 19:49:53
Detail: We tend to put comments in their own line
saroyanm
2018/02/28 20:48:25
Done.
| |
31 // List of all available locale codes | |
32 let locales = []; | |
33 | |
26 let headers = ["StringID", "Description", "Placeholders", defaultLocale]; | 34 let headers = ["StringID", "Description", "Placeholders", defaultLocale]; |
27 let outputFileName = "translations-{repo}-{hash}.csv"; | 35 let outputFileName = "translations-{repo}-{hash}.csv"; |
Thomas Greiner
2018/01/22 19:49:53
Detail: This custom template seems redundant since
saroyanm
2018/02/28 20:48:22
We can't pass Template literals using CLI, until I
Thomas Greiner
2018/03/19 18:28:01
This is not a template literal.
What I meant is t
| |
28 | 36 |
29 /** | 37 /** |
30 * Export existing translation files into CSV file | 38 * Export existing translation - files into CSV file |
31 * @param {[type]} filesFilter Optional parameter which allow include only | 39 * @param {string[]} [filesFilter] - fileNames filter, if omitted all files |
Thomas Greiner
2018/01/22 19:49:49
Suggestion: What I tend to do to visually differen
Thomas Greiner
2018/01/22 19:49:50
Detail: No need to include the text "Optional" bec
Thomas Greiner
2018/01/22 19:49:51
Detail: "[type]" is not a valid type.
Also applie
saroyanm
2018/02/28 20:48:24
Right, it's the default value generated by DocBloc
saroyanm
2018/02/28 20:48:27
Done.
saroyanm
2018/02/28 20:48:31
Done.
| |
32 * fileNames in the array, if ommited all files | 40 * will be exported |
Thomas Greiner
2018/01/22 19:49:51
Typo: Replace "ommited" with "omitted"
Also appli
saroyanm
2018/02/28 20:48:30
Done.
| |
33 * will be exported | |
34 */ | 41 */ |
35 function exportTranslations(filesFilter) | 42 function exportTranslations(filesFilter) |
36 { | 43 { |
37 let mercurialCommands = []; | 44 let mercurialCommands = []; |
38 mercurialCommands.push(executeMercurial("hg id -i")); // Get Hash | 45 // Get Hash |
39 mercurialCommands.push(executeMercurial("hg paths default")); // Get repo path | 46 mercurialCommands.push(executeMercurial(["id", "-i"])); |
47 // Get repo path | |
48 mercurialCommands.push(executeMercurial(["paths", "default"])); | |
40 Promise.all(mercurialCommands).then((outputs) => | 49 Promise.all(mercurialCommands).then((outputs) => |
Thomas Greiner
2018/01/22 19:49:50
You've nicely split up each step in the process in
saroyanm
2018/02/28 20:48:23
I have simplified this function, can try to simpli
Thomas Greiner
2018/03/19 18:54:12
That'd be great, thanks. The more we can disconnec
| |
41 { | 50 { |
42 // Remove line endings and "+" sign from the end of the hash | 51 // Remove line endings and "+" sign from the end of the hash |
Thomas Greiner
2018/01/22 19:49:49
Mercurial revision IDs are written in hexadecimal
saroyanm
2018/02/28 20:48:32
I do use "hg id -i" on my local machine and it ret
Thomas Greiner
2018/03/19 18:28:01
According to `hg id --help`:
Print a summary
| |
43 let [hash, path] = outputs.map((item) => item.replace(/\+\n|\n$/, "")); | 52 let [hash, filePath] = outputs.map((item) => item.replace(/\+\n|\n$/, "")); |
Thomas Greiner
2018/01/22 19:49:52
Detail: Seems like you'd want to use `item.trim()`
saroyanm
2018/02/28 20:48:24
If not the "+" sign the trim would have worked her
| |
44 // Update name of the file to be outputted | 53 // Update name of the file to be output |
Thomas Greiner
2018/01/22 19:49:54
Typo: Replace "outputted" with "output"
saroyanm
2018/02/28 20:48:24
Done.
| |
45 outputFileName = outputFileName.replace("{hash}", hash); | 54 outputFileName = outputFileName.replace("{hash}", hash); |
46 outputFileName = outputFileName.replace("{repo}", path.split("/").pop()); | 55 outputFileName = outputFileName.replace("{repo}", path.basename(filePath)); |
Thomas Greiner
2018/01/22 19:49:48
This code is OS-specific so let's instead use Node
saroyanm
2018/02/28 20:48:24
Done.
| |
47 | 56 |
48 // Prepare to read all available locales and default files | 57 // Read all available locales and default files |
49 let readDirectories = []; | 58 return Promise.all([readDir(path.join(localesDir, defaultLocale)), |
Thomas Greiner
2018/01/22 19:49:51
Suggestion: You can avoid this temporary variable
saroyanm
2018/02/28 20:48:28
Done.
|
saroyanm
2018/05/04 13:51:08
I think we should use module like glob -> https://
Thomas Greiner
2018/05/07 15:16:33
Acknowledged.
|
50 readDirectories.push(readDir(`${localesDir}/${defaultLocale}`)); | 59 readDir(localesDir)]); |
Thomas Greiner
2018/01/22 19:49:52
This code is OS-specific so let's instead use Node
saroyanm
2018/02/28 20:48:23
Done.
| |
51 readDirectories.push(readDir(localesDir)); | |
52 return Promise.all(readDirectories); | |
53 }).then((files) => | 60 }).then((files) => |
Thomas Greiner
2018/01/22 19:49:48
Detail: This variable is redundant because you cou
saroyanm
2018/02/28 20:48:32
I think I can't as I assigning the variables to th
Thomas Greiner
2018/03/19 18:28:01
Then you should use a different name for one of th
| |
54 { | 61 { |
55 [filesNames, locales] = files; | 62 [fileNames, locales] = files; |
56 // Filter files | 63 // Filter files |
57 if (filesFilter.length) | 64 if (filesFilter.length) |
58 filesNames = filesNames.filter((item) => filesFilter.includes(item)); | 65 fileNames = fileNames.filter((item) => filesFilter.includes(item)); |
59 | 66 |
60 let readJsonPromises = []; | 67 let readJsonPromises = []; |
61 for(let file of filesNames) | 68 for(let fileName of fileNames) |
Thomas Greiner
2018/01/22 19:49:50
Coding style: Technically, this is not a violation
saroyanm
2018/02/28 20:48:31
Done.
| |
69 { | |
62 for(let locale of locales) | 70 for(let locale of locales) |
63 readJsonPromises.push(readJson(locale, file)); | 71 { |
72 readJsonPromises.push(readJson(locale, fileName)); | |
73 } | |
74 } | |
64 | 75 |
65 // Reading all existing translations files | 76 // Reading all existing translations files |
66 return Promise.all(readJsonPromises); | 77 return Promise.all(readJsonPromises); |
67 }).then((fileObjects) => | 78 }).then(csvFromJsonFileObjects); |
68 { | 79 } |
69 // Create Object tree from the Objects array, for easier search | 80 |
70 // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}} | 81 /** |
71 let dataTreeObj = fileObjects.reduce((acc, fileObject) => | 82 * Creating Matrix which reflects output CSV file |
Thomas Greiner
2018/01/22 19:49:54
Detail: Please use descriptive variable names beca
saroyanm
2018/02/28 20:48:29
Done.
| |
72 { | 83 * @param {Array} fileObjects - array of file objects created by readJson |
73 if (!fileObject) | 84 * @return {Array} Matrix |
74 return acc; | 85 */ |
75 | 86 function csvFromJsonFileObjects(fileObjects) |
76 let filename = fileObject.filename; | 87 { |
77 let locale = fileObject.locale; | 88 // Create Object tree from the Objects array, for easier search |
Thomas Greiner
2018/01/22 19:49:50
Detail: This becomes a bit simpler when using dest
saroyanm
2018/02/28 20:48:31
Done.
| |
78 if (!acc[filename]) | 89 // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}} |
79 { | 90 let dataTreeObj = fileObjects.reduce((accumulator, fileObject) => |
80 acc[filename] = {}; | 91 { |
81 } | 92 if (!fileObject) |
82 acc[filename][locale] = fileObject.strings; | 93 return accumulator; |
83 return acc; | 94 |
84 }, {}); | 95 let {fileName, locale} = fileObject; |
85 | 96 if (!accumulator[fileName]) |
86 // Create two dimentional strings array that reflects CSV structure | 97 { |
Thomas Greiner
2018/01/22 19:49:49
Typo: Replace "dimentional" with "dimensional"
Al
saroyanm
2018/02/28 20:48:25
Done.
| |
87 let localesWithoutDefault = locales.filter((item) => item != defaultLocale); | 98 accumulator[fileName] = {}; |
Thomas Greiner
2018/01/22 19:49:54
Detail: Why do you call it "item" here when you kn
saroyanm
2018/02/28 20:48:31
Done.
| |
88 let csvArray = [headers.concat(localesWithoutDefault)]; | 99 } |
89 for (let file of filesNames) | 100 accumulator[fileName][locale] = fileObject.strings; |
Thomas Greiner
2018/01/22 19:49:53
Detail: "file" is a bit ambiguous since it could r
saroyanm
2018/02/28 20:48:23
Done.
| |
90 { | 101 return accumulator; |
91 csvArray.push([file]); | 102 }, {}); |
92 for (let stringID in dataTreeObj[file][defaultLocale]) | 103 |
93 { | 104 // Create two dimensional strings array that reflects CSV structure |
94 let fileObj = dataTreeObj[file]; | 105 let translationLocales = locales.filter((locale) => locale != defaultLocale); |
95 let stringObj = fileObj[defaultLocale][stringID]; | 106 let csvArray = [headers.concat(translationLocales)]; |
96 let {description, message, placeholders} = stringObj; | 107 for (let fileName of fileNames) |
saroyanm
2018/05/04 13:51:10
I have this information in fileObjects, I shouldn'
Thomas Greiner
2018/05/07 15:16:33
Acknowledged.
| |
97 | 108 { |
98 // Use yaml-like format for easy extraction, rather sensitive char hacks | 109 csvArray.push([fileName]); |
Thomas Greiner
2018/01/22 19:49:54
Instead of going with a custom syntax, we could si
saroyanm
2018/02/28 20:48:32
Done.
| |
99 let yamlPlaceholder = ""; | 110 let strings = dataTreeObj[fileName][defaultLocale]; |
100 for (let placeholder in placeholders) | 111 for (let stringID of Object.keys(strings)) |
101 { | 112 { |
102 yamlPlaceholder += `${placeholder}:\n`; | 113 let fileObj = dataTreeObj[fileName]; |
103 let {content, example} = placeholders[placeholder]; | 114 let {description, message, placeholders} = strings[stringID]; |
104 yamlPlaceholder += ` content: ${content}\n`; | 115 let row = [stringID, description || "", JSON.stringify(placeholders), |
105 yamlPlaceholder += ` example: ${example}\n`; | 116 message]; |
106 } | 117 |
107 | 118 for (let locale of translationLocales) |
108 let row = [stringID, description || "", yamlPlaceholder, message]; | 119 { |
109 for (let locale of localesWithoutDefault) | 120 let localeFileObj = fileObj[locale]; |
110 { | 121 let isTranslated = !!(localeFileObj && localeFileObj[stringID]); |
111 let localeFileObj = fileObj[locale]; | 122 row.push(isTranslated ? localeFileObj[stringID].message : ""); |
112 let isTranslated = localeFileObj && localeFileObj[stringID]; | 123 } |
Thomas Greiner
2018/01/22 19:49:53
Detail: The name "isTranslated" implies that its v
saroyanm
2018/02/28 20:48:26
Done.
| |
113 row.push(isTranslated ? localeFileObj[stringID].message : ""); | 124 csvArray.push(row); |
114 } | 125 } |
115 csvArray.push(row); | 126 } |
116 } | 127 arrayToCsv(csvArray); |
117 } | |
118 arrayToCsv(csvArray); // Convert matrix to CSV | |
119 }); | |
120 } | 128 } |
121 | 129 |
122 /** | 130 /** |
123 * Import strings from the CSV file | 131 * Import strings from the CSV file |
124 * @param {[type]} filePath CSV file path to import from | 132 * @param {string} filePath - CSV file path to import from |
125 */ | 133 */ |
126 function importTranslations(filePath) | 134 function importTranslations(filePath) |
127 { | 135 { |
128 readCsv(filePath).then((fileObjects) => | 136 readFile(filePath).then((fileObjects) => |
129 { | 137 { |
130 let dataMatrix = csvToArray(fileObjects); | 138 return csvParser(fileObjects, {relax_column_count: true}); |
Thomas Greiner
2018/01/22 19:49:51
Let's investigate whether there's a Node module al
saroyanm
2018/02/28 20:48:26
Done, with finding csvToArray module. Haven't thou
|
Thomas Greiner
2018/03/19 18:54:13
Why do we end up with an inconsistent number of co
saroyanm
2018/04/26 17:53:51
Meeting note: We will use new column called filena
saroyanm
2018/05/04 13:51:08
Done.
saroyanm
2018/05/04 13:51:08
Apparently we were generating right amount of comm
|
131 let headers = dataMatrix.splice(0, 1)[0]; | 139 }).then((dataMatrix) => |
Thomas Greiner
2018/01/22 19:49:51
Detail: This is equivalent to `dataMatrix.shift()`
saroyanm
2018/02/28 20:48:30
Done.
| |
140 { | |
141 let headers = dataMatrix.shift(); | |
142 let [headId, headDescription, headPlaceholder, ...headLocales] = headers; | |
132 let dataTreeObj = {}; | 143 let dataTreeObj = {}; |
133 let currentFilename = ""; | 144 let currentFilename = ""; |
134 for(let rowId in dataMatrix) | 145 for(let rowId in dataMatrix) |
135 { | 146 { |
136 let row = dataMatrix[rowId]; | 147 let row = dataMatrix[rowId]; |
137 let [stringId, description, placeholder] = row; | 148 let [stringId, description, placeholder, ...messages] = row; |
138 if (!stringId) | 149 if (!stringId) |
139 continue; | 150 continue; |
140 | 151 |
141 stringId = stringId.trim(); | 152 stringId = stringId.trim(); |
142 if (stringId.endsWith(".json")) // Check if it's the filename row | 153 // Check if it's the filename row |
Thomas Greiner
2018/01/22 19:49:52
A note for later: We probably want to retrieve the
saroyanm
2018/02/28 20:48:22
I agree, but you are right let's first address all
| |
154 if (stringId.endsWith(".json")) | |
143 { | 155 { |
144 currentFilename = stringId; | 156 currentFilename = stringId; |
145 dataTreeObj[currentFilename] = {}; | 157 dataTreeObj[currentFilename] = {}; |
146 continue; | 158 continue; |
147 } | 159 } |
148 | 160 |
149 description = description.trim(); | 161 description = description.trim(); |
150 placeholder = placeholder.trim(); | 162 for (let i = 0; i < headLocales.length; i++) |
151 for (let i = 3; i < headers.length; i++) | 163 { |
Thomas Greiner
2018/01/22 19:49:50
This value depends on how many columns precede the
saroyanm
2018/02/28 20:48:25
Done.
| |
152 { | 164 let locale = headLocales[i].trim(); |
153 let locale = headers[i].trim(); | 165 let message = messages[i].trim(); |
154 let message = row[i].trim(); | |
155 if (!message) | 166 if (!message) |
156 continue; | 167 continue; |
157 | 168 |
158 // Create Object tree from the Objects array, for easier search | 169 // Create Object tree from the Objects array, for easier search |
159 // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}} | 170 // ex.: {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}} |
160 if (!dataTreeObj[currentFilename][locale]) | 171 if (!dataTreeObj[currentFilename][locale]) |
161 dataTreeObj[currentFilename][locale] = {}; | 172 dataTreeObj[currentFilename][locale] = {}; |
162 | 173 |
163 let localeObj = dataTreeObj[currentFilename][locale]; | 174 let localeObj = dataTreeObj[currentFilename][locale]; |
164 localeObj[stringId] = {}; | 175 localeObj[stringId] = {}; |
Thomas Greiner
2018/03/19 18:28:02
Detail: You're referencing `localeObj[stringId]` a
saroyanm
2018/04/26 17:53:52
Acknowledged.
saroyanm
2018/05/04 13:51:09
Done.
| |
165 | 176 |
166 // We keep string descriptions only in default locale files | 177 // We keep string descriptions only in default locale files |
167 if (locale == defaultLocale) | 178 if (locale == defaultLocale) |
168 localeObj[stringId].description = description; | 179 localeObj[stringId].description = description; |
169 | 180 |
170 localeObj[stringId].message = message; | 181 localeObj[stringId].message = message; |
182 | |
171 if (placeholder) | 183 if (placeholder) |
184 localeObj[stringId].placeholders = JSON.parse(placeholder); | |
185 } | |
186 } | |
187 writeJson(dataTreeObj); | |
188 }); | |
189 } | |
190 | |
191 /** | |
192 * Write locale files according to dataTreeObj | |
193 * @param {Object} dataTreeObj - ex.: | |
194 * {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}} | |
195 */ | |
196 function writeJson(dataTreeObj) | |
197 { | |
198 for (let fileName in dataTreeObj) | |
199 { | |
200 for (let locale in dataTreeObj[fileName]) | |
saroyanm
2018/02/28 20:57:34
When writing to the file we should first find a wa
Thomas Greiner
2018/03/19 18:28:04
We cannot rely on the order of object properties b
saroyanm
2018/04/26 17:53:52
Meeting note: This is required, because we don't w
saroyanm
2018/05/04 13:51:11
Done.
| |
201 { | |
202 let filePath = path.join(localesDir, locale, fileName); | |
203 let fileString = JSON.stringify(dataTreeObj[fileName][locale], null, 2); | |
204 | |
205 // Newline at end of file to match Coding Style | |
206 if (locale == defaultLocale) | |
207 fileString += "\n"; | |
208 fs.writeFile(filePath, fileString, "utf8", (err) => | |
172 { | 209 { |
173 let placeholders = placeholder.split("\n"); | 210 if (err) |
174 let placeholderName = ""; | |
175 localeObj[stringId].placeholders = placeholders.reduce((acc, item) => | |
176 { | 211 { |
177 /* | 212 console.error(err); |
178 Placeholders use YAML like syntax in CSV files, ex: | |
179 tracking: | |
180 content: $1 | |
181 example: Block additional tracking | |
182 acceptableAds: | |
183 content: $2 | |
184 example: Allow Acceptable Ads | |
185 */ | |
186 if (item.startsWith(" ")) | |
187 { | |
188 let [key, value] = item.trim().split(":"); | |
189 acc[placeholderName][key] = value.trim(); | |
190 } | |
191 else | |
192 { | |
193 placeholderName = item.trim().replace(":", ""); | |
194 acc[placeholderName] = {}; | |
195 } | |
196 return acc; | |
197 }, {}); | |
198 } | |
199 } | |
200 } | |
201 writeJson(dataTreeObj); | |
202 }); | |
203 } | |
204 | |
205 /** | |
206 * Write locale files according to dataTreeObj which look like: | |
Thomas Greiner
2018/01/22 19:49:49
Detail: There's a redundant "which look like:" in
saroyanm
2018/02/28 20:48:30
Done.
| |
207 * @param {Object} dataTreeObj which look like: | |
208 * {dektop-options.json: {en_US: {...}, {de: {...}, {ru: {...}}} | |
209 */ | |
210 function writeJson(dataTreeObj) | |
211 { | |
212 for (let filename in dataTreeObj) | |
213 { | |
214 for (let locale in dataTreeObj[filename]) | |
215 { | |
216 let path = `${localesDir}/${locale}/${filename}`; | |
217 let fileString = JSON.stringify(dataTreeObj[filename][locale], null, 2); | |
218 fileString += "\n"; // Newline at end of file to match Coding Style | |
219 fs.writeFile(path, fileString, 'utf8', (err)=> | |
Thomas Greiner
2018/01/22 19:49:52
Coding style: "arrow-spacing" ESLint rule violatio
Thomas Greiner
2018/01/22 19:49:54
Coding style: "Double-quoted strings (e.g. "foo")
saroyanm
2018/02/28 20:48:26
Done.
saroyanm
2018/02/28 20:48:30
Done.
| |
220 { | |
221 if (!err) | |
Thomas Greiner
2018/01/22 19:49:54
Detail: It's usually simpler to avoid negation whe
saroyanm
2018/02/28 20:48:31
Done.
| |
222 { | |
223 console.log(`Updated: ${path}`); | |
224 } | 213 } |
225 else | 214 else |
226 { | 215 { |
227 console.log(err); | 216 console.log(`Updated: ${filePath}`); |
Thomas Greiner
2018/01/22 19:49:53
You're outputting an error here so why not use `co
saroyanm
2018/02/28 20:48:27
Done.
| |
228 } | 217 } |
229 }); | 218 }); |
230 } | 219 } |
231 } | 220 } |
232 } | 221 } |
233 | 222 |
234 /** | 223 /** |
235 * Parse CSV string and return array | 224 * Convert two dimensional array to the CSV file |
236 * @param {String} csvText Array to convert from | 225 * @param {string[][]} csvArray - array to convert from |
Thomas Greiner
2018/01/22 19:49:49
Detail: We're writing native types in lower-case i
saroyanm
2018/02/28 20:48:30
Done.
| |
237 * @return {Array} two dimentional array | |
Thomas Greiner
2018/01/22 19:49:50
Detail: We're defining arrays using the alternativ
saroyanm
2018/02/28 20:48:30
Done.
| |
238 */ | |
239 function csvToArray(csvText) | |
240 { | |
241 let previouseChar = ""; | |
Thomas Greiner
2018/01/22 19:49:50
Typo: Replace "previouseChar" with "previousChar".
saroyanm
2018/02/28 20:48:25
Done.
| |
242 let row = []; // Holds parsed CSV data representing a row/line | |
243 let column = 0; // Pointer of the column in the row | |
244 let csvArray = []; // Two dimentional array that holds rows | |
245 let parseSpecialChars = true; // Like comma(,) and quotation(") | |
Thomas Greiner
2018/01/22 19:49:49
I doubt that we want to get involved into sanitizi
saroyanm
2018/02/28 20:48:23
Done.
| |
246 for (let charIndex in csvText) | |
247 { | |
248 currentChar = csvText[charIndex]; | |
249 if (!row[column]) | |
250 row[column] = ""; | |
251 | |
252 if ('"' == currentChar) | |
253 { | |
254 // Double quote is like escaping quote char in CSV | |
255 if (currentChar === previouseChar && parseSpecialChars) | |
256 row[column] += currentChar; | |
257 | |
258 parseSpecialChars = !parseSpecialChars; | |
259 } | |
260 else if (currentChar == "," && parseSpecialChars) | |
261 { | |
262 currentChar = ""; | |
263 column++; // Update columns, because comma(,) separates columns | |
264 } | |
265 else if (currentChar == "\n" && parseSpecialChars) | |
266 { | |
267 if ("\r" === previouseChar) // In case of \r\n | |
268 row[column] = row[column].slice(0, -1); | |
269 | |
270 csvArray.push(row); | |
271 // Reset pointers for the new row | |
272 row = []; | |
273 column = 0; | |
274 currentChar = ""; | |
275 } | |
276 else | |
277 { | |
278 row[column] += currentChar; | |
279 } | |
280 previouseChar = currentChar; | |
281 } | |
282 csvArray.push(row); | |
283 return csvArray; | |
284 } | |
285 | |
286 | |
287 /** | |
288 * Convert two dimentional array to the CSV file | |
289 * @param {Array} csvArray Array to convert from | |
290 */ | 226 */ |
291 function arrayToCsv(csvArray) | 227 function arrayToCsv(csvArray) |
292 { | 228 { |
293 let dataToWrite = ""; | 229 csv.stringify(csvArray, (err, output) => |
294 for (let row of csvArray) | 230 { |
295 { | 231 fs.writeFile(outputFileName, output, "utf8", function (err) |
Thomas Greiner
2018/03/19 18:28:03
Coding style: `function (err)` violates the follow
saroyanm
2018/04/26 17:53:51
Acknowledged.
saroyanm
2018/05/04 13:51:08
Done.
| |
296 let columnString = row.reduce((accum, col) => | 232 { |
297 { | 233 if (!err) |
298 // Escape single quote with quote before | 234 console.log(`${outputFileName} is created`); |
Thomas Greiner
2018/03/19 18:28:04
We should only ignore errors in exceptional cases.
saroyanm
2018/04/26 17:53:51
Acknowledged.
saroyanm
2018/05/04 13:51:07
Done.
| |
299 accum += `","${col.replace(/\"/g, '""')}`; | 235 }); |
300 return accum; | |
301 }); | |
302 dataToWrite += `"${columnString}"\r\n`; | |
303 } | |
304 dataToWrite += "\r\n"; | |
305 fs.writeFile(outputFileName, dataToWrite, "utf8", function (err) | |
306 { | |
307 if (!err) | |
308 console.log(`${outputFileName} is created`); | |
309 }); | 236 }); |
310 } | 237 } |
311 | 238 |
312 /** | 239 /** |
313 * Reads JSON file and assign filename and locale to it | 240 * Reads JSON file and assign filename and locale to it |
314 * @param {String} locale ex.: "en_US", "de"... | 241 * @param {string} locale - ex.: "en_US", "de"... |
315 * @param {String} fileName ex.: "desktop-options.json" | 242 * @param {string} file - ex.: "desktop-options.json" |
Thomas Greiner
2018/03/19 18:28:04
Detail: Again, "file" is not what you call it in t
saroyanm
2018/05/04 13:51:07
Done.
| |
316 * @return {Promise} Promise object | 243 * @return {Promise<Object>} fileName, locale and Strings of locale file |
Thomas Greiner
2018/01/22 19:49:51
Detail: This is very non-descriptive because it co
saroyanm
2018/02/28 20:48:32
Done.
|
Thomas Greiner
2018/03/19 18:28:03
Typo: Replace "Strings" with "strings"
saroyanm
2018/05/04 13:51:10
Done.
|
317 */ | 244 */ |
318 function readJson(locale, file) | 245 function readJson(locale, fileName) |
Thomas Greiner
2018/01/22 19:49:51
Detail: "file" is not what you call it in the JSDo
saroyanm
2018/02/28 20:48:26
Done.
| |
319 { | 246 { |
320 let path = `${localesDir}/${locale}/${file}`; | |
Thomas Greiner
2018/01/22 19:49:49
Detail: This variable is only being used once beca
saroyanm
2018/02/28 20:48:25
We are already using path module here, so I think
Thomas Greiner
2018/03/19 18:28:01
Acknowledged.
| |
321 return new Promise((resolve, reject) => | 247 return new Promise((resolve, reject) => |
322 { | 248 { |
323 fs.readFile(path, (err, data) => { | 249 let filePath = path.join(localesDir, locale, fileName); |
Thomas Greiner
2018/01/22 19:49:52
Coding style: "Opening braces always go on their o
saroyanm
2018/02/28 20:48:27
Done.
| |
250 fs.readFile(filePath, (err, data) => | |
251 { | |
324 if (err) | 252 if (err) |
325 { | 253 { |
326 reject(err); | 254 reject(err); |
327 } | 255 } |
328 else | 256 else |
329 { | 257 { |
330 let json = {}; | 258 resolve({fileName, locale, strings: JSON.parse(data)}); |
331 json.filename = file; | 259 } |
332 json.locale = locale; | 260 }); |
333 json.strings = JSON.parse(data); | 261 // Continue Promise.All even if rejected. |
Thomas Greiner
2018/03/19 18:28:02
Detail: Why? Not being able to read from a JSON fi
saroyanm
2018/05/04 13:51:11
Done, beforehand I was using locales and filenames
| |
334 resolve(json); | 262 }).catch(reason => {}); |
Thomas Greiner
2018/01/22 19:49:50
Detail: Let's simplify this a bit and avoid this t
saroyanm
2018/02/28 20:48:32
Done.
| |
335 } | 263 } |
336 }); | 264 |
337 }).catch(reason => // Continue Promise.All even if rejected. | 265 /** |
Thomas Greiner
2018/01/22 19:49:52
This function should not be aware of where it's ca
saroyanm
2018/02/28 20:48:24
Not sure if it's yet necessary, while we are not o
| |
338 { | 266 * Reads file |
339 // Commented out log not to spam the output. | 267 * @param {string} filePath |
340 // TODO: Think about more meaningful output without spaming | 268 * @return {Promise<Object>} contents of file in given location |
341 // console.log(`Reading ${path} was rejected: ${reason}`); | 269 */ |
Thomas Greiner
2018/01/22 19:49:49
Coding style: "Don't leave debug printfs or dumps
saroyanm
2018/02/28 20:48:28
Done.
| |
342 }); | 270 function readFile(filePath) |
343 } | |
344 | |
345 /** | |
346 * Reads CSV file | |
347 * @param {String} file path | |
348 * @return {Promise} Promise object | |
349 */ | |
350 function readCsv(filePath) | |
Thomas Greiner
2018/01/22 19:49:51
This name is a bit misleading since it reads any f
saroyanm
2018/02/28 20:48:28
Done.
| |
351 { | 271 { |
352 return new Promise((resolve, reject) => | 272 return new Promise((resolve, reject) => |
353 { | 273 { |
354 fs.readFile(filePath, "utf8", (err, data) => { | 274 fs.readFile(filePath, "utf8", (err, data) => |
275 { | |
355 if (err) | 276 if (err) |
356 reject(err); | 277 reject(err); |
357 else | 278 else |
358 resolve(data); | 279 resolve(data); |
359 }); | 280 }); |
360 }); | 281 }); |
361 } | 282 } |
362 | 283 |
363 /** | 284 /** |
364 * Read files and folder names inside of the directory | 285 * Read files and folder names inside of the directory |
365 * @param {String} dir patch of the folder | 286 * @param {string} dir - path of the folder |
Thomas Greiner
2018/01/22 19:49:53
Typo: Replace "patch" with "path"
saroyanm
2018/02/28 20:48:25
Done.
| |
366 * @return {Promise} Promise object | 287 * @return {Promise<Object>} array of folders |
Thomas Greiner
2018/03/19 18:28:03
Detail: The return type is `Promise<string[]>`.
Thomas Greiner
2018/03/19 18:28:03
Suggestion: Technically, those can be either folde
saroyanm
2018/05/04 13:51:09
Irrelevant in the new patch.
| |
367 */ | 288 */ |
368 function readDir(dir) | 289 function readDir(dir) |
Thomas Greiner
2018/03/19 18:28:04
Suggestion: You could avoid having to write such f
saroyanm
2018/04/26 17:53:52
Agree.
saroyanm
2018/05/04 13:51:07
Done.
| |
369 { | 290 { |
370 return new Promise((resolve, reject) => | 291 return new Promise((resolve, reject) => |
371 { | 292 { |
372 fs.readdir(dir, (err, folders) => { | 293 fs.readdir(dir, (err, folders) => |
294 { | |
373 if (err) | 295 if (err) |
374 reject(err); | 296 reject(err); |
375 else | 297 else |
376 resolve(folders); | 298 resolve(folders); |
377 }); | 299 }); |
378 }); | 300 }); |
379 } | 301 } |
380 | 302 |
381 /** | 303 /** |
382 * Executing mercurial commands on the system level | 304 * Executing mercurial commands on the system level |
383 * @param {String} command mercurial command ex.:"hg ..." | 305 * @param {string} command - mercurial command ex.:"hg ..." |
384 * @return {Promise} Promise object containing output from the command | 306 * @return {Promise<Object>} output of the command |
385 */ | 307 */ |
386 function executeMercurial(command) | 308 function executeMercurial(commands) |
387 { | 309 { |
388 // Limit only to Mercurial commands to minimize the missuse risk | |
389 if (command.substring(0, 3) !== "hg ") | |
390 { | |
391 console.error("You are only allowed to run Mercurial commands('hg ...')"); | |
Thomas Greiner
2018/01/22 19:49:53
Why do you allow to pass arbitrary commands if you
saroyanm
2018/02/28 20:48:30
Agree, done.
| |
392 return; | |
393 } | |
394 | |
395 return new Promise((resolve, reject) => | 310 return new Promise((resolve, reject) => |
396 { | 311 { |
397 exec(command, (err, output) => | 312 exec(`hg ${commands.join(" ")}`, (err, output) => |
Thomas Greiner
2018/03/19 18:28:04
Detail: `child_process.execFile()` already does wh
saroyanm
2018/05/04 13:51:08
Done.
| |
398 { | 313 { |
399 if (err) | 314 if (err) |
400 reject(err); | 315 reject(err); |
401 else | 316 else |
402 resolve(output); | 317 resolve(output); |
403 }); | 318 }); |
404 }); | 319 }); |
405 } | 320 } |
406 | 321 |
407 // CLI | 322 // CLI |
408 let helpText = ` | 323 let helpText = ` |
409 About: This script exports locales into .csv format | 324 About: Converts locale files between CSV and JSON formats |
Thomas Greiner
2018/01/22 19:49:48
It can also export locales into JSON format so why
saroyanm
2018/02/28 20:48:27
Done.
| |
410 Usage: node csv-export.js [option] [argument] | 325 Usage: csv-export.js [option] [argument] |
Thomas Greiner
2018/01/22 19:49:51
Detail: AFAIK it's not common to prefix scripts wi
saroyanm
2018/02/28 20:48:24
Done.
| |
411 Options: | 326 Options: |
412 -f Name of the files to be exported ex.: -f firstRun.json | 327 -f [FILENAME] Name of the files to be exported ex.: -f firstRun.json |
Thomas Greiner
2018/01/22 19:49:49
Only writing "-f" makes it look like it's a binary
saroyanm
2018/02/28 20:48:27
Done.
| |
413 option can be used multiple timeString. | 328 option can be used multiple times. |
Thomas Greiner
2018/01/22 19:49:49
Typo: Replace "timeString" with "times".
saroyanm
2018/02/28 20:48:31
Done.
| |
414 If ommited all files are being exported | 329 If omitted all files are being exported |
415 | 330 |
416 -o Output filename ex.: | 331 -o [FILENAME] Output filename ex.: |
417 -f firstRun.json -o {hash}-firstRun.csv | 332 -f firstRun.json -o {hash}-firstRun.csv |
Thomas Greiner
2018/03/19 18:28:02
Detail: Be careful when passing arguments like tha
saroyanm
2018/05/04 13:51:10
Not sure I understand the comment. I'm not passing
Thomas Greiner
2018/05/07 15:16:33
I'm referring to the CLI argument `-o {hash}-first
| |
418 Placeholders: | 333 Placeholders: |
419 {hash} - Mercurial current revision hash | 334 {hash} - Mercurial current revision hash |
420 {repo} - Name of the "Default" repository | 335 {repo} - Name of the "Default" repository |
Thomas Greiner
2018/01/22 19:49:50
I wouldn't know what "default repository" refers t
saroyanm
2018/02/28 20:48:27
It's the name of the repository set as default in
Thomas Greiner
2018/03/19 18:28:01
Then why not add that to the description? For exam
| |
421 If ommited the output fileName is set to | 336 If omitted the output fileName is set to |
422 translations-{repo}-{hash}.csv | 337 translations-{repo}-{hash}.csv |
423 | 338 |
424 -i Import file path ex: -i issue-reporter.csv | 339 -i [FILENAME] Import file path ex: -i issue-reporter.csv |
Thomas Greiner
2018/01/22 19:49:51
From what I see, there are two parameters for spec
saroyanm
2018/02/28 20:48:29
It's suppose to be used with "-f" or without, but
Thomas Greiner
2018/03/19 18:28:01
Ok, let's tackle this separately.
| |
425 `; | 340 `; |
426 | 341 |
427 let arguments = process.argv.slice(2); | 342 let arguments = process.argv.slice(2); |
428 let stopExportScript = false; | 343 let stopExportScript = false; |
429 let filesFilter = []; // Filter to be used export to the fileNames inside | 344 // Filter to be used export to the fileNames inside |
345 let filesFilter = []; | |
430 | 346 |
431 for (let i = 0; i < arguments.length; i++) | 347 for (let i = 0; i < arguments.length; i++) |
432 { | 348 { |
433 switch (arguments[i]) | 349 switch (arguments[i]) |
434 { | 350 { |
435 case "-h": | 351 case "-h": |
436 console.log(helpText); | 352 console.log(helpText); |
437 stopExportScript = true; | 353 stopExportScript = true; |
438 break; | 354 break; |
439 case "-f": | 355 case "-f": |
440 if (!arguments[i + 1]) // check if argument following option is specified | 356 // check if argument following option is specified |
441 { | 357 if (!arguments[i + 1]) |
442 console.error("Please specify the input filename"); | 358 { |
443 stopExportScript = true; | 359 process.exit("Please specify the input filename"); |
Thomas Greiner
2018/01/22 19:49:52
In Node you can stop the process via `process.exit
saroyanm
2018/02/28 20:48:23
Done, I think the code will become clearer if I se
|
Thomas Greiner
2018/03/19 18:28:04
This is not how you call `process.exit()`.
See ht
saroyanm
2018/05/04 13:51:10
Done.
|
444 } | 360 } |
445 else | 361 else |
446 { | 362 { |
447 filesFilter.push(arguments[i + 1]); | 363 filesFilter.push(arguments[i + 1]); |
448 } | 364 } |
449 break; | 365 break; |
450 case "-o": | 366 case "-o": |
451 if (!arguments[i + 1]) | 367 if (!arguments[i + 1]) |
452 { | 368 { |
453 console.error("Please specify the output filename"); | 369 process.exit("Please specify the output filename"); |
454 stopExportScript = true; | |
455 } | 370 } |
456 else | 371 else |
457 { | 372 { |
458 outputFileName = arguments[i + 1]; | 373 outputFileName = arguments[i + 1]; |
459 } | 374 } |
460 break; | 375 break; |
461 case "-i": | 376 case "-i": |
462 if (!arguments[i + 1]) | 377 if (!arguments[i + 1]) |
463 { | 378 { |
464 console.error("Please specify the input filename"); | 379 process.exit("Please specify the import file"); |
465 } | 380 } |
466 else | 381 else |
467 { | 382 { |
468 let importFile = arguments[i + 1]; | 383 let importFile = arguments[i + 1]; |
469 importTranslations(importFile); | 384 importTranslations(importFile); |
470 } | 385 stopExportScript = true; |
471 stopExportScript = true; | 386 } |
472 break; | 387 break; |
473 } | 388 } |
474 } | 389 } |
475 | 390 |
476 if (!stopExportScript) | 391 if (!stopExportScript) |
477 exportTranslations(filesFilter); | 392 exportTranslations(filesFilter); |
LEFT | RIGHT |