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