-
Notifications
You must be signed in to change notification settings - Fork 0
/
string-literals.js
68 lines (60 loc) · 1.8 KB
/
string-literals.js
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
/*
* Copyright (c) [2023] SUSE LLC
*
*/
// names of all translation functions
const translations = ["_", "n_", "N_", "Nn_"];
// names of the plural translation functions
const plurals = ["n_", "Nn_"];
const errorMsgLiteral = "Use a string literal argument in the translation functions";
const errorMsgMissing = "Missing argument";
/**
* Check whether the AST tree node is a string literal
* @param {Object} node the node
* @returns {boolean} true if the node is a string literal
*/
function isStringLiteral(node) {
if (!node) return false;
return node.type === "Literal" && (typeof node.value === "string");
}
/**
* Check whether the ATS node is a string literal
* @param {Object} node the node to check
* @param {Object} parentNode parent node for reporting error if `node` is undefined
* @param {Object} context the context for reporting an error
*/
function checkNode(node, parentNode, context) {
if (node) {
// string literal?
if (!isStringLiteral(node)) {
context.report(node, errorMsgLiteral);
}
} else {
// missing argument
context.report(parentNode, errorMsgMissing);
}
}
// define the eslint rule
module.exports = {
meta: {
type: "problem",
docs: {
description: "Check that only string literals are passed to the translation functions.",
},
},
create: function (context) {
return {
// callback for handling function calls
CallExpression(node) {
// not a translation function, skip it
if (!translations.includes(node.callee.name)) return;
// check the first argument
checkNode(node.arguments[0], node, context);
// check also the second argument for the plural forms
if (plurals.includes(node.callee.name)) {
checkNode(node.arguments[1], node, context);
}
}
};
}
};