Skip to content

Commit

Permalink
fix: 🐛 inenfficient regex in certain template take a long time
Browse files Browse the repository at this point in the history
  • Loading branch information
shufo committed Aug 20, 2022
1 parent f6ef8b3 commit 28ac4ed
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
10 changes: 10 additions & 0 deletions __tests__/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { spawnSync } from 'child_process';
import { performance } from 'perf_hooks';
import * as cmd from './support/cmd';
import * as util from './support/util';
import { assertFormatted, assertNotFormatted } from './support/assertion';
Expand Down Expand Up @@ -562,4 +563,13 @@ describe('The blade formatter CLI', () => {

expect(cmdResult).toContain(version);
});

test.concurrent('large file', async () => {
const input = 'largefile.blade.php';
const target = 'formatted.largefile.blade.php';
const startTime = performance.now();
await util.checkIfTemplateIsFormattedTwice(input, target);
const endTime = performance.now();
expect(endTime - startTime).toBeLessThan(3000);
});
});
12 changes: 6 additions & 6 deletions src/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,18 +374,18 @@ export default class Formatter {
preserveInlineDirective(content: string): string {
// preserve inline directives inside html tag
const regex = new RegExp(
`(?<=<[\\w\\-\\_]+?[^>]*?)${directivePrefix}(${indentStartTokensWithoutPrefix.join(
`(<[\\w\\-\\_]+?[^>]*?)${directivePrefix}(${indentStartTokensWithoutPrefix.join(
'|',
)})(\\s*?)(\\(.*?\\))(.*?)(@end\\1|@endif)(?=.*?/*>)`,
)})(\\s*?)(\\([^)]*?\\))((?:(?!@end\\2).)+)(@end\\2|@endif)(.*?/*>)`,
'gims',
);
const replaced = _.replace(
content,
regex,
(_match: string, p1: string, p2: string, p3: string, p4: string, p5: string) => {
return `${this.storeInlineDirective(
`${directivePrefix}${p1.trim()}${p2}${p3.trim()} ${p4.trim()} ${p5.trim()}`,
)}`;
(_match: string, p1: string, p2: string, p3: string, p4: string, p5: string, p6: string, p7: string) => {
return `${p1}${this.storeInlineDirective(
`${directivePrefix}${p2.trim()}${p3}${p4.trim()} ${p5.trim()} ${p6.trim()}`,
)}${p7}`;
},
);

Expand Down

0 comments on commit 28ac4ed

Please sign in to comment.