Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ 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
- 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

### Added
Expand Down
145 changes: 50 additions & 95 deletions src/core/collector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -204,115 +205,69 @@ 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)
const records = buffer.split('\x1e');
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);
}
}
});

await new Promise<void>((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();
});
Expand Down
44 changes: 9 additions & 35 deletions src/utils/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -108,43 +109,16 @@ export function validateOptions(options: GitSparkOptions): ValidationResult {
}
}

// Validate path pattern
// Validate path pattern. It is passed to `git log -- <path>` 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');
}
}

Expand Down
32 changes: 31 additions & 1 deletion test/collector-regression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -74,6 +83,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)
Expand Down
56 changes: 35 additions & 21 deletions test/validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

Expand Down
Loading