From 5c2bb990d895254e6563acfd26946c389125387f Mon Sep 17 00:00:00 2001 From: fuyou Date: Wed, 3 Sep 2025 14:19:20 +0800 Subject: [PATCH] fix(gitIgnore): prevent crash/error when processing malformed file paths in GitIgnoreParser (#7553) Co-authored-by: Srinath Padmanabhan <17151014+srithreepo@users.noreply.github.com> --- .../core/src/utils/gitIgnoreParser.test.ts | 10 ++++++ packages/core/src/utils/gitIgnoreParser.ts | 35 +++++++++++++++---- 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/packages/core/src/utils/gitIgnoreParser.test.ts b/packages/core/src/utils/gitIgnoreParser.test.ts index ca76095a1a..2330de1261 100644 --- a/packages/core/src/utils/gitIgnoreParser.test.ts +++ b/packages/core/src/utils/gitIgnoreParser.test.ts @@ -181,6 +181,16 @@ src/*.tmp expect(() => parser.isIgnored('/node_modules')).not.toThrow(); expect(parser.isIgnored('/node_modules')).toBe(false); }); + + it('should handle backslash-prefixed files without crashing', () => { + expect(() => parser.isIgnored('\\backslash-file-test.txt')).not.toThrow(); + expect(parser.isIgnored('\\backslash-file-test.txt')).toBe(false); + }); + + it('should handle files with absolute-like names', () => { + expect(() => parser.isIgnored('/backslash-file-test.txt')).not.toThrow(); + expect(parser.isIgnored('/backslash-file-test.txt')).toBe(false); + }); }); describe('getIgnoredPatterns', () => { diff --git a/packages/core/src/utils/gitIgnoreParser.ts b/packages/core/src/utils/gitIgnoreParser.ts index 177a0d2c9d..1eb5379974 100644 --- a/packages/core/src/utils/gitIgnoreParser.ts +++ b/packages/core/src/utils/gitIgnoreParser.ts @@ -57,16 +57,37 @@ export class GitIgnoreParser implements GitIgnoreFilter { } isIgnored(filePath: string): boolean { - const resolved = path.resolve(this.projectRoot, filePath); - const relativePath = path.relative(this.projectRoot, resolved); - - if (relativePath === '' || relativePath.startsWith('..')) { + if (!filePath || typeof filePath !== 'string') { return false; } - // Even in windows, Ignore expects forward slashes. - const normalizedPath = relativePath.replace(/\\/g, '/'); - return this.ig.ignores(normalizedPath); + if ( + filePath.startsWith('\\') || + filePath === '/' || + filePath.includes('\0') + ) { + return false; + } + + try { + const resolved = path.resolve(this.projectRoot, filePath); + const relativePath = path.relative(this.projectRoot, resolved); + + if (relativePath === '' || relativePath.startsWith('..')) { + return false; + } + + // Even in windows, Ignore expects forward slashes. + const normalizedPath = relativePath.replace(/\\/g, '/'); + + if (normalizedPath.startsWith('/') || normalizedPath === '') { + return false; + } + + return this.ig.ignores(normalizedPath); + } catch (_error) { + return false; + } } getPatterns(): string[] {