or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Gitlog

Gitlog is a Git log parser for Node.JS that provides programmatic access to git commit history with full TypeScript support. It executes git log commands and parses the output into structured JavaScript objects, supporting flexible filtering, field selection, and cross-platform compatibility.

Package Information

  • Package Name: gitlog
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install gitlog

Core Imports

import gitlog, { GitlogOptions, CommitField, FileLineRange } from "gitlog";
import type { ExecFileSyncOptions, ExecFileException } from "node:child_process";

For CommonJS:

const gitlog = require("gitlog");

Basic Usage

import gitlog from "gitlog";

// Simple usage with defaults
const commits = await gitlog({
  repo: "/path/to/git/repository"
});

// Advanced usage with custom fields and filtering
const commits = await gitlog({
  repo: "/path/to/git/repository",
  number: 20,
  fields: ["hash", "subject", "authorName", "authorDate"],
  author: "John Doe",
  since: "1 week ago"
});

console.log(commits[0].subject); // First commit subject
console.log(commits[0].files);   // Changed files (if nameStatus enabled)
console.log(commits[0].status);  // File status codes (A/M/D/etc.)

Architecture

Gitlog is built around several key components:

  • Main Function: Single async function with multiple overloads for different usage patterns
  • Type System: Full TypeScript integration with field-based return type inference
  • Git Execution: Uses Node.js child_process to execute git log commands
  • Parsing Engine: Converts git log output into structured JavaScript objects
  • Field Mapping: Maps git format placeholders to JavaScript property names
  • Status Parsing: Parses git file status information when enabled

Capabilities

Git Log Parsing

Core functionality for parsing git commit history into structured data with flexible field selection and filtering options.

/**
 * Callback-based version with file status information disabled
 * @param userOptions - Configuration options with nameStatus disabled  
 * @param cb - Callback function receiving error and commits
 */
function gitlog<Field extends CommitField = DefaultField>(
  userOptions: GitlogOptions<Field> & { nameStatus: false },
  cb: (err: GitlogError, commits: CommitBase<Field>[]) => void
): void;

/**
 * Callback-based version with file status information
 * @param userOptions - Configuration options
 * @param cb - Callback function receiving error and commits
 */
function gitlog<Field extends CommitField = DefaultField>(
  userOptions: GitlogOptions<Field>,
  cb: (err: GitlogError, commits: CommitBaseWithFiles<Field>[]) => void
): void;

/**
 * Parses git log without file status information
 * @param userOptions - Configuration options with nameStatus disabled
 * @returns Promise resolving to array of commit objects without files/status
 */
function gitlog<Field extends CommitField = DefaultField>(
  userOptions: GitlogOptions<Field> & { nameStatus: false }
): Promise<CommitBase<Field>[]>;

/**
 * Parses git log and returns commit data
 * @param userOptions - Configuration options for git log parsing
 * @returns Promise resolving to array of commit objects
 */
function gitlog<Field extends CommitField = DefaultField>(
  userOptions: GitlogOptions<Field>
): Promise<CommitBaseWithFiles<Field>[]>;

Usage Examples:

import gitlog from "gitlog";

// Promise-based usage
const commits = await gitlog({
  repo: "/path/to/repo",
  number: 10,
  fields: ["hash", "subject", "authorName"]
});

// Callback-based usage
gitlog({
  repo: "/path/to/repo",
  number: 5
}, (error, commits) => {
  if (error) {
    console.error('Error:', error);
    return;
  }
  console.log('Commits:', commits);
});

// Without file status information
const commitsOnly = await gitlog({
  repo: "/path/to/repo",
  nameStatus: false,
  fields: ["subject", "authorName"]
});

Configuration Options

Comprehensive configuration interface for customizing git log behavior and output.

interface GitlogOptions<Fields extends string = DefaultField> {
  /** The location of the repo (required) */
  repo: string;
  
  /** Much more likely to set status codes to 'C' if files are exact copies of each other */
  findCopiesHarder?: boolean;
  
  /** Find commits on all branches instead of just on the current one */
  all?: boolean;
  
  /** Pass the -m option to includes files in a merge commit */
  includeMergeCommitFiles?: boolean;
  
  /** Pass the -follow option to follow files across renames */
  follow?: boolean;
  
  /** The number of commits to return (default: 10) */
  number?: number;
  
  /** An array of fields to return from the log */
  fields?: readonly Fields[];
  
  /** Below fields was returned from the log: files, status (default: true) */
  nameStatus?: boolean;
  
  /** Show only commits in the specified branch or revision range */
  branch?: string;
  
  /** Range of lines for a given file to find the commits for */
  fileLineRange?: FileLineRange;
  
  /** File filter for the git log command */
  file?: string;
  
  /** Limit the commits output to ones with author header lines that match the specified pattern */
  author?: string;
  
  /** Limit the commits output to ones with committer header lines that match the specified pattern */
  committer?: string;
  
  /** Show commits more recent than a specific date */
  since?: string;
  
  /** Show commits more recent than a specific date */
  after?: string;
  
  /** Show commits older than a specific date */
  until?: string;
  
  /** Show commits older than a specific date */
  before?: string;
  
  /** Specify some options to be passed to the .exec() method */
  execOptions?: ExecFileSyncOptions;
}

Usage Examples:

// Filter by author and date range
const authorCommits = await gitlog({
  repo: "/path/to/repo",
  author: "john@example.com",
  since: "2023-01-01",
  until: "2023-12-31",
  number: 50
});

// Follow file renames
const fileHistory = await gitlog({
  repo: "/path/to/repo",
  file: "important-file.js",
  follow: true,
  number: 100
});

// Analyze specific line range
const lineHistory = await gitlog({
  repo: "/path/to/repo",
  fileLineRange: {
    file: "src/main.js",
    startLine: 10,
    endLine: 20
  }
});

// All branches with merge commit files
const allCommits = await gitlog({
  repo: "/path/to/repo",
  all: true,
  includeMergeCommitFiles: true,
  findCopiesHarder: true
});

File Line Range Analysis

Interface for analyzing git history of specific line ranges within files.

interface FileLineRange {
  /** The file to get the commits for */
  file: string;
  
  /** The number of the first line in the desired range */
  startLine: number;
  
  /** Either the absolute line number for the end of the desired range, or the offset from the startLine */
  endLine: number | string;
}

Usage Examples:

// Analyze first 10 lines of a file
const topLines = await gitlog({
  repo: "/path/to/repo",
  fileLineRange: {
    file: "package.json",
    startLine: 1,
    endLine: 10
  }
});

// Analyze with relative offset
const relativeRange = await gitlog({
  repo: "/path/to/repo", 
  fileLineRange: {
    file: "src/index.js",
    startLine: 50,
    endLine: "+20"  // 20 lines from startLine
  }
});

Types

Node.js Types

/**
 * Options for Node.js child_process.execFile()
 */
interface ExecFileSyncOptions {
  /** Current working directory of the child process */
  cwd?: string;
  /** Environment key-value pairs */
  env?: Record<string, string>;
  /** Encoding for stdio */
  encoding?: string;
  /** Timeout in milliseconds */
  timeout?: number;
  /** Maximum buffer size in bytes (default: 200*1024) */
  maxBuffer?: number;
  /** Signal to kill the child process (default: 'SIGTERM') */
  killSignal?: string;
  /** Whether to set session ID */
  setsid?: boolean;
}

/**
 * Exception type from Node.js child_process operations
 */
interface ExecFileException extends Error {
  /** Exit code of the process */
  code?: number;
  /** Signal that terminated the process */
  signal?: string;
  /** Command that was executed */
  cmd?: string;
}

Available Commit Fields

/**
 * Available fields that can be requested from git log
 * Corresponds to git format placeholders
 */
type CommitField = 
  | "hash"                // Full commit hash (%H)
  | "abbrevHash"          // Abbreviated commit hash (%h)
  | "treeHash"            // Tree hash (%T)
  | "abbrevTreeHash"      // Abbreviated tree hash (%t)
  | "parentHashes"        // Parent hashes (%P)
  | "abbrevParentHashes"  // Abbreviated parent hashes (%P) - same as parentHashes
  | "authorName"          // Author name (%an)
  | "authorEmail"         // Author email (%ae)
  | "authorDate"          // Author date (%ai)
  | "authorDateRel"       // Author relative date (%ar)
  | "committerName"       // Committer name (%cn)
  | "committerEmail"      // Committer email (%ce)
  | "committerDate"       // Committer date (%cd)
  | "committerDateRel"    // Committer relative date (%cr)
  | "subject"             // Commit subject (%s)
  | "body"                // Commit body (%b)
  | "rawBody"             // Raw commit body (%B)
  | "tag";                // Tag information (%D)

Default Fields:

/**
 * Default fields returned when no fields are specified
 */
type DefaultField = "abbrevHash" | "hash" | "subject" | "authorName" | "authorDate";

Return Types

/**
 * Base commit object with specified fields
 */
type CommitBase<Field extends string> = Record<Field, string>;

/**
 * Commit object with files and status arrays (when nameStatus is true)
 */
type CommitBaseWithFiles<Field extends string> = CommitBase<Field> & {
  /** Array of changed file names */
  files: string[];
  /** Array of file status codes (A=added, M=modified, D=deleted, R=renamed, C=copied) */
  status: string[];
};

/**
 * Error type for callback functions
 */
type GitlogError = ExecFileException | null;

Usage Examples:

// Type-safe field selection
const commits = await gitlog({
  repo: "/path/to/repo",
  fields: ["hash", "subject", "authorName"] as const
});
// commits[0].hash     ✓ Available
// commits[0].subject  ✓ Available  
// commits[0].body     ✗ TypeScript error - not in fields

// Working with file status
const commitsWithFiles = await gitlog({
  repo: "/path/to/repo",
  nameStatus: true
});
console.log(commitsWithFiles[0].files);   // string[]
console.log(commitsWithFiles[0].status);  // string[] (e.g., ["M", "A", "D"])

// Without file status
const commitsOnly = await gitlog({
  repo: "/path/to/repo", 
  nameStatus: false
});
// commitsOnly[0].files   ✗ Not available
// commitsOnly[0].status  ✗ Not available

Error Handling

Gitlog throws or returns errors in the following cases:

  • Missing repo parameter: "Repo required!"
  • Non-existent repository: "Repo location does not exist"
  • Unknown field: "Unknown field: [field-name]"
  • Git command errors: Git-specific errors (e.g., invalid branch names, command failures)

Usage Examples:

try {
  const commits = await gitlog({
    repo: "/invalid/path"
  });
} catch (error) {
  console.error('Error:', error.message);
  // Output: "Repo location does not exist"
}

// With callback
gitlog({
  repo: "/path/to/repo",
  branch: "non-existent-branch"
}, (error, commits) => {
  if (error) {
    console.error('Git error:', error.message);
    // Output: Git-specific error about unknown revision
    return;
  }
  // Process commits...
});