Skip to content

Commit c75b461

Browse files
committed
fix: add error for not closed parenthesis in parse-parenthesis-content
1 parent 6766729 commit c75b461

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

src/constant.js

+2
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
11
export const METHOD = 'map-get((';
2+
3+
export const ERROR_PREFIX = 'postcss – map-get';

src/parse-parenthesis-content.js

+13-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import {ERROR_PREFIX} from './constant';
2+
13
/**
24
* Get all the content inside brackets
3-
* @param {string} stringToParse string with parenthesis. This string must start with an `()`
4-
* @param {string} [startingPosition] to start parsing
5+
* @param {string} stringToParse string with parenthesis. This string must start with an `(`
6+
* @param {number} [startingPosition] to start parsing
57
* @returns {{content: string, position: number}} All the content inside parenthesis including nested properties
68
*
79
* @todo might worth to parse the string until a `(` is found?
@@ -11,10 +13,10 @@ export default function parseParenthesisContent(stringToParse, startingPosition
1113
let content = '';
1214

1315
const stack = [];
14-
while (true) { // eslint-disable-line no-constant-condition
16+
while (position !== stringToParse.length) {
1517
const mapChracter = stringToParse[position];
1618
if (mapChracter === '(') {
17-
stack.push(mapChracter);
19+
stack.push(position);
1820
} else if (mapChracter === ')') {
1921
stack.pop();
2022
}
@@ -27,5 +29,12 @@ export default function parseParenthesisContent(stringToParse, startingPosition
2729
}
2830
}
2931

32+
/**
33+
* String should be already validated by postcss but to avoid unclear stacktrace I'll manage the error anyway.
34+
*/
35+
if (stack.length !== 0) {
36+
throw new Error(`${ERROR_PREFIX} – parenthesis not closed`);
37+
}
38+
3039
return {content, position};
3140
}

test/test.parse-parenthesis-content.js

+11
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,14 @@ tests.forEach(({stringToParse, startPosition, expectedContent}, testIndex) => {
3131
t.deepEqual(output.position, expectedPosition);
3232
});
3333
});
34+
35+
test('it should throw an error when number of parenthesis is not exact', t => {
36+
// missing parenthesis position: ↓
37+
const value = '(map-get((corporate: (textColor: green, ea: (textColor: black), corporate), textColor)';
38+
39+
const testError = t.throws(() => {
40+
parseParenthesisContent(value);
41+
}, null);
42+
43+
t.is(testError.message, 'postcss – map-get – parenthesis not closed');
44+
});

0 commit comments

Comments
 (0)