UNPKG

git-bolt

Version:

Git utilities for faster development

75 lines (60 loc) 2.51 kB
import chalk from 'chalk'; import fs from 'fs'; import git from 'isomorphic-git'; async function logCommand(options) { try { const depth = options.depth || 10; // Default to showing 10 commits // Get current branch const currentBranch = await git.currentBranch({ fs, dir: '.' }) .catch(() => 'HEAD'); console.log(chalk.blue(`Commit history for branch: ${currentBranch || 'HEAD'}`)); console.log(chalk.gray('─'.repeat(80))); // Get the latest commit let commitOid = await git.resolveRef({ fs, dir: '.', ref: currentBranch || 'HEAD' }); // Track visited commits to avoid duplicates const visitedCommits = new Set(); let count = 0; // Traverse the commit history while (commitOid && count < depth) { // Skip if we've seen this commit (prevents cycles) if (visitedCommits.has(commitOid)) break; visitedCommits.add(commitOid); try { // Read commit const { commit, oid } = await git.readCommit({ fs, dir: '.', oid: commitOid }); // Format date const date = new Date(commit.author.timestamp * 1000); const formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString(); // Short commit hash const shortOid = oid.substring(0, 7); // Print commit info console.log(chalk.yellow(`Commit: ${shortOid}`)); console.log(chalk.green(`Author: ${commit.author.name} <${commit.author.email}>`)); console.log(chalk.green(`Date: ${formattedDate}`)); console.log(''); console.log(` ${commit.message.split('\n').join('\n ')}`); console.log(chalk.gray('─'.repeat(80))); // Move to parent commit if (commit.parent.length > 0) { commitOid = commit.parent[0]; } else { // No more parents commitOid = null; } count++; } catch (error) { console.error(chalk.red(`Error reading commit ${commitOid}: ${error.message}`)); break; } } if (count === 0) { console.log(chalk.yellow('No commits found in this repository.')); } else if (count === depth && commitOid) { console.log(chalk.blue(`Showing ${depth} most recent commits. Use --depth <number> to see more.`)); } } catch (error) { console.error(chalk.red('Error getting commit history:'), error.message); process.exit(1); } } export { logCommand };