fix(localize): improve matching and parsing of XTB translation files (#35793)

This commit improves the `canParse()` method to check that the file is
valid XML and has the expected root node. Previously it was relying upon
a regular expression to do this.

PR Close #35793
This commit is contained in:
Pete Bacon Darwin
2020-03-09 12:11:58 -04:00
committed by Matias Niemelä
parent 08071e5634
commit 0e2a577b42
2 changed files with 433 additions and 85 deletions
@@ -5,7 +5,7 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Element, Node, XmlParser, visitAll} from '@angular/compiler';
import {Element, ParseErrorLevel, visitAll} from '@angular/compiler';
import {ɵParsedTranslation} from '@angular/localize';
import {extname} from 'path';
@@ -14,87 +14,100 @@ import {BaseVisitor} from '../base_visitor';
import {MessageSerializer} from '../message_serialization/message_serializer';
import {TargetMessageRenderer} from '../message_serialization/target_message_renderer';
import {TranslationParseError} from './translation_parse_error';
import {ParsedTranslationBundle, TranslationParser} from './translation_parser';
import {getAttrOrThrow, parseInnerRange} from './translation_utils';
import {XmlTranslationParserHint, addParseDiagnostic, addParseError, canParseXml, getAttribute, parseInnerRange} from './translation_utils';
/**
* A translation parser that can load XB files.
*/
export class XtbTranslationParser implements TranslationParser {
constructor(private diagnostics: Diagnostics = new Diagnostics()) {}
canParse(filePath: string, contents: string): boolean {
export class XtbTranslationParser implements TranslationParser<XmlTranslationParserHint> {
canParse(filePath: string, contents: string): XmlTranslationParserHint|false {
const extension = extname(filePath);
return (extension === '.xtb' || extension === '.xmb') &&
contents.includes('<translationbundle');
if (extension !== '.xtb' && extension !== '.xmb') {
return false;
}
return canParseXml(filePath, contents, 'translationbundle', {});
}
parse(filePath: string, contents: string): ParsedTranslationBundle {
const xmlParser = new XmlParser();
const xml = xmlParser.parse(contents, filePath);
const bundle = XtbVisitor.extractBundle(this.diagnostics, xml.rootNodes);
if (bundle === undefined) {
throw new Error(`Unable to parse "${filePath}" as XTB/XMB format.`);
parse(filePath: string, contents: string, hint?: XmlTranslationParserHint):
ParsedTranslationBundle {
if (hint) {
return this.extractBundle(hint);
} else {
return this.extractBundleDeprecated(filePath, contents);
}
}
private extractBundle({element, errors}: XmlTranslationParserHint): ParsedTranslationBundle {
const langAttr = element.attrs.find((attr) => attr.name === 'lang');
const bundle: ParsedTranslationBundle = {
locale: langAttr && langAttr.value,
translations: {},
diagnostics: new Diagnostics()
};
errors.forEach(e => addParseError(bundle.diagnostics, e));
const bundleVisitor = new XtbVisitor();
visitAll(bundleVisitor, element.children, bundle);
return bundle;
}
private extractBundleDeprecated(filePath: string, contents: string) {
const hint = this.canParse(filePath, contents);
if (!hint) {
throw new Error(`Unable to parse "${filePath}" as XMB/XTB format.`);
}
const bundle = this.extractBundle(hint);
if (bundle.diagnostics.hasErrors) {
const message =
bundle.diagnostics.formatDiagnostics(`Failed to parse "${filePath}" as XMB/XTB format`);
throw new Error(message);
}
return bundle;
}
}
class XtbVisitor extends BaseVisitor {
static extractBundle(diagnostics: Diagnostics, messageBundles: Node[]): ParsedTranslationBundle
|undefined {
const visitor = new this(diagnostics);
const bundles: ParsedTranslationBundle[] = visitAll(visitor, messageBundles, undefined);
return bundles[0];
}
constructor(private diagnostics: Diagnostics) { super(); }
visitElement(element: Element, bundle: ParsedTranslationBundle|undefined): any {
visitElement(element: Element, bundle: ParsedTranslationBundle): any {
switch (element.name) {
case 'translationbundle':
if (bundle) {
throw new TranslationParseError(
element.sourceSpan, '<translationbundle> elements can not be nested');
}
const langAttr = element.attrs.find((attr) => attr.name === 'lang');
bundle = {
locale: langAttr && langAttr.value,
translations: {},
diagnostics: this.diagnostics
};
visitAll(this, element.children, bundle);
return bundle;
case 'translation':
if (!bundle) {
throw new TranslationParseError(
element.sourceSpan, '<translation> must be inside a <translationbundle>');
// Error if no `id` attribute
const id = getAttribute(element, 'id');
if (id === undefined) {
addParseDiagnostic(
bundle.diagnostics, element.sourceSpan,
`Missing required "id" attribute on <trans-unit> element.`, ParseErrorLevel.ERROR);
return;
}
const id = getAttrOrThrow(element, 'id');
if (bundle.translations.hasOwnProperty(id)) {
throw new TranslationParseError(
element.sourceSpan, `Duplicated translations for message "${id}"`);
} else {
try {
bundle.translations[id] = serializeTargetMessage(element);
} catch (error) {
if (typeof error === 'string') {
this.diagnostics.warn(
`Could not parse message with id "${id}" - perhaps it has an unrecognised ICU format?\n` +
error);
} else {
throw error;
}
// Error if there is already a translation with the same id
if (bundle.translations[id] !== undefined) {
addParseDiagnostic(
bundle.diagnostics, element.sourceSpan, `Duplicated translations for message "${id}"`,
ParseErrorLevel.ERROR);
return;
}
try {
bundle.translations[id] = serializeTargetMessage(element);
} catch (error) {
if (typeof error === 'string') {
bundle.diagnostics.warn(
`Could not parse message with id "${id}" - perhaps it has an unrecognised ICU format?\n` +
error);
} else if (error.span && error.msg && error.level) {
addParseDiagnostic(bundle.diagnostics, error.span, error.msg, error.level);
} else {
throw error;
}
}
break;
default:
throw new TranslationParseError(element.sourceSpan, 'Unexpected tag');
addParseDiagnostic(
bundle.diagnostics, element.sourceSpan, `Unexpected <${element.name}> tag.`,
ParseErrorLevel.ERROR);
}
}
}