Skip to content

Commit

Permalink
Improve escaping path separators for regexp on Windows (#6523)
Browse files Browse the repository at this point in the history
  • Loading branch information
hron authored and SimenB committed Jul 3, 2018
1 parent d6e0a1b commit e8a8f62
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

- `[jest-snapshot]` Introduce `toMatchInlineSnapshot` and `toThrowErrorMatchingInlineSnapshot` matchers ([#6380](https://github.com/facebook/jest/pull/6380))

### Fixes

- `[jest-regex-util]` Improve handling already escaped path separators on Windows ([#6523](https://github.com/facebook/jest/pull/6523))

### Chore & Maintenance

- `[website]` Switch domain to https://jestjs.io ([#6549](https://github.com/facebook/jest/pull/6549))
Expand Down
20 changes: 13 additions & 7 deletions packages/jest-regex-util/src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,23 @@ describe('replacePathSepForRegex()', () => {

it('should not escape an escaped dot', () => {
expect(replacePathSepForRegex('a\\.dotfile')).toBe('a\\.dotfile');

// If we expect Windows path separators to be escaped, one would expect
// the regular expression "\\\." to be unescaped as "\.". This is not the
// current behavior.
expect(replacePathSepForRegex('a\\\\\\.dotfile')).toBe(
'a\\\\\\\\\\.dotfile',
);
expect(replacePathSepForRegex('a\\\\\\.dotfile')).toBe('a\\\\\\.dotfile');
});

it('should not escape an escaped regexp symbol', () => {
expect(replacePathSepForRegex('b\\(86')).toBe('b\\(86');
});

it('should escape Windows path separators inside groups', () => {
expect(replacePathSepForRegex('[/\\\\]')).toBe('[\\\\\\\\]');
});

it('should escape Windows path separator at the beginning', () => {
expect(replacePathSepForRegex('\\a')).toBe('\\\\a');
});

it('should not escape several already escaped path separators', () => {
expect(replacePathSepForRegex('\\\\\\\\')).toBe('\\\\\\\\');
});
});
});
5 changes: 4 additions & 1 deletion packages/jest-regex-util/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ export const escapeStrForRegex = (string: string) =>

export const replacePathSepForRegex = (string: string) => {
if (path.sep === '\\') {
return string.replace(/(\/|\\(?![[\]{}()*+?.^$|]))/g, '\\\\');
return string.replace(
/(\/|(.)?\\(?![[\]{}()*+?.^$|\\]))/g,
(_match, p1, p2) => (p2 && p2 !== '\\' ? p2 + '\\\\' : '\\\\'),
);
}
return string;
};

0 comments on commit e8a8f62

Please sign in to comment.