-
Notifications
You must be signed in to change notification settings - Fork 499
/
Copy pathl10n-no-locked-or-placeholder-only-phrase.ts
72 lines (64 loc) · 2.41 KB
/
l10n-no-locked-or-placeholder-only-phrase.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {isUIStringsVariableDeclarator} from './utils/l10n-helper.ts';
import {createRule} from './utils/ruleCreator.ts';
const FULLY_LOCKED_PHRASE_REGEX = /^`[^`]*`$/;
const SINGLE_PLACEHOLDER_REGEX = /^\{\w+\}$/; // Matches the PH regex in `collect-strings.js`.
// Define the rule using the createRule utility
export default createRule({
name: 'l10n-no-locked-or-placeholder-only-phrase',
meta: {
type: 'problem',
docs: {
description:
'UIStrings object literals are not allowed to have phrases that are fully locked, or consist only of a single placeholder.',
category: 'Possible Errors',
},
schema: [], // no options
messages: {
fullyLockedPhrase: 'Locking whole phrases is not allowed. Use i18n.i18n.lockedString instead.',
singlePlaceholderPhrase: 'Single placeholder-only phrases are not allowed. Use i18n.i18n.lockedString instead.',
},
},
defaultOptions: [],
create: function(context) {
return {
VariableDeclarator(node) {
if (!isUIStringsVariableDeclarator(context, node)) {
return;
}
if (node.init?.type !== 'TSAsExpression') {
return;
}
const expression = node.init.expression;
// Check if the expression inside TSAsExpression is an ObjectExpression
if (expression?.type !== 'ObjectExpression') {
return;
}
for (const property of expression.properties) {
// Ensure the property is a standard Property and its value is a Literal
if (property.type !== 'Property' || property.value?.type !== 'Literal') {
continue;
}
const propertyValue = property.value.value;
// Check if the literal value is a string before testing regex
if (typeof propertyValue !== 'string') {
continue;
}
if (FULLY_LOCKED_PHRASE_REGEX.test(propertyValue)) {
context.report({
node: property.value,
messageId: 'fullyLockedPhrase',
});
} else if (SINGLE_PLACEHOLDER_REGEX.test(propertyValue)) {
context.report({
node: property.value,
messageId: 'singlePlaceholderPhrase',
});
}
}
},
};
},
});