Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 1 | // Copyright 2019 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | const fs = require('fs'); |
| 6 | const md5 = require('./md5'); |
| 7 | const {promisify} = require('util'); |
| 8 | const path = require('path'); |
| 9 | const readFileAsync = promisify(fs.readFile); |
| 10 | const readDirAsync = promisify(fs.readdir); |
| 11 | const statAsync = promisify(fs.stat); |
Mandy Chen | 5128cc6 | 2019-09-23 16:46:00 +0000 | [diff] [blame] | 12 | const writeFileAsync = promisify(fs.writeFile); |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 13 | |
| 14 | const esprimaTypes = { |
| 15 | BI_EXPR: 'BinaryExpression', |
| 16 | CALL_EXPR: 'CallExpression', |
| 17 | COND_EXPR: 'ConditionalExpression', |
| 18 | IDENTIFIER: 'Identifier', |
| 19 | LITERAL: 'Literal', |
| 20 | MEMBER_EXPR: 'MemberExpression', |
Mandy Chen | 7a8829b | 2019-06-25 22:13:07 +0000 | [diff] [blame] | 21 | NEW_EXPR: 'NewExpression', |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 22 | TAGGED_TEMP_EXPR: 'TaggedTemplateExpression', |
| 23 | TEMP_LITERAL: 'TemplateLiteral' |
| 24 | }; |
| 25 | |
Paul Irish | e7b977e | 2019-09-25 12:23:38 +0000 | [diff] [blame] | 26 | const excludeFiles = ['Tests.js']; |
| 27 | const excludeDirs = ['test_runner', 'Images', 'langpacks', 'node_modules', 'lighthouse']; |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 28 | const cppSpecialCharactersMap = { |
| 29 | '"': '\\"', |
| 30 | '\\': '\\\\', |
| 31 | '\n': '\\n' |
| 32 | }; |
| 33 | const IDSPrefix = 'IDS_DEVTOOLS_'; |
| 34 | |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame^] | 35 | const SRC_PATH = path.resolve(__dirname, '..', '..'); |
| 36 | const GRD_PATH = path.resolve(SRC_PATH, 'front_end', 'langpacks', 'devtools_ui_strings.grd'); |
Mandy Chen | 1e9d87b | 2019-09-18 17:18:15 +0000 | [diff] [blame] | 37 | const SHARED_STRINGS_PATH = path.resolve(__dirname, '..', '..', 'front_end', 'langpacks', 'shared_strings.grdp'); |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame^] | 38 | const NODE_MODULES_PATH = path.resolve(SRC_PATH, 'node_modules'); |
| 39 | const escodegen = require(path.resolve(NODE_MODULES_PATH, 'escodegen')); |
| 40 | const esprima = require(path.resolve(NODE_MODULES_PATH, 'esprima')); |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 41 | |
| 42 | function getRelativeFilePathFromSrc(filePath) { |
| 43 | return path.relative(SRC_PATH, filePath); |
| 44 | } |
| 45 | |
| 46 | function shouldParseDirectory(directoryName) { |
| 47 | return !excludeDirs.some(dir => directoryName.includes(dir)); |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * @filepath can be partial path or full path, as long as it contains the file name. |
| 52 | */ |
| 53 | function shouldParseFile(filepath) { |
| 54 | return !excludeFiles.includes(path.basename(filepath)); |
| 55 | } |
| 56 | |
| 57 | async function parseFileContent(filePath) { |
| 58 | const fileContent = await readFileAsync(filePath); |
| 59 | return fileContent.toString(); |
| 60 | } |
| 61 | |
| 62 | function isNodeCallOnObject(node, objectName, propertyName) { |
| 63 | return node !== undefined && node.type === esprimaTypes.CALL_EXPR && |
| 64 | verifyCallExpressionCallee(node.callee, objectName, propertyName); |
| 65 | } |
| 66 | |
| 67 | function isNodeCommonUIStringCall(node) { |
| 68 | return isNodeCallOnObject(node, 'Common', 'UIString'); |
| 69 | } |
| 70 | |
Mandy Chen | 7a8829b | 2019-06-25 22:13:07 +0000 | [diff] [blame] | 71 | function isNodeCommonUIStringFormat(node) { |
| 72 | return node && node.type === esprimaTypes.NEW_EXPR && |
| 73 | verifyCallExpressionCallee(node.callee, 'Common', 'UIStringFormat'); |
| 74 | } |
| 75 | |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 76 | function isNodeUIformatLocalized(node) { |
| 77 | return isNodeCallOnObject(node, 'UI', 'formatLocalized'); |
| 78 | } |
| 79 | |
| 80 | function isNodelsTaggedTemplateExpression(node) { |
| 81 | return node !== undefined && node.type === esprimaTypes.TAGGED_TEMP_EXPR && verifyIdentifier(node.tag, 'ls') && |
| 82 | node.quasi !== undefined && node.quasi.type !== undefined && node.quasi.type === esprimaTypes.TEMP_LITERAL; |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Verify callee of objectName.propertyName(), e.g. Common.UIString(). |
| 87 | */ |
| 88 | function verifyCallExpressionCallee(callee, objectName, propertyName) { |
| 89 | return callee !== undefined && callee.type === esprimaTypes.MEMBER_EXPR && callee.computed === false && |
| 90 | verifyIdentifier(callee.object, objectName) && verifyIdentifier(callee.property, propertyName); |
| 91 | } |
| 92 | |
| 93 | function verifyIdentifier(node, name) { |
| 94 | return node !== undefined && node.type === esprimaTypes.IDENTIFIER && node.name === name; |
| 95 | } |
| 96 | |
| 97 | function getLocalizationCase(node) { |
| 98 | if (isNodeCommonUIStringCall(node)) |
| 99 | return 'Common.UIString'; |
Mandy Chen | 7a8829b | 2019-06-25 22:13:07 +0000 | [diff] [blame] | 100 | else if (isNodeCommonUIStringFormat(node)) |
| 101 | return 'Common.UIStringFormat'; |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 102 | else if (isNodelsTaggedTemplateExpression(node)) |
| 103 | return 'Tagged Template'; |
| 104 | else if (isNodeUIformatLocalized(node)) |
| 105 | return 'UI.formatLocalized'; |
| 106 | else |
| 107 | return null; |
| 108 | } |
| 109 | |
| 110 | function isLocalizationCall(node) { |
| 111 | return isNodeCommonUIStringCall(node) || isNodelsTaggedTemplateExpression(node) || isNodeUIformatLocalized(node); |
| 112 | } |
| 113 | |
| 114 | /** |
| 115 | * Verify if callee is functionName() or object.functionName(). |
| 116 | */ |
| 117 | function verifyFunctionCallee(callee, functionName) { |
| 118 | return callee !== undefined && |
| 119 | ((callee.type === esprimaTypes.IDENTIFIER && callee.name === functionName) || |
| 120 | (callee.type === esprimaTypes.MEMBER_EXPR && verifyIdentifier(callee.property, functionName))); |
| 121 | } |
| 122 | |
| 123 | function getLocationMessage(location) { |
| 124 | if (location !== undefined && location.start !== undefined && location.end !== undefined && |
| 125 | location.start.line !== undefined && location.end.line !== undefined) { |
| 126 | const startLine = location.start.line; |
| 127 | const endLine = location.end.line; |
| 128 | if (startLine === endLine) |
| 129 | return ` Line ${startLine}`; |
| 130 | else |
| 131 | return ` Line ${location.start.line}-${location.end.line}`; |
| 132 | } |
| 133 | return ''; |
| 134 | } |
| 135 | |
| 136 | function sanitizeStringIntoGRDFormat(str) { |
| 137 | return str.replace(/&/g, '&') |
| 138 | .replace(/</g, '<') |
| 139 | .replace(/>/g, '>') |
| 140 | .replace(/"/g, '"') |
| 141 | .replace(/'/g, ''') |
| 142 | } |
| 143 | |
| 144 | function sanitizeStringIntoFrontendFormat(str) { |
| 145 | return str.replace(/'/g, '\'') |
| 146 | .replace(/"/g, '"') |
| 147 | .replace(/>/g, '>') |
| 148 | .replace(/</g, '<') |
| 149 | .replace(/&/g, '&'); |
| 150 | } |
| 151 | |
| 152 | function sanitizeString(str, specialCharactersMap) { |
| 153 | let sanitizedStr = ''; |
| 154 | for (let i = 0; i < str.length; i++) { |
| 155 | let currChar = str.charAt(i); |
| 156 | if (specialCharactersMap[currChar] !== undefined) |
| 157 | currChar = specialCharactersMap[currChar]; |
| 158 | |
| 159 | sanitizedStr += currChar; |
| 160 | } |
| 161 | return sanitizedStr; |
| 162 | } |
| 163 | |
| 164 | function sanitizeStringIntoCppFormat(str) { |
| 165 | return sanitizeString(str, cppSpecialCharactersMap); |
| 166 | } |
| 167 | |
| 168 | async function getFilesFromItem(itemPath, filePaths, acceptedFileEndings) { |
| 169 | const stat = await statAsync(itemPath); |
| 170 | if (stat.isDirectory() && shouldParseDirectory(itemPath)) |
| 171 | return await getFilesFromDirectory(itemPath, filePaths, acceptedFileEndings); |
| 172 | |
| 173 | const hasAcceptedEnding = |
| 174 | acceptedFileEndings.some(acceptedEnding => itemPath.toLowerCase().endsWith(acceptedEnding.toLowerCase())); |
| 175 | if (hasAcceptedEnding && shouldParseFile(itemPath)) |
| 176 | filePaths.push(itemPath); |
| 177 | } |
| 178 | |
| 179 | async function getFilesFromDirectory(directoryPath, filePaths, acceptedFileEndings) { |
| 180 | const itemNames = await readDirAsync(directoryPath); |
| 181 | const promises = []; |
| 182 | for (const itemName of itemNames) { |
| 183 | const itemPath = path.resolve(directoryPath, itemName); |
| 184 | promises.push(getFilesFromItem(itemPath, filePaths, acceptedFileEndings)); |
| 185 | } |
| 186 | return Promise.all(promises); |
| 187 | } |
| 188 | |
| 189 | async function getChildDirectoriesFromDirectory(directoryPath) { |
| 190 | const dirPaths = []; |
| 191 | const itemNames = await readDirAsync(directoryPath); |
| 192 | for (const itemName of itemNames) { |
| 193 | const itemPath = path.resolve(directoryPath, itemName); |
| 194 | const stat = await statAsync(itemPath); |
| 195 | if (stat.isDirectory() && shouldParseDirectory(itemName)) |
| 196 | dirPaths.push(itemPath); |
| 197 | } |
| 198 | return dirPaths; |
| 199 | } |
| 200 | |
Mandy Chen | 7855263 | 2019-06-12 00:55:43 +0000 | [diff] [blame] | 201 | /** |
| 202 | * Pad leading / trailing whitespace with ''' so that the whitespace is preserved. See |
| 203 | * https://www.chromium.org/developers/tools-we-use-in-chromium/grit/grit-users-guide. |
| 204 | */ |
| 205 | function padWhitespace(str) { |
| 206 | if (str.match(/^\s+/)) |
| 207 | str = `'''${str}`; |
| 208 | if (str.match(/\s+$/)) |
| 209 | str = `${str}'''`; |
| 210 | return str; |
| 211 | } |
| 212 | |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 213 | function modifyStringIntoGRDFormat(str, args) { |
| 214 | let sanitizedStr = sanitizeStringIntoGRDFormat(str); |
Mandy Chen | 7855263 | 2019-06-12 00:55:43 +0000 | [diff] [blame] | 215 | sanitizedStr = padWhitespace(sanitizedStr); |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 216 | |
| 217 | const phRegex = /%d|%f|%s|%.[0-9]f/gm; |
| 218 | if (!str.match(phRegex)) |
| 219 | return sanitizedStr; |
| 220 | |
| 221 | let phNames; |
| 222 | if (args !== undefined) |
| 223 | phNames = args.map(arg => arg.replace(/[^a-zA-Z]/gm, '_').toUpperCase()); |
| 224 | else |
| 225 | phNames = ['PH1', 'PH2', 'PH3', 'PH4', 'PH5', 'PH6', 'PH7', 'PH8', 'PH9']; |
| 226 | |
| 227 | // It replaces all placeholders with <ph> tags. |
| 228 | let match; |
| 229 | let count = 1; |
| 230 | while ((match = phRegex.exec(sanitizedStr)) !== null) { |
| 231 | // This is necessary to avoid infinite loops with zero-width matches |
| 232 | if (match.index === phRegex.lastIndex) |
| 233 | phRegex.lastIndex++; |
| 234 | |
| 235 | // match[0]: the placeholder (e.g. %d, %s, %.2f, etc.) |
| 236 | const ph = match[0]; |
| 237 | // e.g. $1s, $1d, $1.2f |
| 238 | const newPh = `$${count}` + ph.substr(1); |
| 239 | |
| 240 | const i = sanitizedStr.indexOf(ph); |
| 241 | sanitizedStr = `${sanitizedStr.substring(0, i)}<ph name="${phNames[count - 1]}">${newPh}</ph>${ |
| 242 | sanitizedStr.substring(i + ph.length)}`; |
| 243 | count++; |
| 244 | } |
| 245 | return sanitizedStr; |
| 246 | } |
| 247 | |
| 248 | function createGrdpMessage(ids, stringObj) { |
Mandy Chen | c94d52a | 2019-06-11 22:51:53 +0000 | [diff] [blame] | 249 | let message = ` <message name="${ids}" desc="${stringObj.description || ''}">\n`; |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 250 | message += ` ${modifyStringIntoGRDFormat(stringObj.string, stringObj.arguments)}\n`; |
| 251 | message += ' </message>\n'; |
| 252 | return message; |
| 253 | } |
| 254 | |
| 255 | function getIDSKey(str) { |
Mandy Chen | 5128cc6 | 2019-09-23 16:46:00 +0000 | [diff] [blame] | 256 | return `${IDSPrefix}${md5(str)}`; |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 257 | } |
| 258 | |
Mandy Chen | d97200b | 2019-07-29 21:13:39 +0000 | [diff] [blame] | 259 | // Get line number in the file of a character at given index |
| 260 | function lineNumberOfIndex(str, index) { |
| 261 | const stringToIndex = str.substr(0, index); |
| 262 | return stringToIndex.split('\n').length; |
| 263 | } |
| 264 | |
Mandy Chen | 5128cc6 | 2019-09-23 16:46:00 +0000 | [diff] [blame] | 265 | // Relative file path from grdp file with back slash replaced with forward slash |
| 266 | function getRelativeGrdpPath(grdpPath) { |
| 267 | return path.relative(path.dirname(GRD_PATH), grdpPath).split(path.sep).join('/'); |
| 268 | } |
| 269 | |
| 270 | function getAbsoluteGrdpPath(relativeGrdpFilePath) { |
| 271 | return path.resolve(path.dirname(GRD_PATH), relativeGrdpFilePath); |
| 272 | } |
| 273 | |
| 274 | // Create a <part> entry, given absolute path of a grdp file |
| 275 | function createPartFileEntry(grdpFilePath) { |
| 276 | const relativeGrdpFilePath = getRelativeGrdpPath(grdpFilePath); |
| 277 | return ` <part file="${relativeGrdpFilePath}" />\n`; |
| 278 | } |
| 279 | |
| 280 | // grdpFilePaths are sorted and are absolute file paths |
| 281 | async function addChildGRDPFilePathsToGRD(grdpFilePaths) { |
| 282 | const grdFileContent = await parseFileContent(GRD_PATH); |
| 283 | const grdLines = grdFileContent.split('\n'); |
| 284 | |
| 285 | let newGrdFileContent = ''; |
| 286 | for (let i = 0; i < grdLines.length; i++) { |
| 287 | const grdLine = grdLines[i]; |
| 288 | // match[0]: full match |
| 289 | // match[1]: relative grdp file path |
| 290 | const match = grdLine.match(/<part file="(.*?)"/); |
| 291 | if (match) { |
| 292 | const grdpFilePathsRemaining = []; |
| 293 | for (const grdpFilePath of grdpFilePaths) { |
| 294 | if (grdpFilePath < getAbsoluteGrdpPath(match[1])) |
| 295 | newGrdFileContent += createPartFileEntry(grdpFilePath); |
| 296 | else |
| 297 | grdpFilePathsRemaining.push(grdpFilePath); |
| 298 | } |
| 299 | grdpFilePaths = grdpFilePathsRemaining; |
| 300 | } else if (grdLine.includes('</messages>')) { |
| 301 | for (const grdpFilePath of grdpFilePaths) |
| 302 | newGrdFileContent += createPartFileEntry(grdpFilePath); |
| 303 | } |
| 304 | newGrdFileContent += grdLine; |
| 305 | if (i < grdLines.length - 1) |
| 306 | newGrdFileContent += '\n'; |
| 307 | } |
| 308 | return writeFileAsync(GRD_PATH, newGrdFileContent); |
| 309 | } |
| 310 | |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 311 | module.exports = { |
Mandy Chen | 5128cc6 | 2019-09-23 16:46:00 +0000 | [diff] [blame] | 312 | addChildGRDPFilePathsToGRD, |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 313 | createGrdpMessage, |
Mandy Chen | 5128cc6 | 2019-09-23 16:46:00 +0000 | [diff] [blame] | 314 | createPartFileEntry, |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 315 | escodegen, |
| 316 | esprima, |
| 317 | esprimaTypes, |
Mandy Chen | 5128cc6 | 2019-09-23 16:46:00 +0000 | [diff] [blame] | 318 | getAbsoluteGrdpPath, |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 319 | getChildDirectoriesFromDirectory, |
| 320 | getFilesFromDirectory, |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 321 | getIDSKey, |
| 322 | getLocalizationCase, |
| 323 | getLocationMessage, |
| 324 | getRelativeFilePathFromSrc, |
Mandy Chen | 5128cc6 | 2019-09-23 16:46:00 +0000 | [diff] [blame] | 325 | getRelativeGrdpPath, |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 326 | GRD_PATH, |
| 327 | IDSPrefix, |
| 328 | isLocalizationCall, |
Mandy Chen | d97200b | 2019-07-29 21:13:39 +0000 | [diff] [blame] | 329 | lineNumberOfIndex, |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 330 | modifyStringIntoGRDFormat, |
| 331 | parseFileContent, |
Mandy Chen | 1e9d87b | 2019-09-18 17:18:15 +0000 | [diff] [blame] | 332 | SHARED_STRINGS_PATH, |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 333 | sanitizeStringIntoCppFormat, |
| 334 | sanitizeStringIntoFrontendFormat, |
Paul Irish | e7b977e | 2019-09-25 12:23:38 +0000 | [diff] [blame] | 335 | shouldParseDirectory, |
Lorne Mitchell | c56ff2d | 2019-05-28 23:35:03 +0000 | [diff] [blame] | 336 | verifyFunctionCallee |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame^] | 337 | }; |