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

- Renamed files are recorded under their real old and new paths. When a rename kept part of the path, Git abbreviates it as `dir/{old => new}/file`, and git-spark split that text on ` => `, recording paths such as `new}/file` and `dir/{old`. In this repository 110 of 134 renames were affected, which skewed hotspots, file counts, file types, and file ownership
- Each file change's status (added, modified, deleted, renamed, copied) now comes from Git. It was guessed from line counts, so an edit that only added lines was reported as a new file and one that only removed lines as a deleted file
- Non-ASCII filenames appear as their real names instead of Git's octal-escaped form (for example `"caf\303\251.txt"`)

## [2.0.3] - 2026-11-21

### Fixed
Expand Down
140 changes: 108 additions & 32 deletions src/core/collector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,28 @@ import { CommitData, FileChange, GitSparkOptions, ProgressCallback } from '../ty
import { GitExecutor } from '../utils/git.js';
import { validateGitOptions } from '../utils/input-validation.js';
import { createLogger } from '../utils/logger.js';
import { expandRenamePath, unquoteGitPath } from './git-paths.js';
// import { validateCommitMessage } from '../utils/validation.js';

const logger = createLogger('collector');

/** A file entry from `git log --raw`: Git's change status and the full old/new paths. */
interface RawChange {
status: FileChange['status'];
path: string;
oldPath?: string;
}

/** Git raw status letters. Type changes (T) and anything unrecognized count as modified. */
const RAW_STATUS: Record<string, FileChange['status']> = {
A: 'added',
M: 'modified',
D: 'deleted',
R: 'renamed',
C: 'copied',
T: 'modified',
};

/**
* Git repository data collection engine
*
Expand Down Expand Up @@ -174,10 +192,16 @@ export class DataCollector {
const safeOptions = validation.sanitized!;

// We prefix each commit with a record separator so we can split reliably even for large bodies.
// Format: \x1e<fields...> then numstat lines, then the next commit begins with \x1e
// Format: \x1e<fields...> then raw lines, then numstat lines; the next commit begins with \x1e.
// --raw supplies Git's own change status and full old/new paths (numstat abbreviates renames
// as `dir/{old => new}/file`); numstat supplies line counts in the same file order.
// core.quotePath=false keeps non-ASCII filenames readable instead of octal-escaped.
const args: string[] = [
'-c',
'core.quotePath=false',
'log',
'--no-merges',
'--raw',
'--numstat',
`--pretty=format:%x1e%H%x1f%h%x1f%an%x1f%ae%x1f%ai%x1f%s%x1f%b%x1f%P`,
];
Expand Down Expand Up @@ -231,14 +255,25 @@ export class DataCollector {
}

currentCommit = this.parseCommitHeader(record.slice(0, headerEnd).split('\x1f'));
for (const line of record.slice(headerEnd + 1).split('\n')) {
const rawEntries: RawChange[] = [];
const statEntries: FileChange[] = [];
for (const rawLine of record.slice(headerEnd + 1).split('\n')) {
const line = rawLine.replace(/\r$/, '');
if (!line.trim()) continue;
const fileChange = this.parseFileStats(line.replace(/\r$/, ''));
if (fileChange) {
currentCommit.files = currentCommit.files || [];
currentCommit.files.push(fileChange);
if (line.startsWith(':')) {
const raw = this.parseRawLine(line);
if (raw) rawEntries.push(raw);
continue;
}
const fileChange = this.parseFileStats(line);
if (fileChange) statEntries.push(fileChange);
}
currentCommit.files = this.mergeFileChanges(
rawEntries,
statEntries,
currentCommit.hash || '',
warnings
);
finalizeCurrent();
processed++;
if (processed % 200 === 0 || processed === totalCommits) {
Expand All @@ -248,8 +283,10 @@ export class DataCollector {
return true;
};

child.stdout.on('data', (chunk: Buffer) => {
buffer += chunk.toString();
// Decode as a stream so a multi-byte UTF-8 character split across chunks stays intact
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk: string) => {
buffer += chunk;
// Split on record separator (each commit starts with \x1e)
const records = buffer.split('\x1e');
buffer = records.pop() || '';
Expand Down Expand Up @@ -318,44 +355,83 @@ export class DataCollector {
};
}

/**
* Parse a `--raw` line: `:<srcmode> <dstmode> <srcsha> <dstsha> <status>[score]\t<path>[\t<path>]`.
* Renames and copies carry the old path then the new path.
*/
private parseRawLine(line: string): RawChange | null {
const tab = line.indexOf('\t');
if (tab === -1) return null;
const meta = line.slice(1, tab).split(' ');
const code = meta[4]?.charAt(0);
if (!code) return null;
const paths = line
.slice(tab + 1)
.split('\t')
.map(p => unquoteGitPath(p));

const status = RAW_STATUS[code] ?? 'modified';
if ((status === 'renamed' || status === 'copied') && paths.length >= 2) {
return { status, path: paths[1], oldPath: paths[0] };
}
return { status, path: paths[0] };
}

/**
* Parse a `--numstat` line for its line counts. The path is only used as a fallback when raw
* entries are unavailable; rename forms (`old => new`, `dir/{old => new}/file`) are expanded.
*/
private parseFileStats(line: string): FileChange | null {
const match = line.match(/^(\d+|\-)\s+(\d+|\-)\s+(.+)$/);
const match = line.match(/^(\d+|-)\t(\d+|-)\t(.+)$/);
if (!match) return null;

const [, insertions, deletions, path] = match;

// Handle binary files
// Binary files report '-' for both counts
const ins = insertions === '-' ? 0 : parseInt(insertions, 10);
const dels = deletions === '-' ? 0 : parseInt(deletions, 10);

// Determine file status and handle renames
let status: FileChange['status'] = 'modified';
let filePath = path;
let oldPath: string | undefined;

if (path.includes(' => ')) {
status = 'renamed';
const parts = path.split(' => ');
oldPath = parts[0].trim();
filePath = parts[1].trim();
} else if (ins > 0 && dels === 0) {
status = 'added';
} else if (ins === 0 && dels > 0) {
status = 'deleted';
}

const rename = expandRenamePath(path);
const result: FileChange = {
path: filePath,
path: rename ? rename.path : unquoteGitPath(path),
insertions: ins,
deletions: dels,
status,
status: rename ? 'renamed' : 'modified',
};
if (rename) result.oldPath = rename.oldPath;
return result;
}

if (oldPath) {
result.oldPath = oldPath;
/**
* Combine Git's raw entries (status and paths) with numstat entries (line counts). Git emits
* both for the same files in the same order. If the counts ever disagree, keep the numstat
* entries, whose status is limited to renamed/modified, and record a warning.
*/
private mergeFileChanges(
rawEntries: RawChange[],
statEntries: FileChange[],
hash: string,
warnings: string[]
): FileChange[] {
if (rawEntries.length !== statEntries.length) {
if (statEntries.length > 0) {
warnings.push(
`File status unavailable for ${hash.slice(0, 7)}: ${rawEntries.length} raw vs ${statEntries.length} numstat entries`
);
}
return statEntries;
}

return result;
return statEntries.map((stat, i) => {
const raw = rawEntries[i];
const merged: FileChange = {
path: raw.path,
insertions: stat.insertions,
deletions: stat.deletions,
status: raw.status,
};
if (raw.oldPath) merged.oldPath = raw.oldPath;
return merged;
});
}

private finalizeCommit(commit: Partial<CommitData>): CommitData {
Expand Down
65 changes: 65 additions & 0 deletions src/core/git-paths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Helpers for reading file paths from `git log` output.
*/

const C_ESCAPES: Record<string, number> = {
a: 7,
b: 8,
t: 9,
n: 10,
v: 11,
f: 12,
r: 13,
'"': 34,
'\\': 92,
};

/**
* Decode a path Git printed in C-style quotes (used for names containing quotes, backslashes,
* control characters or, without core.quotePath=false, non-ASCII bytes). Unquoted paths are
* returned unchanged.
*/
export function unquoteGitPath(path: string): string {
if (path.length < 2 || !path.startsWith('"') || !path.endsWith('"')) return path;
const inner = path.slice(1, -1);
const bytes: number[] = [];
for (let i = 0; i < inner.length; i++) {
const ch = inner[i];
if (ch !== '\\' || i + 1 >= inner.length) {
bytes.push(...Buffer.from(ch, 'utf8'));
continue;
}
const next = inner[i + 1];
const octal = /^[0-7]{3}/.exec(inner.slice(i + 1));
if (octal) {
bytes.push(parseInt(octal[0], 8));
i += 3;
} else if (next in C_ESCAPES) {
bytes.push(C_ESCAPES[next]);
i += 1;
} else {
bytes.push(...Buffer.from(ch, 'utf8'));
}
}
return Buffer.from(bytes).toString('utf8');
}

/**
* Expand a numstat rename path into old and new paths. Git prints either `old => new` or, when
* the paths share a prefix or suffix, `prefix{old => new}suffix` where either side may be empty.
* Returns null when the path is not a rename.
*/
export function expandRenamePath(path: string): { path: string; oldPath: string } | null {
const brace = /^(.*)\{(.*) => (.*)\}(.*)$/.exec(path);
if (brace) {
const [, prefix, from, to, suffix] = brace;
const join = (middle: string) => `${prefix}${middle}${suffix}`.replace(/\/\/+/g, '/');
return { oldPath: join(from), path: join(to) };
}
const arrow = path.indexOf(' => ');
if (arrow === -1) return null;
return {
oldPath: unquoteGitPath(path.slice(0, arrow)),
path: unquoteGitPath(path.slice(arrow + 4)),
};
}
120 changes: 120 additions & 0 deletions test/file-change-records.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { DataCollector } from '../src/core/collector.js';
import { expandRenamePath, unquoteGitPath } from '../src/core/git-paths.js';
import { mkdirSync, mkdtempSync, writeFileSync, appendFileSync, rmSync } from 'fs';
import { join, dirname } from 'path';
import { tmpdir } from 'os';
import { execFileSync } from 'child_process';
import type { CommitData } from '../src/types/index.js';

function git(root: string, ...args: string[]) {
execFileSync('git', args, { cwd: root, stdio: 'pipe' });
}

function write(root: string, file: string, content: string) {
const full = join(root, file);
mkdirSync(dirname(full), { recursive: true });
writeFileSync(full, content, 'utf-8');
}

describe('file change records', () => {
let repo: string;
let commits: CommitData[];
const bySubject = (subject: string) => {
const commit = commits.find(c => c.subject === subject);
if (!commit) throw new Error(`missing commit: ${subject}`);
return commit;
};

beforeAll(async () => {
repo = mkdtempSync(join(tmpdir(), 'git-spark-file-changes-'));
git(repo, 'init', '-q');
git(repo, 'config', 'user.name', 'Test User');
git(repo, 'config', 'user.email', 'test@example.com');
git(repo, 'config', 'diff.renames', 'true');

write(repo, 'docs/guide/intro.md', '# Intro\n\nline one\nline two\nline three\n');
write(repo, 'notes.txt', 'first note\n');
write(repo, 'old/keep.txt', 'to be removed\n');
write(repo, 'café.txt', 'non-ascii name\n');
git(repo, 'add', '-A');
git(repo, 'commit', '-q', '-m', 'add files');

appendFileSync(join(repo, 'notes.txt'), 'second note\nthird note\n');
git(repo, 'commit', '-q', '-am', 'append notes');

mkdirSync(join(repo, 'docs/manual'), { recursive: true });
git(repo, 'mv', 'docs/guide/intro.md', 'docs/manual/intro.md');
git(repo, 'commit', '-q', '-m', 'move intro');

git(repo, 'rm', '-q', 'old/keep.txt');
git(repo, 'commit', '-q', '-m', 'remove keep');

commits = await new DataCollector(repo).collectCommits({ repoPath: repo });
});

afterAll(() => {
rmSync(repo, { recursive: true, force: true });
});

it('records added files with their real names, including non-ASCII ones', () => {
const files = bySubject('add files').files;
expect(files.map(f => [f.path, f.status]).sort()).toEqual([
['café.txt', 'added'],
['docs/guide/intro.md', 'added'],
['notes.txt', 'added'],
['old/keep.txt', 'added'],
]);
});

it('reports an append-only edit as modified, not added', () => {
const [file] = bySubject('append notes').files;
expect(file).toEqual({ path: 'notes.txt', insertions: 2, deletions: 0, status: 'modified' });
});

it('expands a brace-form rename into the full old and new paths', () => {
const [file] = bySubject('move intro').files;
expect(file.status).toBe('renamed');
expect(file.path).toBe('docs/manual/intro.md');
expect(file.oldPath).toBe('docs/guide/intro.md');
});

it('reports a removed file as deleted', () => {
const [file] = bySubject('remove keep').files;
expect(file).toEqual({ path: 'old/keep.txt', insertions: 0, deletions: 1, status: 'deleted' });
});

it('records no path with rename braces or arrows', () => {
const paths = commits.flatMap(c => c.files.flatMap(f => [f.path, f.oldPath ?? '']));
expect(paths.filter(p => /[{}]| => /.test(p))).toEqual([]);
});
});

describe('expandRenamePath', () => {
it.each([
['src/{a => b}/file.ts', 'src/a/file.ts', 'src/b/file.ts'],
['{old => new}/x.md', 'old/x.md', 'new/x.md'],
['docs/{ => sub}/x.md', 'docs/x.md', 'docs/sub/x.md'],
['docs/{sub => }/x.md', 'docs/sub/x.md', 'docs/x.md'],
['dir/{a.txt => b.txt}', 'dir/a.txt', 'dir/b.txt'],
['a.txt => b.txt', 'a.txt', 'b.txt'],
])('%s', (input, oldPath, path) => {
expect(expandRenamePath(input)).toEqual({ oldPath, path });
});

it('returns null for a path that is not a rename', () => {
expect(expandRenamePath('src/index.ts')).toBeNull();
});
});

describe('unquoteGitPath', () => {
it('leaves unquoted paths unchanged', () => {
expect(unquoteGitPath('src/plain.ts')).toBe('src/plain.ts');
});

it('decodes C-style escapes and octal UTF-8 bytes', () => {
expect(unquoteGitPath('"caf\\303\\251.txt"')).toBe('café.txt');
expect(unquoteGitPath('"say \\"hi\\".txt"')).toBe('say "hi".txt');
expect(unquoteGitPath('"tab\\there"')).toBe('tab\there');
expect(unquoteGitPath('"back\\\\slash"')).toBe('back\\slash');
});
});
Loading