blob: 7a2436d0a90cfb32ac167fbad31857889649e119 [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');
37const REPO_NODE_MODULES_PATH = path.resolve(THIRD_PARTY_PATH, 'node', 'node_modules');
38const escodegen = require(path.resolve(REPO_NODE_MODULES_PATH, 'escodegen'));
39const esprima = require(path.resolve(REPO_NODE_MODULES_PATH, 'esprima'));
40
41function getRelativeFilePathFromSrc(filePath) {
42 return path.relative(SRC_PATH, filePath);
43}
44
45function shouldParseDirectory(directoryName) {
46 return !excludeDirs.some(dir => directoryName.includes(dir));
47}
48
49/**
50 * @filepath can be partial path or full path, as long as it contains the file name.
51 */
52function shouldParseFile(filepath) {
53 return !excludeFiles.includes(path.basename(filepath));
54}
55
56async function parseFileContent(filePath) {
57 const fileContent = await readFileAsync(filePath);
58 return fileContent.toString();
59}
60
61function isNodeCallOnObject(node, objectName, propertyName) {
62 return node !== undefined && node.type === esprimaTypes.CALL_EXPR &&
63 verifyCallExpressionCallee(node.callee, objectName, propertyName);
64}
65
66function isNodeCommonUIStringCall(node) {
67 return isNodeCallOnObject(node, 'Common', 'UIString');
68}
69
Mandy Chen7a8829b2019-06-25 22:13:07 +000070function isNodeCommonUIStringFormat(node) {
71 return node && node.type === esprimaTypes.NEW_EXPR &&
72 verifyCallExpressionCallee(node.callee, 'Common', 'UIStringFormat');
73}
74
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000075function isNodeUIformatLocalized(node) {
76 return isNodeCallOnObject(node, 'UI', 'formatLocalized');
77}
78
79function isNodelsTaggedTemplateExpression(node) {
80 return node !== undefined && node.type === esprimaTypes.TAGGED_TEMP_EXPR && verifyIdentifier(node.tag, 'ls') &&
81 node.quasi !== undefined && node.quasi.type !== undefined && node.quasi.type === esprimaTypes.TEMP_LITERAL;
82}
83
84/**
85 * Verify callee of objectName.propertyName(), e.g. Common.UIString().
86 */
87function verifyCallExpressionCallee(callee, objectName, propertyName) {
88 return callee !== undefined && callee.type === esprimaTypes.MEMBER_EXPR && callee.computed === false &&
89 verifyIdentifier(callee.object, objectName) && verifyIdentifier(callee.property, propertyName);
90}
91
92function verifyIdentifier(node, name) {
93 return node !== undefined && node.type === esprimaTypes.IDENTIFIER && node.name === name;
94}
95
96function getLocalizationCase(node) {
97 if (isNodeCommonUIStringCall(node))
98 return 'Common.UIString';
Mandy Chen7a8829b2019-06-25 22:13:07 +000099 else if (isNodeCommonUIStringFormat(node))
100 return 'Common.UIStringFormat';
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000101 else if (isNodelsTaggedTemplateExpression(node))
102 return 'Tagged Template';
103 else if (isNodeUIformatLocalized(node))
104 return 'UI.formatLocalized';
105 else
106 return null;
107}
108
109function isLocalizationCall(node) {
110 return isNodeCommonUIStringCall(node) || isNodelsTaggedTemplateExpression(node) || isNodeUIformatLocalized(node);
111}
112
113/**
114 * Verify if callee is functionName() or object.functionName().
115 */
116function verifyFunctionCallee(callee, functionName) {
117 return callee !== undefined &&
118 ((callee.type === esprimaTypes.IDENTIFIER && callee.name === functionName) ||
119 (callee.type === esprimaTypes.MEMBER_EXPR && verifyIdentifier(callee.property, functionName)));
120}
121
122function getLocationMessage(location) {
123 if (location !== undefined && location.start !== undefined && location.end !== undefined &&
124 location.start.line !== undefined && location.end.line !== undefined) {
125 const startLine = location.start.line;
126 const endLine = location.end.line;
127 if (startLine === endLine)
128 return ` Line ${startLine}`;
129 else
130 return ` Line ${location.start.line}-${location.end.line}`;
131 }
132 return '';
133}
134
135function sanitizeStringIntoGRDFormat(str) {
136 return str.replace(/&/g, '&')
137 .replace(/</g, '&lt;')
138 .replace(/>/g, '&gt;')
139 .replace(/"/g, '&quot;')
140 .replace(/'/g, '&apos;')
141}
142
143function sanitizeStringIntoFrontendFormat(str) {
144 return str.replace(/&apos;/g, '\'')
145 .replace(/&quot;/g, '"')
146 .replace(/&gt;/g, '>')
147 .replace(/&lt;/g, '<')
148 .replace(/&amp;/g, '&');
149}
150
151function sanitizeString(str, specialCharactersMap) {
152 let sanitizedStr = '';
153 for (let i = 0; i < str.length; i++) {
154 let currChar = str.charAt(i);
155 if (specialCharactersMap[currChar] !== undefined)
156 currChar = specialCharactersMap[currChar];
157
158 sanitizedStr += currChar;
159 }
160 return sanitizedStr;
161}
162
163function sanitizeStringIntoCppFormat(str) {
164 return sanitizeString(str, cppSpecialCharactersMap);
165}
166
167async function getFilesFromItem(itemPath, filePaths, acceptedFileEndings) {
168 const stat = await statAsync(itemPath);
169 if (stat.isDirectory() && shouldParseDirectory(itemPath))
170 return await getFilesFromDirectory(itemPath, filePaths, acceptedFileEndings);
171
172 const hasAcceptedEnding =
173 acceptedFileEndings.some(acceptedEnding => itemPath.toLowerCase().endsWith(acceptedEnding.toLowerCase()));
174 if (hasAcceptedEnding && shouldParseFile(itemPath))
175 filePaths.push(itemPath);
176}
177
178async function getFilesFromDirectory(directoryPath, filePaths, acceptedFileEndings) {
179 const itemNames = await readDirAsync(directoryPath);
180 const promises = [];
181 for (const itemName of itemNames) {
182 const itemPath = path.resolve(directoryPath, itemName);
183 promises.push(getFilesFromItem(itemPath, filePaths, acceptedFileEndings));
184 }
185 return Promise.all(promises);
186}
187
188async function getChildDirectoriesFromDirectory(directoryPath) {
189 const dirPaths = [];
190 const itemNames = await readDirAsync(directoryPath);
191 for (const itemName of itemNames) {
192 const itemPath = path.resolve(directoryPath, itemName);
193 const stat = await statAsync(itemPath);
194 if (stat.isDirectory() && shouldParseDirectory(itemName))
195 dirPaths.push(itemPath);
196 }
197 return dirPaths;
198}
199
Mandy Chen78552632019-06-12 00:55:43 +0000200/**
201 * Pad leading / trailing whitespace with ''' so that the whitespace is preserved. See
202 * https://www.chromium.org/developers/tools-we-use-in-chromium/grit/grit-users-guide.
203 */
204function padWhitespace(str) {
205 if (str.match(/^\s+/))
206 str = `'''${str}`;
207 if (str.match(/\s+$/))
208 str = `${str}'''`;
209 return str;
210}
211
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000212function modifyStringIntoGRDFormat(str, args) {
213 let sanitizedStr = sanitizeStringIntoGRDFormat(str);
Mandy Chen78552632019-06-12 00:55:43 +0000214 sanitizedStr = padWhitespace(sanitizedStr);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000215
216 const phRegex = /%d|%f|%s|%.[0-9]f/gm;
217 if (!str.match(phRegex))
218 return sanitizedStr;
219
220 let phNames;
221 if (args !== undefined)
222 phNames = args.map(arg => arg.replace(/[^a-zA-Z]/gm, '_').toUpperCase());
223 else
224 phNames = ['PH1', 'PH2', 'PH3', 'PH4', 'PH5', 'PH6', 'PH7', 'PH8', 'PH9'];
225
226 // It replaces all placeholders with <ph> tags.
227 let match;
228 let count = 1;
229 while ((match = phRegex.exec(sanitizedStr)) !== null) {
230 // This is necessary to avoid infinite loops with zero-width matches
231 if (match.index === phRegex.lastIndex)
232 phRegex.lastIndex++;
233
234 // match[0]: the placeholder (e.g. %d, %s, %.2f, etc.)
235 const ph = match[0];
236 // e.g. $1s, $1d, $1.2f
237 const newPh = `$${count}` + ph.substr(1);
238
239 const i = sanitizedStr.indexOf(ph);
240 sanitizedStr = `${sanitizedStr.substring(0, i)}<ph name="${phNames[count - 1]}">${newPh}</ph>${
241 sanitizedStr.substring(i + ph.length)}`;
242 count++;
243 }
244 return sanitizedStr;
245}
246
247function createGrdpMessage(ids, stringObj) {
Mandy Chenc94d52a2019-06-11 22:51:53 +0000248 let message = ` <message name="${ids}" desc="${stringObj.description || ''}">\n`;
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000249 message += ` ${modifyStringIntoGRDFormat(stringObj.string, stringObj.arguments)}\n`;
250 message += ' </message>\n';
251 return message;
252}
253
254function getIDSKey(str) {
255 return `${IDSPrefix}${md5(str)}`
256}
257
Mandy Chend97200b2019-07-29 21:13:39 +0000258// Get line number in the file of a character at given index
259function lineNumberOfIndex(str, index) {
260 const stringToIndex = str.substr(0, index);
261 return stringToIndex.split('\n').length;
262}
263
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000264module.exports = {
265 createGrdpMessage,
266 escodegen,
267 esprima,
268 esprimaTypes,
269 getChildDirectoriesFromDirectory,
270 getFilesFromDirectory,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000271 getIDSKey,
272 getLocalizationCase,
273 getLocationMessage,
274 getRelativeFilePathFromSrc,
275 GRD_PATH,
276 IDSPrefix,
277 isLocalizationCall,
Mandy Chend97200b2019-07-29 21:13:39 +0000278 lineNumberOfIndex,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000279 modifyStringIntoGRDFormat,
280 parseFileContent,
281 sanitizeStringIntoCppFormat,
282 sanitizeStringIntoFrontendFormat,
283 verifyFunctionCallee
284};