blob: b10890afd6ab58006589f623d1bbd07773ecf10c [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
Yang Guo4fd355c2019-09-19 10:59:03 +020035const SRC_PATH = path.resolve(__dirname, '..', '..');
36const GRD_PATH = path.resolve(SRC_PATH, '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');
Yang Guo4fd355c2019-09-19 10:59:03 +020038const NODE_MODULES_PATH = path.resolve(SRC_PATH, 'node_modules');
39const escodegen = require(path.resolve(NODE_MODULES_PATH, 'escodegen'));
40const esprima = require(path.resolve(NODE_MODULES_PATH, 'esprima'));
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000041
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) {
Mandy Chen5128cc62019-09-23 16:46:00 +0000256 return `${IDSPrefix}${md5(str)}`;
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000257}
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
Mandy Chen5128cc62019-09-23 16:46:00 +0000265// Relative file path from grdp file with back slash replaced with forward slash
266function getRelativeGrdpPath(grdpPath) {
267 return path.relative(path.dirname(GRD_PATH), grdpPath).split(path.sep).join('/');
268}
269
270function 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
275function createPartFileEntry(grdpFilePath) {
276 const relativeGrdpFilePath = getRelativeGrdpPath(grdpFilePath);
277 return ` <part file="${relativeGrdpFilePath}" />\n`;
278}
279
280// grdpFilePaths are sorted and are absolute file paths
281async 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 Mitchellc56ff2d2019-05-28 23:35:03 +0000311module.exports = {
Mandy Chen5128cc62019-09-23 16:46:00 +0000312 addChildGRDPFilePathsToGRD,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000313 createGrdpMessage,
Mandy Chen5128cc62019-09-23 16:46:00 +0000314 createPartFileEntry,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000315 escodegen,
316 esprima,
317 esprimaTypes,
Mandy Chen5128cc62019-09-23 16:46:00 +0000318 getAbsoluteGrdpPath,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000319 getChildDirectoriesFromDirectory,
320 getFilesFromDirectory,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000321 getIDSKey,
322 getLocalizationCase,
323 getLocationMessage,
324 getRelativeFilePathFromSrc,
Mandy Chen5128cc62019-09-23 16:46:00 +0000325 getRelativeGrdpPath,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000326 GRD_PATH,
327 IDSPrefix,
328 isLocalizationCall,
Mandy Chend97200b2019-07-29 21:13:39 +0000329 lineNumberOfIndex,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000330 modifyStringIntoGRDFormat,
331 parseFileContent,
Mandy Chen1e9d87b2019-09-18 17:18:15 +0000332 SHARED_STRINGS_PATH,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000333 sanitizeStringIntoCppFormat,
334 sanitizeStringIntoFrontendFormat,
Paul Irishe7b977e2019-09-25 12:23:38 +0000335 shouldParseDirectory,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000336 verifyFunctionCallee
Yang Guo4fd355c2019-09-19 10:59:03 +0200337};