Skip to content

Commit

Permalink
fix: Handle backslashes before opening curly braces
Browse files Browse the repository at this point in the history
  • Loading branch information
ivov committed Dec 2, 2024
1 parent 30da791 commit 21ce421
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
21 changes: 15 additions & 6 deletions src/ExpressionSplitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@ export interface ExpressionCode {

export type ExpressionChunk = ExpressionCode | ExpressionText;

const OPEN_BRACKET = /(?<escape>\\|)(?<brackets>\{\{)/;
const CLOSE_BRACKET = /(?<escape>\\|)(?<brackets>\}\})/;
const OPEN_BRACKET = /(?<brackets>\{\{)/;
const CLOSE_BRACKET = /(?<brackets>\}\})/;

export const escapeCode = (text: string): string => {
return text.replace('\\}}', '}}');
};

const normalizeBackslashes = (text: string): string => {
return text.replace(/\\\\/g, '\\');
};

export const splitExpression = (expression: string): ExpressionChunk[] => {
const chunks: ExpressionChunk[] = [];
let searchingFor: 'open' | 'close' = 'open';
Expand Down Expand Up @@ -51,16 +55,21 @@ export const splitExpression = (expression: string): ExpressionChunk[] => {
}
break;
}
if (res.groups.escape) {
buffer += expr.slice(0, res.index + 3);
index += res.index + 3;

const beforeMatch = expr.slice(0, res.index);
const backslashCount = beforeMatch.match(/\\*$/)?.[0]?.length ?? 0;
const isEscaped = backslashCount % 2 === 1;

if (isEscaped) {
buffer += expr.slice(0, res.index + '{{'.length);
index += res.index + '{{'.length;
} else {
buffer += expr.slice(0, res.index);

if (searchingFor === 'open') {
chunks.push({
type: 'text',
text: buffer,
text: normalizeBackslashes(buffer),
});
searchingFor = 'close';
activeRegex = CLOSE_BRACKET;
Expand Down
20 changes: 20 additions & 0 deletions test/ExpressionSplitter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { splitExpression } from '../src/ExpressionSplitter';

describe('splitExpression', () => {
test('should handle escaping backslashes before double opening curly braces', () => {
const expr = 'C:\\\\Users\\\\Administrator\\\\Desktop\\\\abc\\\\{{ $json.files[0].fileName }}';
const result = splitExpression(expr);

expect(result).toEqual([
{
type: 'text',
text: 'C:\\Users\\Administrator\\Desktop\\abc\\',
},
{
type: 'code',
text: ' $json.files[0].fileName ',
hasClosingBrackets: true,
},
]);
});
});

0 comments on commit 21ce421

Please sign in to comment.