From 7e54a13d062f66eadb849876ea3f8bc33b58fb67 Mon Sep 17 00:00:00 2001 From: Mark Hazleton Date: Sat, 21 Nov 2026 10:31:58 -0600 Subject: [PATCH 1/2] fix(cli): accept glob patterns in --path and honor --branch with --path --path is passed to `git log -- ` as a Git pathspec, but validateOptions checked it as a regular expression, so globs like `src/**` were rejected. Validate it as a pathspec instead, reusing validatePathString (disallowed characters, traversal, length). The collector also put the branch after `--`, where git reads it as a second pathspec, so --branch was silently ignored whenever --path was set. The revision now comes before `--`. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++ src/core/collector.ts | 3 +- src/utils/validation.ts | 44 +++++------------------- test/collector-regression.test.ts | 21 ++++++++++++ test/validation.test.ts | 56 +++++++++++++++++++------------ 5 files changed, 72 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bede096..ef01af9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- `--path` accepts Git glob patterns such as `src/**` and `src/core/*.ts`. It was validated as a regular expression, so `**` failed with "Path pattern is not a valid regex pattern" even though the value is passed to Git as a pathspec +- `--branch` combined with `--path` now analyzes the requested branch. The branch was placed after Git's `--` separator, so Git read it as a second path and analyzed the current branch instead + ## [2.0.2] - 2026-11-21 ### Added diff --git a/src/core/collector.ts b/src/core/collector.ts index 12b5f9a..55f3a58 100644 --- a/src/core/collector.ts +++ b/src/core/collector.ts @@ -185,8 +185,9 @@ export class DataCollector { if (safeOptions.since) args.push('--since', safeOptions.since); if (safeOptions.until) args.push('--until', safeOptions.until); if (safeOptions.author) args.push('--author', safeOptions.author); - if (safeOptions.path) args.push('--', safeOptions.path); + // The revision must come before `--`; anything after it is read as a pathspec. if (safeOptions.branch) args.push(safeOptions.branch); + if (safeOptions.path) args.push('--', safeOptions.path); const { spawn } = await import('child_process'); const child = spawn('git', args, { cwd: this.repoPath }); diff --git a/src/utils/validation.ts b/src/utils/validation.ts index 039e509..0bc2fb2 100644 --- a/src/utils/validation.ts +++ b/src/utils/validation.ts @@ -2,6 +2,7 @@ import { GitSparkOptions, ValidationResult, ValidationError } from '../types/ind import { existsSync, statSync } from 'fs'; import { resolve } from 'path'; import * as semver from 'semver'; +import { validatePathString } from './input-validation.js'; /** * Validates Git Spark CLI options for correctness and safety. @@ -108,43 +109,16 @@ export function validateOptions(options: GitSparkOptions): ValidationResult { } } - // Validate path pattern + // Validate path pattern. It is passed to `git log -- ` as a Git pathspec (a glob such as + // `src/**` or `*.ts`), never compiled or executed as a regular expression. if (options.path) { - try { - // Sanitize input: limit length and check for balanced parentheses - if (options.path.length > 500) { - errors.push('Path pattern is too long (max 500 characters)'); - } - - // Check for balanced parentheses to prevent malformed regex - const openParens = (options.path.match(/\(/g) || []).length; - const closeParens = (options.path.match(/\)/g) || []).length; - if (openParens !== closeParens) { - errors.push('Path pattern has unbalanced parentheses'); - } - - // Check for potentially dangerous regex patterns that could cause ReDoS - // Detect these specific patterns in the user's input string - const hasNestedStarPlus = options.path.includes('(.*)+') || options.path.includes('(.*)*.js'); - const hasRepeatedEscapedDot = - options.path.includes('\\.\\+\\.\\+') || options.path.includes('\\.\\*\\.\\*'); - const hasNestedWordQuant = options.path.includes('(\\w+*)+'); - const hasNestedCharClass = options.path.includes('([a-z]+)+'); - - if (hasNestedStarPlus || hasRepeatedEscapedDot || hasNestedWordQuant || hasNestedCharClass) { - errors.push( - 'Path pattern contains potentially dangerous regex that could cause performance issues' - ); - } else { - // Validate regex syntax only — never execute user-supplied patterns to prevent ReDoS - try { - new RegExp(options.path); - } catch (e) { - errors.push('Path pattern is not a valid regex pattern'); - } + if (options.path.length > 500) { + errors.push('Path pattern is too long (max 500 characters)'); + } else { + const pathCheck = validatePathString(options.path); + if (!pathCheck.isValid) { + errors.push(`Path pattern is not allowed: ${pathCheck.error}`); } - } catch (e) { - errors.push('Path pattern is not a valid regex pattern'); } } diff --git a/test/collector-regression.test.ts b/test/collector-regression.test.ts index 0ca6c97..0e4efac 100644 --- a/test/collector-regression.test.ts +++ b/test/collector-regression.test.ts @@ -74,6 +74,27 @@ describe('DataCollector streaming parser regression', () => { } }); + it('filters commits with a glob path pattern', async () => { + const commits = await new DataCollector(tmp).collectCommits({ repoPath: tmp, path: 'dir/**' }); + const subjects = commits.map(c => c.subject).sort(); + expect(subjects).toEqual([ + 'chore: second commit with more changes', + 'refactor: third commit touching multiple files', + ]); + expect(commits.every(c => c.files.every(f => f.path.startsWith('dir/')))).toBe(true); + }); + + it('applies the branch when combined with a path filter', async () => { + // The revision must precede `--`; after it, git reads the branch name as a path + execSync('git branch path-filter-base HEAD~1', { cwd: tmp }); + const commits = await new DataCollector(tmp).collectCommits({ + repoPath: tmp, + branch: 'path-filter-base', + path: 'dir/**', + }); + expect(commits.map(c => c.subject)).toEqual(['chore: second commit with more changes']); + }); + it('caps --days to the first commit with a full timestamp, not a bare date', async () => { // A bare YYYY-MM-DD makes git use the current time of day, which drops recent // commits whenever the local and UTC dates differ (e.g. US evenings) diff --git a/test/validation.test.ts b/test/validation.test.ts index 699a13d..b634db1 100644 --- a/test/validation.test.ts +++ b/test/validation.test.ts @@ -94,38 +94,52 @@ describe('Validation Utils', () => { expect(result.warnings.some(w => w.includes('Author filter is very short'))).toBe(true); }); - it('should reject invalid path pattern', () => { + it('should accept glob path patterns', () => { + const globPatterns = ['src/**', 'src/core/**', 'src/core/*.ts', '*.md', 'src/core', 'src/?ore']; + + globPatterns.forEach(pattern => { + const result = validateOptions({ path: pattern }); + expect(result.errors).toEqual([]); + expect(result.isValid).toBe(true); + }); + }); + + it('should reject path patterns with disallowed characters', () => { const options: GitSparkOptions = { - path: '[invalid-regex', + path: '[invalid', }; const result = validateOptions(options); - expect(result.errors.some(e => e.includes('Path pattern'))).toBe(true); + expect(result.errors.some(e => e.includes('Path pattern is not allowed'))).toBe(true); expect(result.isValid).toBe(false); }); - it('should reject ReDoS patterns in path', () => { - const buildPattern = (...codes: number[]): string => String.fromCharCode(...codes); + it('should reject path patterns with directory traversal', () => { + const result = validateOptions({ path: '../outside/**' }); + expect(result.errors.some(e => e.includes('directory traversal'))).toBe(true); + expect(result.isValid).toBe(false); + }); - // Build test inputs at runtime so this test does not itself embed - // dangerous regex literals while still exercising the validator. - const dangerousPatterns = [ - buildPattern(40, 46, 42, 41, 43, 116, 101, 115, 116), - buildPattern(40, 46, 42, 41, 42, 46, 106, 115), - buildPattern(92, 46, 92, 43, 92, 46, 92, 43, 92, 46, 92, 43), - buildPattern(92, 46, 92, 42, 92, 46, 92, 42, 92, 46, 92, 42), - buildPattern(40, 92, 119, 43, 42, 41, 43), - buildPattern(40, 91, 97, 45, 122, 93, 43, 41, 43), - ]; + it('should reject overly long path patterns', () => { + const result = validateOptions({ path: 'a'.repeat(501) }); + expect(result.errors).toContain('Path pattern is too long (max 500 characters)'); + expect(result.isValid).toBe(false); + }); - dangerousPatterns.forEach(pattern => { - const options: GitSparkOptions = { - path: pattern, - }; + it('should reject former regex-style path patterns', () => { + const buildPattern = (...codes: number[]): string => String.fromCharCode(...codes); + + // Regex syntax such as groups and escapes is not valid in a path filter. + const regexPatterns = [ + buildPattern(40, 46, 42, 41, 43, 116, 101, 115, 116), + buildPattern(92, 46, 92, 43, 92, 46, 92, 43, 92, 46, 92, 43), + buildPattern(40, 91, 97, 45, 122, 93, 43, 41, 43), + ]; - const result = validateOptions(options); + regexPatterns.forEach(pattern => { + const result = validateOptions({ path: pattern }); expect(result.isValid).toBe(false); - expect(result.errors.some(e => e.includes('dangerous regex'))).toBe(true); + expect(result.errors.some(e => e.includes('Path pattern is not allowed'))).toBe(true); }); }); From 9f379907a4b74605f0d0bd57590a09fbf7083e01 Mon Sep 17 00:00:00 2001 From: Mark Hazleton Date: Sat, 21 Nov 2026 10:41:15 -0600 Subject: [PATCH 2/2] fix(collector): keep the oldest commit when its body spans lines git log emits the oldest commit last, and that record was parsed by the stream close handler, which treated the first newline as the end of the header. A multi-line commit body therefore looked like a header with too few fields, and the commit was silently dropped, so any range whose oldest commit had a detailed message lost one commit. Parse every record with one helper that ends the header at the first newline after the 7th field separator, both while streaming and at close. The regression test now asserts all 3 commits instead of >= 2, which had hidden the bug. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + src/core/collector.ts | 142 ++++++++++-------------------- test/collector-regression.test.ts | 11 ++- 3 files changed, 59 insertions(+), 95 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef01af9..98430e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `--path` accepts Git glob patterns such as `src/**` and `src/core/*.ts`. It was validated as a regular expression, so `**` failed with "Path pattern is not a valid regex pattern" even though the value is passed to Git as a pathspec - `--branch` combined with `--path` now analyzes the requested branch. The branch was placed after Git's `--` separator, so Git read it as a second path and analyzed the current branch instead +- The oldest commit in the analyzed range is no longer dropped when its message has a multi-line body. The last record of the Git log stream was parsed as if its header ended at the first newline, so a body spanning several lines made it look malformed and it was silently skipped, undercounting commits, churn, and files in any window or path filter whose oldest commit had a detailed message ## [2.0.2] - 2026-11-21 diff --git a/src/core/collector.ts b/src/core/collector.ts index 55f3a58..72790a9 100644 --- a/src/core/collector.ts +++ b/src/core/collector.ts @@ -205,6 +205,49 @@ export class DataCollector { } }; + // Parse one \x1e-delimited record. Returns false when the record is still incomplete. + // The header has 8 \x1f-separated fields (hash..parents); the body (%b) may contain + // newlines, so the header ends at the first newline after the 7th separator, not the + // first newline in the record. Numstat lines follow the header. + const processRecord = (record: string, isFinal: boolean): boolean => { + let sepIdx = -1; + let sepCount = 0; + for (let i = 0; i < record.length; i++) { + if (record.charCodeAt(i) === 0x1f && ++sepCount === 7) { + sepIdx = i; + break; + } + } + if (sepIdx === -1) { + if (isFinal) warnings.push('Malformed commit header encountered (insufficient fields)'); + return isFinal; + } + + let headerEnd = record.indexOf('\n', sepIdx + 1); + if (headerEnd === -1) { + // Parents field not terminated yet; at end of stream the record ends here + if (!isFinal) return false; + headerEnd = record.length; + } + + currentCommit = this.parseCommitHeader(record.slice(0, headerEnd).split('\x1f')); + for (const line of record.slice(headerEnd + 1).split('\n')) { + if (!line.trim()) continue; + const fileChange = this.parseFileStats(line.replace(/\r$/, '')); + if (fileChange) { + currentCommit.files = currentCommit.files || []; + currentCommit.files.push(fileChange); + } + } + finalizeCurrent(); + processed++; + if (processed % 200 === 0 || processed === totalCommits) { + const pct = totalCommits ? Math.min(100, Math.round((processed / totalCommits) * 70)) : 0; + this.reportProgress('Streaming commit collection', pct, 100); + } + return true; + }; + child.stdout.on('data', (chunk: Buffer) => { buffer += chunk.toString(); // Split on record separator (each commit starts with \x1e) @@ -212,74 +255,9 @@ export class DataCollector { buffer = records.pop() || ''; for (const record of records) { if (!record.trim()) continue; - - // We need 7 field separators (\x1f) to yield 8 header fields (hash..parents) - // The commit body (%b) may contain newlines, so the header can span multiple lines - // until the parents field is encountered. Only after the parents field do file - // change (numstat) lines begin on subsequent lines. - // Count field separators (0x1F) without regex to satisfy lint (no-control-regex) - let fieldSepCount = 0; - for (let i = 0; i < record.length; i++) { - if (record.charCodeAt(i) === 0x1f) fieldSepCount++; - } - if (fieldSepCount < 7) { - // Incomplete header (body truncated across chunk) - re-buffer + if (!processRecord(record, false)) { + // Incomplete record - re-buffer until more data arrives buffer = '\x1e' + record + buffer; - continue; - } - - // Find the index of the 7th separator to know where parents field starts - let sepCount = 0; - let idx = -1; - for (let i = 0; i < record.length; i++) { - if (record[i] === '\x1f') { - sepCount++; - if (sepCount === 7) { - // after this comes the parents field value - // Find newline ending the parents field - const newlineAfterParents = record.indexOf('\n', i + 1); - if (newlineAfterParents === -1) { - // Parents field not terminated yet; wait for more data - buffer = '\x1e' + record + buffer; - idx = -1; - } else { - idx = newlineAfterParents; // header ends here - } - break; - } - } - } - - if (idx === -1) { - continue; // wait for more data - } - - const headerLine = record.slice(0, idx); - const parts = headerLine.split('\x1f'); - if (parts.length < 8) { - warnings.push('Malformed commit header encountered (insufficient fields)'); - continue; - } - currentCommit = this.parseCommitHeader(parts); - - // Remainder after header newline are numstat lines (may contain blank line at end) - const remainder = record.slice(idx + 1); - if (remainder) { - const lines = remainder.split('\n'); - for (const l of lines) { - if (!l.trim()) continue; - const fileChange = this.parseFileStats(l.replace(/\r$/, '')); - if (fileChange) { - currentCommit.files = currentCommit.files || []; - currentCommit.files.push(fileChange); - } - } - } - finalizeCurrent(); - processed++; - if (processed % 200 === 0 || processed === totalCommits) { - const pct = totalCommits ? Math.min(100, Math.round((processed / totalCommits) * 70)) : 0; - this.reportProgress('Streaming commit collection', pct, 100); } } }); @@ -287,33 +265,9 @@ export class DataCollector { await new Promise((resolve, reject) => { child.on('error', (e: Error) => reject(e)); child.on('close', () => { - // Process any remaining buffered (partial) record - if (buffer.trim()) { - const newlineIdx = buffer.indexOf('\n'); - if (newlineIdx !== -1) { - const headerLine = buffer.slice(0, newlineIdx); - let fieldSepCount = 0; - for (let i = 0; i < headerLine.length; i++) { - if (headerLine.charCodeAt(i) === 0x1f) fieldSepCount++; - } - if (fieldSepCount >= 7) { - const parts = headerLine.split('\x1f'); - if (parts.length >= 8) { - currentCommit = this.parseCommitHeader(parts); - const remainder = buffer.slice(newlineIdx + 1); - const lines = remainder ? remainder.split('\n') : []; - for (const l of lines) { - if (!l.trim()) continue; - const fc = this.parseFileStats(l); - if (fc) { - currentCommit.files = currentCommit.files || []; - currentCommit.files.push(fc); - } - } - finalizeCurrent(); - } - } - } + // The last record (the oldest commit) has no following \x1e, so it is still buffered + for (const record of buffer.split('\x1e')) { + if (record.trim()) processRecord(record, true); } resolve(); }); diff --git a/test/collector-regression.test.ts b/test/collector-regression.test.ts index 0e4efac..d6d0539 100644 --- a/test/collector-regression.test.ts +++ b/test/collector-regression.test.ts @@ -55,11 +55,20 @@ describe('DataCollector streaming parser regression', () => { it('parses multiple commits via streaming parser', async () => { const collector = new DataCollector(tmp); const commits = await collector.collectCommits({ repoPath: tmp }); - expect(commits.length).toBeGreaterThanOrEqual(2); + expect(commits.length).toBe(3); // Ensure subjects are captured and not empty expect(commits.every(c => c.subject.length > 0)).toBe(true); }); + it('keeps the oldest commit when its message has a multi-line body', async () => { + // git emits the oldest commit last; its record is parsed when the stream closes + const commits = await new DataCollector(tmp).collectCommits({ repoPath: tmp }); + const first = commits.find(c => c.subject === 'feat: first commit'); + expect(first).toBeTruthy(); + expect(first?.body).toContain('line two of body with details'); + expect(first?.files.map(f => f.path)).toEqual(['file1.txt']); + }); + it('extracts file stats for each commit correctly', async () => { const collector = new DataCollector(tmp); const commits = await collector.collectCommits({ repoPath: tmp });