forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwarning-and-invariant-args.js
88 lines (83 loc) · 2.65 KB
/
warning-and-invariant-args.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Copyright 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
/**
* The warning() and invariant() functions take format strings as their second
* argument.
*/
module.exports = function(context) {
// we also allow literal strings and concatinated literal strings
function getLiteralString(node) {
if (node.type === 'Literal' && typeof node.value === 'string') {
return node.value;
} else if (node.type === 'BinaryExpression' && node.operator === '+') {
var l = getLiteralString(node.left);
var r = getLiteralString(node.right);
if (l !== null && r !== null) {
return l + r;
}
}
return null;
}
return {
CallExpression: function(node) {
// This could be a little smarter by checking context.getScope() to see
// how warning/invariant was defined.
var isWarningOrInvariant =
node.callee.type === 'Identifier' &&
(node.callee.name === 'warning' || node.callee.name === 'invariant');
if (!isWarningOrInvariant) {
return;
}
if (node.arguments.length < 2) {
context.report(
node,
'{{name}} takes at least two arguments',
{name: node.callee.name}
);
return;
}
var format = getLiteralString(node.arguments[1]);
if (format === null) {
context.report(
node,
'The second argument to {{name}} must be a string literal',
{name: node.callee.name}
);
return;
}
if (format.length < 10 || /^[s\W]*$/.test(format)) {
context.report(
node,
'The {{name}} format should be able to uniquely identify this ' +
'{{name}}. Please, use a more descriptive format than: {{format}}',
{name: node.callee.name, format: format}
);
return;
}
// count the number of formating substitutions, plus the first two args
var expectedNArgs = (format.match(/%s/g) || []).length + 2;
if (node.arguments.length !== expectedNArgs) {
context.report(
node,
'Expected {{expectedNArgs}} arguments in call to {{name}} based on ' +
'the number of "%s" substitutions, but got {{length}}',
{
expectedNArgs: expectedNArgs,
name: node.callee.name,
length: node.arguments.length,
}
);
}
},
};
};
module.exports.schema = [];