blob: 148740e73eaf77f9917bce67ef0454380afe004f [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
5/**
6 * Functions in this script parse DevTools frontend .js and module.json files,
7 * collect localizable strings, check if frontend strings are in .grd/.grdp
8 * files and report error if present.
9 */
10
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000011const path = require('path');
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000012const localizationUtils = require('./localization_utils');
13const escodegen = localizationUtils.escodegen;
14const esprimaTypes = localizationUtils.esprimaTypes;
15const esprima = localizationUtils.esprima;
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000016const extensionStringKeys = ['category', 'destination', 'title', 'title-mac'];
17
18// Format of frontendStrings
19// { IDS_md5-hash => {
20// string: string,
21// code: string,
22// filepath: string,
Mandy Chenc94d52a2019-06-11 22:51:53 +000023// grdpPath: string,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000024// location: {
25// start: {
26// line: number, (1-based)
27// column: number (0-based)
28// },
29// end: {
30// line: number,
31// column: number
32// }
33// },
34// arguments: string[]
35// }
36// }
37const frontendStrings = new Map();
38
39// Format
40// {
Mandy Chen4a7ad052019-07-16 16:09:29 +000041// IDS_KEY => a list of {
Mandy Chen81d4fc42019-07-11 23:12:02 +000042// actualIDSKey: string, // the IDS key in the message tag
Mandy Chenc94d52a2019-06-11 22:51:53 +000043// description: string,
Mandy Chen4a7ad052019-07-16 16:09:29 +000044// grdpPath: string,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000045// location: {
46// start: {
47// line: number
48// },
49// end: {
50// line: number
51// }
52// }
53// }
54// }
55const IDSkeys = new Map();
Mandy Chenc94d52a2019-06-11 22:51:53 +000056const fileToGRDPMap = new Map();
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000057
58const devtoolsFrontendPath = path.resolve(__dirname, '..', '..', 'front_end');
59
Mandy Chen4a7ad052019-07-16 16:09:29 +000060async function parseLocalizableResourceMaps() {
Mandy Chenc94d52a2019-06-11 22:51:53 +000061 const grdpToFiles = new Map();
62 const dirs = await localizationUtils.getChildDirectoriesFromDirectory(devtoolsFrontendPath);
63 const grdpToFilesPromises = dirs.map(dir => {
64 const files = [];
65 grdpToFiles.set(path.resolve(dir, `${path.basename(dir)}_strings.grdp`), files);
66 return localizationUtils.getFilesFromDirectory(dir, files, ['.js', 'module.json']);
67 });
68 await Promise.all(grdpToFilesPromises);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000069
Mandy Chen4a7ad052019-07-16 16:09:29 +000070 const promises = [];
Mandy Chenc94d52a2019-06-11 22:51:53 +000071 for (const [grdpPath, files] of grdpToFiles) {
72 files.forEach(file => fileToGRDPMap.set(file, grdpPath));
Mandy Chen4a7ad052019-07-16 16:09:29 +000073 promises.push(parseLocalizableStrings(files));
Mandy Chenc94d52a2019-06-11 22:51:53 +000074 }
75 await Promise.all(promises);
Mandy Chen4a7ad052019-07-16 16:09:29 +000076 // Parse grd(p) files after frontend strings are processed so we know
77 // what to add or remove based on frontend strings
78 await parseIDSKeys(localizationUtils.GRD_PATH);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000079}
80
81/**
Mandy Chen7a8829b2019-06-25 22:13:07 +000082 * The following functions parse localizable strings (wrapped in Common.UIString,
83 * Common.UIStringFormat, UI.formatLocalized or ls``) from devtools frontend files.
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000084 */
85
Mandy Chen4a7ad052019-07-16 16:09:29 +000086async function parseLocalizableStrings(devtoolsFiles) {
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000087 const promises = devtoolsFiles.map(filePath => parseLocalizableStringsFromFile(filePath));
88 await Promise.all(promises);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +000089}
90
91async function parseLocalizableStringsFromFile(filePath) {
92 const fileContent = await localizationUtils.parseFileContent(filePath);
93 if (path.basename(filePath) === 'module.json')
94 return parseLocalizableStringFromModuleJson(fileContent, filePath);
95
96 const ast = esprima.parse(fileContent, {loc: true});
97 for (const node of ast.body)
98 parseLocalizableStringFromNode(node, filePath);
99}
100
101function parseLocalizableStringFromModuleJson(fileContent, filePath) {
102 const fileJSON = JSON.parse(fileContent);
103 if (!fileJSON.extensions)
104 return;
105
106 for (const extension of fileJSON.extensions) {
107 for (const key in extension) {
108 if (extensionStringKeys.includes(key)) {
109 addString(extension[key], extension[key], filePath);
110 } else if (key === 'device') {
111 addString(extension.device.title, extension.device.title, filePath);
112 } else if (key === 'options') {
113 for (const option of extension.options) {
114 addString(option.title, option.title, filePath);
115 if (option.text !== undefined)
116 addString(option.text, option.text, filePath);
117 }
118 }
119 }
120 }
121}
122
123function parseLocalizableStringFromNode(node, filePath) {
124 if (!node)
125 return;
126
127 if (Array.isArray(node)) {
128 for (const child of node)
129 parseLocalizableStringFromNode(child, filePath);
130
131 return;
132 }
133
134 const keys = Object.keys(node);
135 const objKeys = keys.filter(key => key !== 'loc' && typeof node[key] === 'object');
136 if (objKeys.length === 0) {
137 // base case: all values are non-objects -> node is a leaf
138 return;
139 }
140
141 const locCase = localizationUtils.getLocalizationCase(node);
142 switch (locCase) {
143 case 'Common.UIString':
Mandy Chen7a8829b2019-06-25 22:13:07 +0000144 case 'Common.UIStringFormat':
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000145 handleCommonUIString(node, filePath);
146 break;
147 case 'UI.formatLocalized':
148 if (node.arguments !== undefined && node.arguments[1] !== undefined && node.arguments[1].elements !== undefined)
149 handleCommonUIString(node, filePath, node.arguments[1].elements);
150 break;
151 case 'Tagged Template':
152 handleTemplateLiteral(node.quasi, escodegen.generate(node), filePath);
153 break;
154 case null:
155 break;
156 default:
157 throw new Error(
158 `${filePath}${localizationUtils.getLocationMessage(node.loc)}: unexpected localization case for node: ${
159 escodegen.generate(node)}`);
160 }
161
162 for (const key of objKeys) {
163 // recursively parse all the child nodes
164 parseLocalizableStringFromNode(node[key], filePath);
165 }
166}
167
168function handleCommonUIString(node, filePath, argumentNodes) {
169 if (argumentNodes === undefined)
170 argumentNodes = node.arguments.slice(1);
171 const firstArgType = node.arguments[0].type;
172 switch (firstArgType) {
173 case esprimaTypes.LITERAL:
174 const message = node.arguments[0].value;
175 addString(message, escodegen.generate(node), filePath, node.loc, argumentNodes);
176 break;
177 case esprimaTypes.TEMP_LITERAL:
178 handleTemplateLiteral(node.arguments[0], escodegen.generate(node), filePath, argumentNodes);
179 break;
180 default:
181 break;
182 }
183}
184
185function handleTemplateLiteral(node, code, filePath, argumentNodes) {
186 if (node.expressions.length === 0) {
187 // template literal does not contain any variables, parse the value
188 addString(node.quasis[0].value.cooked, code, filePath, node.loc, argumentNodes);
189 return;
190 }
191
192 argumentNodes = node.expressions;
193 let processedMsg = '';
194 for (let i = 0; i < node.quasis.length; i++) {
195 processedMsg += node.quasis[i].value.cooked;
196 if (i < node.expressions.length) {
197 // add placeholder for variable so that
198 // the ph tag gets generated
199 processedMsg += '%s';
200 }
201 }
202 addString(processedMsg, code, filePath, node.loc, argumentNodes);
203}
204
205function addString(str, code, filePath, location, argumentNodes) {
Mandy Chenc94d52a2019-06-11 22:51:53 +0000206 const currentString = {string: str, code: code, filepath: filePath, grdpPath: fileToGRDPMap.get(filePath)};
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000207 if (location)
208 currentString.location = location;
209 if (argumentNodes && argumentNodes.length > 0)
210 currentString.arguments = argumentNodes.map(argNode => escodegen.generate(argNode));
211
212 // In the case of duplicates, to enforce that entries are added to
213 // a consistent GRDP file, we use the file path that sorts lowest as
214 // the winning entry into frontendStrings.
215 const ids = localizationUtils.getIDSKey(str);
216 if (frontendStrings.has(ids) && frontendStrings.get(ids).filepath <= filePath)
217 return;
218 frontendStrings.set(ids, currentString);
219}
220
221/**
222 * The following functions parse <message>s and their IDS keys from
223 * devtools frontend grdp files.
224 */
225
Mandy Chen4a7ad052019-07-16 16:09:29 +0000226async function parseIDSKeys(grdFilePath) {
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000227 // NOTE: this function assumes that no <message> tags are present in the parent
228 const grdpFilePaths = await parseGRDFile(grdFilePath);
229 await parseGRDPFiles(grdpFilePaths);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000230}
231
232async function parseGRDFile(grdFilePath) {
233 const fileContent = await localizationUtils.parseFileContent(grdFilePath);
234 const grdFileDir = path.dirname(grdFilePath);
235 const partFileRegex = /<part file="(.*?)"/g;
236
237 let match;
238 const grdpFilePaths = new Set();
239 while ((match = partFileRegex.exec(fileContent)) !== null) {
240 if (match.index === partFileRegex.lastIndex)
241 partFileRegex.lastIndex++;
242 // match[0]: full match
243 // match[1]: part file path
244 grdpFilePaths.add(path.resolve(grdFileDir, match[1]));
245 }
246 return grdpFilePaths;
247}
248
249function parseGRDPFiles(grdpFilePaths) {
250 const promises = Array.from(grdpFilePaths, grdpFilePath => parseGRDPFile(grdpFilePath));
251 return Promise.all(promises);
252}
253
254function trimGrdpPlaceholder(placeholder) {
255 const exampleRegex = new RegExp('<ex>.*?<\/ex>', 'gms');
256 // $1s<ex>my example</ex> -> $1s
257 return placeholder.replace(exampleRegex, '').trim();
258}
259
260function convertToFrontendPlaceholders(message) {
261 // <ph name="phname">$1s<ex>my example</ex></ph> and <ph name="phname2">$2.3f</ph>
262 // match[0]: <ph name="phname1">$1s</ph>
263 // match[1]: $1s<ex>my example</ex>
264 let placeholderRegex = new RegExp('<ph[^>]*>(.*?)<\/ph>', 'gms');
265 let match;
266 while ((match = placeholderRegex.exec(message)) !== null) {
267 const placeholder = match[0];
268 const placeholderValue = trimGrdpPlaceholder(match[1]);
269 const newPlaceholderValue = placeholderValue.replace(/\$[1-9]/, '%');
270 message =
271 message.substring(0, match.index) + newPlaceholderValue + message.substring(match.index + placeholder.length);
272 // Modified the message, so search from the beginning of the string again.
273 placeholderRegex.lastIndex = 0;
274 }
275 return message;
276}
277
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000278async function parseGRDPFile(filePath) {
279 const fileContent = await localizationUtils.parseFileContent(filePath);
280
Mandy Chen78552632019-06-12 00:55:43 +0000281 function stripWhitespacePadding(message) {
282 let match = message.match(/^'''/);
283 if (match)
284 message = message.substring(3);
285 match = message.match(/(.*?)'''$/);
286 if (match)
287 message = match[1];
288 return message;
289 }
290
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000291 // Example:
Mandy Chen81d4fc42019-07-11 23:12:02 +0000292 // <message name="IDS_DEVTOOLS_md5_hash" desc="Description of this message">
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000293 // Message text here with optional placeholders <ph name="phname">$1s</ph>
294 // </message>
295 // match[0]: the entire '<message>...</message>' block.
Mandy Chen81d4fc42019-07-11 23:12:02 +0000296 // match[1]: 'IDS_DEVTOOLS_md5_hash'
297 // match[2]: 'Description of this message'
298 // match[3]: ' Message text here with optional placeholders <ph name="phname">$1s</ph>\n '
299 const messageRegex = new RegExp('<message[^>]*name="([^"]*)"[^>]*desc="([^"]*)"[^>]*>\s*\n(.*?)<\/message>', 'gms');
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000300 let match;
301 while ((match = messageRegex.exec(fileContent)) !== null) {
Mandy Chend97200b2019-07-29 21:13:39 +0000302 const line = localizationUtils.lineNumberOfIndex(fileContent, match.index);
Mandy Chen81d4fc42019-07-11 23:12:02 +0000303 const actualIDSKey = match[1];
304 const description = match[2];
305 let message = match[3];
Mandy Chen78552632019-06-12 00:55:43 +0000306 message = convertToFrontendPlaceholders(message.trim());
307 message = stripWhitespacePadding(message);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000308 message = localizationUtils.sanitizeStringIntoFrontendFormat(message);
309
310 const ids = localizationUtils.getIDSKey(message);
Mandy Chen4a7ad052019-07-16 16:09:29 +0000311 addMessage(ids, actualIDSKey, filePath, line, description);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000312 }
313}
314
Mandy Chen4a7ad052019-07-16 16:09:29 +0000315function addMessage(expectedIDSKey, actualIDSKey, grdpPath, line, description) {
316 if (!IDSkeys.has(expectedIDSKey))
317 IDSkeys.set(expectedIDSKey, []);
318
319 IDSkeys.get(expectedIDSKey).push({actualIDSKey, grdpPath, location: {start: {line}, end: {line}}, description});
320}
321
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000322/**
323 * The following functions compare frontend localizable strings
Mandy Chen81d4fc42019-07-11 23:12:02 +0000324 * with grdp <message>s and report error of resources to add,
325 * remove or modify.
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000326 */
Mandy Chen4a7ad052019-07-16 16:09:29 +0000327async function getAndReportResourcesToAdd() {
328 const keysToAddToGRD = getMessagesToAdd();
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000329 if (keysToAddToGRD.size === 0)
330 return;
331
332 let errorStr = 'The following frontend string(s) need to be added to GRD/GRDP file(s).\n';
333 errorStr += 'Please refer to auto-generated message(s) below and modify as needed.\n\n';
334
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000335 // Example error message:
336 // third_party/blink/renderer/devtools/front_end/network/NetworkDataGridNode.js Line 973: ls`(disk cache)`
337 // Add a new message tag for this string to third_party\blink\renderer\devtools\front_end\network\network_strings.grdp
338 // <message name="IDS_DEVTOOLS_ad86890fb40822a3b12627efaca4ecd7" desc="Fill in the description.">
339 // (disk cache)
340 // </message>
341 for (const [key, stringObj] of keysToAddToGRD) {
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000342 errorStr += `${localizationUtils.getRelativeFilePathFromSrc(stringObj.filepath)}${
343 localizationUtils.getLocationMessage(stringObj.location)}: ${stringObj.code}\n`;
344 errorStr += `Add a new message tag for this string to ${
Mandy Chenc94d52a2019-06-11 22:51:53 +0000345 localizationUtils.getRelativeFilePathFromSrc(fileToGRDPMap.get(stringObj.filepath))}\n\n`;
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000346 errorStr += localizationUtils.createGrdpMessage(key, stringObj);
347 }
348 return errorStr;
349}
350
Mandy Chen4a7ad052019-07-16 16:09:29 +0000351function getAndReportResourcesToRemove() {
352 const keysToRemoveFromGRD = getMessagesToRemove();
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000353 if (keysToRemoveFromGRD.size === 0)
354 return;
355
356 let errorStr =
357 '\nThe message(s) associated with the following IDS key(s) should be removed from its GRD/GRDP file(s):\n';
358 // Example error message:
Mandy Chen4a7ad052019-07-16 16:09:29 +0000359 // third_party/blink/renderer/devtools/front_end/accessibility/accessibility_strings.grdp Line 300: IDS_DEVTOOLS_c9bbad3047af039c14d0e7ec957bb867
360 for (const [ids, messages] of keysToRemoveFromGRD) {
361 messages.forEach(
362 message => errorStr += `${localizationUtils.getRelativeFilePathFromSrc(message.grdpPath)}${
363 localizationUtils.getLocationMessage(message.location)}: ${ids}\n\n`);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000364 }
365 return errorStr;
366}
367
Mandy Chen81d4fc42019-07-11 23:12:02 +0000368function getAndReportIDSKeysToModify() {
369 const messagesToModify = getIDSKeysToModify();
370 if (messagesToModify.size === 0)
371 return;
372
373 let errorStr = '\nThe following GRD/GRDP message(s) do not have the correct IDS key.\n';
374 errorStr += 'Please update the key(s) by changing the "name" value.\n\n';
375
Mandy Chen4a7ad052019-07-16 16:09:29 +0000376 for (const [expectedIDSKey, messages] of messagesToModify) {
377 messages.forEach(
378 message => errorStr += `${localizationUtils.getRelativeFilePathFromSrc(message.grdpPath)}${
379 localizationUtils.getLocationMessage(
380 message.location)}:\n${message.actualIDSKey} --> ${expectedIDSKey}\n\n`);
Mandy Chen81d4fc42019-07-11 23:12:02 +0000381 }
382 return errorStr;
383}
384
Mandy Chen4a7ad052019-07-16 16:09:29 +0000385function getMessagesToAdd() {
386 // If a message with ids key exists in grdpPath
387 function messageExists(ids, grdpPath) {
388 const messages = IDSkeys.get(ids);
389 return messages.some(message => message.grdpPath === grdpPath);
390 }
391
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000392 const difference = [];
Mandy Chen4a7ad052019-07-16 16:09:29 +0000393 for (const [ids, frontendString] of frontendStrings) {
394 if (!IDSkeys.has(ids) || !messageExists(ids, frontendString.grdpPath))
395 difference.push([ids, frontendString]);
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000396 }
397 return new Map(difference.sort());
398}
399
Mandy Chen4a7ad052019-07-16 16:09:29 +0000400// Return a map from the expected IDS key to a list of messages
401// whose actual IDS keys need to be modified.
Mandy Chen81d4fc42019-07-11 23:12:02 +0000402function getIDSKeysToModify() {
403 const messagesToModify = new Map();
Mandy Chen4a7ad052019-07-16 16:09:29 +0000404 for (const [expectedIDSKey, messages] of IDSkeys) {
405 for (const message of messages) {
406 if (expectedIDSKey !== message.actualIDSKey) {
407 if (messagesToModify.has(expectedIDSKey))
408 messagesToModify.get(expectedIDSKey).push(message);
409 else
410 messagesToModify.set(expectedIDSKey, [message]);
411 }
412 }
Mandy Chen81d4fc42019-07-11 23:12:02 +0000413 }
414 return messagesToModify;
415}
416
Mandy Chen4a7ad052019-07-16 16:09:29 +0000417function getMessagesToRemove() {
418 const difference = new Map();
419 for (const [ids, messages] of IDSkeys) {
420 if (!frontendStrings.has(ids)) {
421 difference.set(ids, messages);
422 continue;
423 }
424
425 const expectedGrdpPath = frontendStrings.get(ids).grdpPath;
426 const messagesInGrdp = [];
427 const messagesToRemove = [];
428 messages.forEach(message => {
429 if (message.grdpPath !== expectedGrdpPath)
430 messagesToRemove.push(message);
431 else
432 messagesInGrdp.push(message);
433 });
434
435 if (messagesToRemove.length === 0 && messagesInGrdp.length === 1)
436 continue;
437
438 if (messagesInGrdp.length > 1) {
439 // If there are more than one messages with ids in the
440 // expected grdp file, keep one with the longest
441 // description and delete all the other messages
442 const longestDescription = getLongestDescription(messagesInGrdp);
443 let foundMessageToKeep = false;
444 for (const message of messagesInGrdp) {
445 if (message.description === longestDescription && !foundMessageToKeep) {
446 foundMessageToKeep = true;
447 continue;
448 }
449 messagesToRemove.push(message);
450 }
451 }
452 difference.set(ids, messagesToRemove);
453 }
454 return difference;
455}
456
457function getLongestDescription(messages) {
458 let longestDescription = '';
459 messages.forEach(message => {
460 if (message.description.length > longestDescription.length)
461 longestDescription = message.description;
462 });
463 return longestDescription;
464}
465
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000466module.exports = {
Mandy Chenc94d52a2019-06-11 22:51:53 +0000467 frontendStrings,
468 IDSkeys,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000469 parseLocalizableResourceMaps,
Mandy Chen81d4fc42019-07-11 23:12:02 +0000470 getAndReportIDSKeysToModify,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000471 getAndReportResourcesToAdd,
472 getAndReportResourcesToRemove,
Mandy Chen4a7ad052019-07-16 16:09:29 +0000473 getIDSKeysToModify,
474 getLongestDescription,
475 getMessagesToAdd,
476 getMessagesToRemove,
Lorne Mitchellc56ff2d2019-05-28 23:35:03 +0000477};