← Complete Projects

阅读中文版本

Build a Git Commit Statistics CLI

A CLI that parses git log output, reports commit counts per author and per day, tracks insertions and deletions, and highlights the busiest files, all from a local repository.

beginner~4 hnodejsgitclianalytics

Project goal

Build a CLI that runs git log with a machine-readable format, parses commits into records, and reports per-author, per-day, and per-file statistics with totals.

Final features

  • Run git log with a parseable separator format and parse each commit record.
  • Count commits per author with the newest activity first.
  • Aggregate commits per day and per weekday to show cadence.
  • Sum insertions and deletions per author.
  • List the most frequently changed files with a count.

Architecture

A git runner shells out to git log and captures stdout; a parser turns that text into commit records; an aggregator computes several views from one record set; and a formatter prints each view as a table. The parser and aggregator are pure functions over text and records so they test without a repository.

Prerequisites

  • Node.js 20 LTS or later
  • A local git repository to analyse
  • Familiarity with child processes and text parsing

Dependencies

  • node >=20 — child_process to run git and the CLI entry point
  • vitest ^2.1.0 — Parser and aggregator tests over fixture text

Directory structure

git-stats/
├── src/
│   ├── run.js
│   ├── parse.js
│   ├── aggregate.js
│   ├── format.js
│   └── cli.js
├── test/
│   ├── parse.test.js
│   └── aggregate.test.js
└── package.json

Phases

1. Git invocation

Run git log with a fixed format and numstat, returning stdout as a string and surfacing git errors.

Files: src/run.js

import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const run = promisify(execFile);

export const LOG_ARGS = [
  'log',
  '--pretty=format:__COMMIT__%H%x09%an%x09%aI%x09%s',
  '--numstat',
  '--no-merges',
];

export async function gitLog(cwd = process.cwd(), extra = []) {
  try {
    const { stdout } = await run('git', [...LOG_ARGS, ...extra], { cwd, maxBuffer: 64 * 1024 * 1024 });
    return stdout;
  } catch (err) {
    throw new Error('git log failed: ' + err.message);
  }
}

Expected behavior: Running in a repository returns a non-empty log string, and running outside one throws a wrapped error rather than crashing with a raw stack trace.

2. Log parser

Split the log into commits and parse the header fields and numstat file lines into records.

Files: src/parse.js

export function parseLog(text) {
  return text
    .split('__COMMIT__')
    .filter((chunk) => chunk.trim())
    .map((chunk) => {
      const [header, ...fileLines] = chunk.split('\n');
      const [hash, author, date, subject] = header.split('\t');
      const files = fileLines
        .map((l) => l.split('\t'))
        .filter((parts) => parts.length === 3)
        .map(([insertions, deletions, path]) => ({
          path,
          insertions: insertions === '-' ? 0 : Number(insertions),
          deletions: deletions === '-' ? 0 : Number(deletions),
          binary: insertions === '-',
        }));
      return { hash, author, date, subject, files };
    });
}

Expected behavior: A fixture with three commits parses into three records with correct fields, and a binary file line yields zero insertions and a binary flag.

3. Aggregations

Compute per-author, per-day, and per-file statistics as pure functions over the records.

Files: src/aggregate.js

export function byAuthor(commits) {
  const map = new Map();
  for (const c of commits) {
    const entry = map.get(c.author) ?? { author: c.author, commits: 0, insertions: 0, deletions: 0 };
    entry.commits++;
    for (const f of c.files) { entry.insertions += f.insertions; entry.deletions += f.deletions; }
    map.set(c.author, entry);
  }
  return [...map.values()].sort((a, b) => b.commits - a.commits || a.author.localeCompare(b.author));
}

export function byFile(commits) {
  const map = new Map();
  for (const c of commits) for (const f of c.files) map.set(f.path, (map.get(f.path) ?? 0) + 1);
  return [...map.entries()].map(([path, changes]) => ({ path, changes }))
    .sort((a, b) => b.changes - a.changes || a.path.localeCompare(b.path));
}

Expected behavior: Author totals sum insertions and deletions correctly, and the file list ranks the most frequently changed file first.

4. Date aggregation

Group commits by ISO day and by weekday to show development cadence.

Files: src/dates.js

const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

export function byDay(commits) {
  const map = new Map();
  for (const c of commits) {
    const day = c.date.slice(0, 10);
    map.set(day, (map.get(day) ?? 0) + 1);
  }
  return [...map.entries()].map(([day, commits]) => ({ day, commits })).sort((a, b) => a.day.localeCompare(b.day));
}

export function byWeekday(commits) {
  const counts = Object.fromEntries(WEEKDAYS.map((d) => [d, 0]));
  for (const c of commits) counts[WEEKDAYS[new Date(c.date).getUTCDay()]]++;
  return counts;
}

Expected behavior: Day counts group by the ISO date prefix and weekday counts sum to the total commit count.

5. Table formatting

Render each aggregation as a fixed-width table with aligned columns and a header.

Files: src/format.js

export function table(rows, columns) {
  const widths = columns.map((col) =>
    Math.max(col.label.length, ...rows.map((r) => String(r[col.key]).length)));
  const header = columns.map((col, i) => col.label.padEnd(widths[i])).join('  ');
  const lines = rows.map((r) => columns.map((col, i) => String(r[col.key]).padEnd(widths[i])).join('  '));
  return [header, '-'.repeat(header.length), ...lines].join('\n');
}

Expected behavior: A table renders aligned columns sized to the widest cell, and an empty row set still prints the header and separator.

6. CLI and tests

Wire git log, parsing, aggregation, and formatting, and cover the parser and aggregators with tests.

Files: src/cli.js

import { gitLog } from './run.js';
import { parseLog } from './parse.js';
import { byAuthor, byFile } from './aggregate.js';
import { table } from './format.js';

const [view = 'authors', ...extra] = process.argv.slice(2);
const commits = parseLog(await gitLog(process.cwd(), extra));
if (view === 'authors') {
  console.log(table(byAuthor(commits), [
    { key: 'author', label: 'Author' }, { key: 'commits', label: 'Commits' },
    { key: 'insertions', label: '+' }, { key: 'deletions', label: '-' },
  ]));
} else if (view === 'files') {
  console.log(table(byFile(commits), [{ key: 'path', label: 'File' }, { key: 'changes', label: 'Changes' }]));
} else {
  console.error('usage: git-stats [authors|files|days] [git args]');
  process.exit(1);
}

Expected behavior: Running in a repository prints an aligned author table, and an unknown view exits with code 1 and a usage line.

Testing

Run npx vitest. Parser tests feed a fixture log excerpt and assert commit fields, numstat parsing, and binary files where insertions and deletions are dashes. Aggregator tests assert per-author totals, per-day counts, and file change counts including a file touched in two commits.

Troubleshooting

Author names differ for the same person

Normalise by email in addition to name, or group on the email field; git records both, and many contributors have several display names.

Binary files report NaN totals

Treat a dash in numstat as zero and mark the file as binary; coercing a dash with Number produces NaN, which poisons any sum it enters.

The log for a large repository is truncated

Raise the child process maxBuffer or stream git output and parse incrementally; the default buffer is far smaller than a large log.

Deployment

Run in CI or locally to produce a periodic activity report; the output is plain text so it can be committed or posted to a chat. A JSON formatter makes the same data available to a dashboard.

Known limitations

  • Only numstat totals are used, so renames and moves count as a delete plus an add.
  • Merge commits are excluded by default, which undercounts integration-heavy workflows.

Project overview

Git already stores everything you want to measure; the work is asking for it in a parseable shape and turning that shape into answers. This project does exactly that without a heavy dependency.

The tool runs git log with a custom separator format, parses each commit including the numstat lines, and reports author, date, and file statistics from a single record set.

The log format is chosen so that records are unambiguous to split, which is the foundation the whole parser rests on:

export const LOG_FORMAT = [
  '--pretty=format:__COMMIT__%H%x09%an%x09%aI%x09%s',
  '--numstat',
].join(' ');

export function parseLog(text) {
  return text
    .split('__COMMIT__')
    .filter((chunk) => chunk.trim())
    .map((chunk) => {
      const [header, ...fileLines] = chunk.split('\n');
      const [hash, author, date, subject] = header.split('\t');
      const files = fileLines
        .map((l) => l.split('\t'))
        .filter((parts) => parts.length === 3 && parts[0] !== '-')
        .map(([insertions, deletions, path]) => ({
          path,
          insertions: Number(insertions),
          deletions: Number(deletions),
        }));
      return { hash, author, date, subject, files };
    });
}

Once commits are records with a files array, every report is a different grouping of the same data rather than a new git invocation.

Setup

The tool shells out to the git binary rather than parsing the repository format directly, so it works against any repository and requires no git library.

Dependency Version Why it is here
node >=20 child_process to run git and the CLI entry point
vitest ^2.1.0 Parser and aggregator tests over fixture text

Create the project and install:

mkdir git-stats && cd git-stats
npm init -y
npm install -D vitest@^2.1.0

Configure the CLI and tests in package.json:

{
  "name": "git-stats",
  "type": "module",
  "scripts": {
    "stats": "node src/cli.js",
    "test": "vitest run"
  }
}

Commit a fixture log excerpt as a test resource so the parser is verified without depending on the host repository.

Phase 1: Git invocation

Run git log with a fixed format and numstat, returning stdout as a string and surfacing git errors. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const run = promisify(execFile);

export const LOG_ARGS = [
  'log',
  '--pretty=format:__COMMIT__%H%x09%an%x09%aI%x09%s',
  '--numstat',
  '--no-merges',
];

export async function gitLog(cwd = process.cwd(), extra = []) {
  try {
    const { stdout } = await run('git', [...LOG_ARGS, ...extra], { cwd, maxBuffer: 64 * 1024 * 1024 });
    return stdout;
  } catch (err) {
    throw new Error('git log failed: ' + err.message);
  }
}

Acceptance for this phase: Running in a repository returns a non-empty log string, and running outside one throws a wrapped error rather than crashing with a raw stack trace.

Phase 2: Log parser

Split the log into commits and parse the header fields and numstat file lines into records. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

export function parseLog(text) {
  return text
    .split('__COMMIT__')
    .filter((chunk) => chunk.trim())
    .map((chunk) => {
      const [header, ...fileLines] = chunk.split('\n');
      const [hash, author, date, subject] = header.split('\t');
      const files = fileLines
        .map((l) => l.split('\t'))
        .filter((parts) => parts.length === 3)
        .map(([insertions, deletions, path]) => ({
          path,
          insertions: insertions === '-' ? 0 : Number(insertions),
          deletions: deletions === '-' ? 0 : Number(deletions),
          binary: insertions === '-',
        }));
      return { hash, author, date, subject, files };
    });
}

Acceptance for this phase: A fixture with three commits parses into three records with correct fields, and a binary file line yields zero insertions and a binary flag.

Phase 3: Aggregations

Compute per-author, per-day, and per-file statistics as pure functions over the records. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

export function byAuthor(commits) {
  const map = new Map();
  for (const c of commits) {
    const entry = map.get(c.author) ?? { author: c.author, commits: 0, insertions: 0, deletions: 0 };
    entry.commits++;
    for (const f of c.files) { entry.insertions += f.insertions; entry.deletions += f.deletions; }
    map.set(c.author, entry);
  }
  return [...map.values()].sort((a, b) => b.commits - a.commits || a.author.localeCompare(b.author));
}

export function byFile(commits) {
  const map = new Map();
  for (const c of commits) for (const f of c.files) map.set(f.path, (map.get(f.path) ?? 0) + 1);
  return [...map.entries()].map(([path, changes]) => ({ path, changes }))
    .sort((a, b) => b.changes - a.changes || a.path.localeCompare(b.path));
}

Acceptance for this phase: Author totals sum insertions and deletions correctly, and the file list ranks the most frequently changed file first.

Phase 4: Date aggregation

Group commits by ISO day and by weekday to show development cadence. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

export function byDay(commits) {
  const map = new Map();
  for (const c of commits) {
    const day = c.date.slice(0, 10);
    map.set(day, (map.get(day) ?? 0) + 1);
  }
  return [...map.entries()].map(([day, commits]) => ({ day, commits })).sort((a, b) => a.day.localeCompare(b.day));
}

export function byWeekday(commits) {
  const counts = Object.fromEntries(WEEKDAYS.map((d) => [d, 0]));
  for (const c of commits) counts[WEEKDAYS[new Date(c.date).getUTCDay()]]++;
  return counts;
}

Acceptance for this phase: Day counts group by the ISO date prefix and weekday counts sum to the total commit count.

Phase 5: Table formatting

Render each aggregation as a fixed-width table with aligned columns and a header. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

export function table(rows, columns) {
  const widths = columns.map((col) =>
    Math.max(col.label.length, ...rows.map((r) => String(r[col.key]).length)));
  const header = columns.map((col, i) => col.label.padEnd(widths[i])).join('  ');
  const lines = rows.map((r) => columns.map((col, i) => String(r[col.key]).padEnd(widths[i])).join('  '));
  return [header, '-'.repeat(header.length), ...lines].join('\n');
}

Acceptance for this phase: A table renders aligned columns sized to the widest cell, and an empty row set still prints the header and separator.

Phase 6: CLI and tests

Wire git log, parsing, aggregation, and formatting, and cover the parser and aggregators with tests. Each phase produces something demonstrable, so the tutorial never asks the reader to hold an unfinished design in their head.

import { gitLog } from './run.js';
import { parseLog } from './parse.js';
import { byAuthor, byFile } from './aggregate.js';
import { table } from './format.js';

const [view = 'authors', ...extra] = process.argv.slice(2);
const commits = parseLog(await gitLog(process.cwd(), extra));
if (view === 'authors') {
  console.log(table(byAuthor(commits), [
    { key: 'author', label: 'Author' }, { key: 'commits', label: 'Commits' },
    { key: 'insertions', label: '+' }, { key: 'deletions', label: '-' },
  ]));
} else if (view === 'files') {
  console.log(table(byFile(commits), [{ key: 'path', label: 'File' }, { key: 'changes', label: 'Changes' }]));
} else {
  console.error('usage: git-stats [authors|files|days] [git args]');
  process.exit(1);
}

Acceptance for this phase: Running in a repository prints an aligned author table, and an unknown view exits with code 1 and a usage line.

Testing strategy

Run npx vitest. Parser tests feed a fixture log excerpt and assert commit fields, numstat parsing, and binary files where insertions and deletions are dashes. Aggregator tests assert per-author totals, per-day counts, and file change counts including a file touched in two commits.

The binary-file test matters because numstat prints dashes for those lines, and a parser that blindly coerces them to numbers would report NaN totals.

Extending the project

A date-range option is a filter before aggregation; a per-path filter is one predicate; and exporting to CSV or JSON is a new formatter over the same records. None of these touch the git runner or the parser.