blob: 72521b8125f76cd24696cb9ece3743a6c904da8b [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);
12
13const esprimaTypes = {
14 BI_EXPR: 'BinaryExpression',
15 CALL_EXPR: 'CallExpression',
16 COND_EXPR: 'ConditionalExpression',
17 IDENTIFIER: 'Identifier',
18 LITERAL: 'Literal',
19 MEMBER_EXPR: 'MemberExpression',
Mandy Chen7a8829b2019-06-25 22:13:07 +000020 NEW_EXPR: 'NewExpression',
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000021 TAGGED_TEMP_EXPR: 'TaggedTemplateExpression',
22 TEMP_LITERAL: 'TemplateLiteral'
23};
24
25const excludeFiles = ['lighthouse-dt-bundle.js', 'Tests.js'];
26const excludeDirs = ['test_runner', 'Images', 'langpacks', 'node_modules'];
27const cppSpecialCharactersMap = {
28 '"': '\\"',
29 '\\': '\\\\',
30 '\n': '\\n'
31};
32const IDSPrefix = 'IDS_DEVTOOLS_';
33
34const THIRD_PARTY_PATH = path.resolve(__dirname, '..', '..', '..', '..', '..');
35const SRC_PATH = path.resolve(THIRD_PARTY_PATH, '..');
36const GRD_PATH = path.resolve(__dirname, '..', '..', 'front_end', 'langpacks', 'devtools_ui_strings.grd');
Mandy Chen1e9d87b2019-09-18 17:18:15 +000037const SHARED_STRINGS_PATH = path.resolve(__dirname, '..', '..', 'front_end', 'langpacks', 'shared_strings.grdp');
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000038const REPO_NODE_MODULES_PATH = path.resolve(THIRD_PARTY_PATH, 'node', 'node_modules');
39const escodegen = require(path.resolve(REPO_NODE_MODULES_PATH, 'escodegen'));
40const esprima = require(path.resolve(REPO_NODE_MODULES_PATH, 'esprima'));
41
42function getRelativeFilePathFromSrc(filePath) {
43 return path.relative(SRC_PATH, filePath);
44}
45
46function 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 */
53function shouldParseFile(filepath) {
54 return !excludeFiles.includes(path.basename(filepath));
55}
56
57async function parseFileContent(filePath) {
58 const fileContent = await readFileAsync(filePath);
59 return fileContent.toString();
60}
61
62function isNodeCallOnObject(node, objectName, propertyName) {
63 return node !== undefined && node.type === esprimaTypes.CALL_EXPR &&
64 verifyCallExpressionCallee(node.callee, objectName, propertyName);
65}
66
67function isNodeCommonUIStringCall(node) {
68 return isNodeCallOnObject(node, 'Common', 'UIString');
69}
70
Mandy Chen7a8829b2019-06-25 22:13:07 +000071function isNodeCommonUIStringFormat(node) {
72 return node && node.type === esprimaTypes.NEW_EXPR &&
73 verifyCallExpressionCallee(node.callee, 'Common', 'UIStringFormat');
74}
75
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000076function isNodeUIformatLocalized(node) {
77 return isNodeCallOnObject(node, 'UI', 'formatLocalized');
78}
79
80function 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 */
88function 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
93function verifyIdentifier(node, name) {
94 return node !== undefined && node.type === esprimaTypes.IDENTIFIER && node.name === name;
95}
96
97function getLocalizationCase(node) {
98 if (isNodeCommonUIStringCall(node))
99 return 'Common.UIString';
Mandy Chen7a8829b2019-06-25 22:13:07 +0000100 else if (isNodeCommonUIStringFormat(node))
101 return 'Common.UIStringFormat';
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000102 else if (isNodelsTaggedTemplateExpression(node))
103 return 'Tagged Template';
104 else if (isNodeUIformatLocalized(node))
105 return 'UI.formatLocalized';
106 else
107 return null;
108}
109
110function isLocalizationCall(node) {
111 return isNodeCommonUIStringCall(node) || isNodelsTaggedTemplateExpression(node) || isNodeUIformatLocalized(node);
112}
113
114/**
115 * Verify if callee is functionName() or object.functionName().
116 */
117function 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
123function 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
136function sanitizeStringIntoGRDFormat(str) {
137 return str.replace(/&/g, '&')
138 .replace(/</g, '&lt;')
139 .replace(/>/g, '&gt;')
140 .replace(/"/g, '&quot;')
141 .replace(/'/g, '&apos;')
142}
143
144function sanitizeStringIntoFrontendFormat(str) {
145 return str.replace(/&apos;/g, '\'')
146 .replace(/&quot;/g, '"')
147 .replace(/&gt;/g, '>')
148 .replace(/&lt;/g, '<')
149 .replace(/&amp;/g, '&');
150}
151
152function 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
164function sanitizeStringIntoCppFormat(str) {
165 return sanitizeString(str, cppSpecialCharactersMap);
166}
167
168async 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
179async 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
189async 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 Chen78552632019-06-12 00:55:43 +0000201/**
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 */
205function padWhitespace(str) {
206 if (str.match(/^\s+/))
207 str = `'''${str}`;
208 if (str.match(/\s+$/))
209 str = `${str}'''`;
210 return str;
211}
212
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000213function modifyStringIntoGRDFormat(str, args) {
214 let sanitizedStr = sanitizeStringIntoGRDFormat(str);
Mandy Chen78552632019-06-12 00:55:43 +0000215 sanitizedStr = padWhitespace(sanitizedStr);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000216
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
248function createGrdpMessage(ids, stringObj) {
Mandy Chenc94d52a2019-06-11 22:51:53 +0000249 let message = ` <message name="${ids}" desc="${stringObj.description || ''}">\n`;
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000250 message += ` ${modifyStringIntoGRDFormat(stringObj.string, stringObj.arguments)}\n`;
251 message += ' </message>\n';
252 return message;
253}
254
255function getIDSKey(str) {
256 return `${IDSPrefix}${md5(str)}`
257}
258
Mandy Chend97200b2019-07-29 21:13:39 +0000259// Get line number in the file of a character at given index
260function lineNumberOfIndex(str, index) {
261 const stringToIndex = str.substr(0, index);
262 return stringToIndex.split('\n').length;
263}
264
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000265module.exports = {
266 createGrdpMessage,
267 escodegen,
268 esprima,
269 esprimaTypes,
270 getChildDirectoriesFromDirectory,
271 getFilesFromDirectory,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000272 getIDSKey,
273 getLocalizationCase,
274 getLocationMessage,
275 getRelativeFilePathFromSrc,
276 GRD_PATH,
277 IDSPrefix,
278 isLocalizationCall,
Mandy Chend97200b2019-07-29 21:13:39 +0000279 lineNumberOfIndex,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000280 modifyStringIntoGRDFormat,
281 parseFileContent,
Mandy Chen1e9d87b2019-09-18 17:18:15 +0000282 SHARED_STRINGS_PATH,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000283 sanitizeStringIntoCppFormat,
284 sanitizeStringIntoFrontendFormat,
285 verifyFunctionCallee
286};