UNPKG

repomix

Version:

A tool to pack repository contents to single file for AI consumption

84 lines (83 loc) 2.81 kB
import fs from 'node:fs/promises'; import path from 'node:path'; import { logger } from '../../shared/logger.js'; import { getFileChangeCount, isGitInstalled } from '../git/gitRepositoryHandle.js'; const fileChangeCountsCache = new Map(); const gitAvailabilityCache = new Map(); const buildCacheKey = (cwd, maxCommits) => { return `${cwd}:${maxCommits ?? 'default'}`; }; const getFileChangeCounts = async (cwd, maxCommits, deps) => { const cacheKey = buildCacheKey(cwd, maxCommits); const cached = fileChangeCountsCache.get(cacheKey); if (cached) { logger.trace('Using cached git file change counts'); return cached; } const gitAvailable = await checkGitAvailability(cwd, deps); if (!gitAvailable) { return null; } try { const fileChangeCounts = await deps.getFileChangeCount(cwd, maxCommits); fileChangeCountsCache.set(cacheKey, fileChangeCounts); logger.trace('Git File change counts max commits:', maxCommits); logger.trace('Git File change counts:', fileChangeCounts); return fileChangeCounts; } catch { return null; } }; const checkGitAvailability = async (cwd, deps) => { const cached = gitAvailabilityCache.get(cwd); if (cached !== undefined) { return cached; } const gitInstalled = await deps.isGitInstalled(); if (!gitInstalled) { logger.trace('Git is not installed'); gitAvailabilityCache.set(cwd, false); return false; } const gitFolderPath = path.resolve(cwd, '.git'); try { await fs.access(gitFolderPath); gitAvailabilityCache.set(cwd, true); return true; } catch { logger.trace('Git folder not found'); gitAvailabilityCache.set(cwd, false); return false; } }; export const sortOutputFiles = async (files, config, deps = { getFileChangeCount, isGitInstalled, }) => { if (!config.output.git?.sortByChanges) { logger.trace('Git sort is not enabled'); return files; } const fileChangeCounts = await getFileChangeCounts(config.cwd, config.output.git?.sortByChangesMaxCommits, deps); if (!fileChangeCounts) { return files; } return sortFilesByChangeCounts(files, fileChangeCounts); }; export const prefetchSortData = async (config, deps = { getFileChangeCount, isGitInstalled, }) => { if (!config.output.git?.sortByChanges) return; await getFileChangeCounts(config.cwd, config.output.git?.sortByChangesMaxCommits, deps); }; const sortFilesByChangeCounts = (files, fileChangeCounts) => { return [...files].sort((a, b) => { const countA = fileChangeCounts[a.path] || 0; const countB = fileChangeCounts[b.path] || 0; return countA - countB; }); };