Skip to content

Commit d61797a

Browse files
committed
ASTUtils: support template strings in getStringArray
1 parent 51cf739 commit d61797a

File tree

2 files changed

+32
-7
lines changed

2 files changed

+32
-7
lines changed

lib/lbt/utils/ASTUtils.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,15 @@ function getValue(obj, names) {
131131
*/
132132
function getStringArray(array, skipNonStringLiterals) {
133133
return array.elements.reduce( (result, item) => {
134-
if ( isString(item) ) {
135-
result.push(item.value);
134+
const value = getStringValue(item);
135+
if ( value !== undefined ) {
136+
result.push(value);
136137
} else if ( !skipNonStringLiterals ) {
137-
throw new TypeError("array element is not a string literal:" + item.type);
138+
if (item.type === Syntax.TemplateLiteral) {
139+
throw new TypeError("array element is a template literal with expressions");
140+
} else {
141+
throw new TypeError("array element is not a string literal: " + item.type);
142+
}
138143
}
139144
return result;
140145
}, []);

test/lib/lbt/utils/ASTUtils.js

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,16 +129,36 @@ test("isMethodCall", (t) => {
129129

130130
test("getStringArray", (t) => {
131131
const array = parseJS("['a', 5]").body[0].expression;
132-
const error = t.throws(() => {
132+
t.throws(() => {
133133
ASTUtils.getStringArray(array);
134-
}, {instanceOf: TypeError}, "array contains a number");
135-
136-
t.deepEqual(error.message, "array element is not a string literal:Literal");
134+
}, {
135+
instanceOf: TypeError,
136+
message: "array element is not a string literal: Literal"
137+
}, "array contains a number");
137138

138139
const stringArray = parseJS("['a', 'x']").body[0].expression;
139140
t.deepEqual(ASTUtils.getStringArray(stringArray), ["a", "x"], "array contains only strings");
140141
});
141142

143+
test("getStringArray (skipNonStringLiterals=true)", (t) => {
144+
const array = parseJS("['a', `x`, true, 5, `${foo}`, {}]").body[0].expression;
145+
t.deepEqual(ASTUtils.getStringArray(array, true), ["a", "x"], "result contains only strings");
146+
});
147+
148+
test("getStringArray (template literal)", (t) => {
149+
const array = parseJS("[`a`, `${a}`]").body[0].expression;
150+
t.throws(() => {
151+
ASTUtils.getStringArray(array);
152+
}, {
153+
instanceOf: TypeError,
154+
message: "array element is a template literal with expressions"
155+
});
156+
157+
const stringArray = parseJS("[`a`, 'x']").body[0].expression;
158+
t.deepEqual(ASTUtils.getStringArray(stringArray), ["a", "x"],
159+
"array contains only strings or template literals without expressions");
160+
});
161+
142162
test("getLocation", (t) => {
143163
t.deepEqual(ASTUtils.getLocation([{value: "module/name"}]), "module/name");
144164
});

0 commit comments

Comments
 (0)