使用 Repomix 将代码仓库打包为 AI 友好文件:从入门到源码级实践

使用 Repomix 将代码仓库打包为 AI 友好文件:从入门到源码级实践 使用 Repomix 将代码仓库打包为 AI 友好文件从入门到源码级实践【免费下载链接】repomix Repomix is a powerful tool that packs your entire repository into a single, AI-friendly file. Perfect for when you need to feed your codebase to Large Language Models (LLMs) or other AI tools like Claude, ChatGPT, DeepSeek, Perplexity, Gemini, Gemma, Llama, Grok, and more.项目地址: https://gitcode.com/GitHub_Trending/rep/repomix导读本指南围绕 Repomix 的核心能力——把整个代码仓库压缩打包为单一 AI 友好文件展开覆盖从一条命令快速上手、核心特性解析到源码级打包流水线、Token 计数、安全扫描与 Git 集成的完整实践路径。读完本文你将掌握 Repomix 的安装与使用、输出格式选型、--compress压缩、--include/--ignore文件筛选、远程仓库打包、Token 预算控制等实战技能并能理解其底层实现原理为把代码库喂给 ChatGPT、Claude、Gemini、DeepSeek 等 LLM 做好准备。说明本文基于当前仓库 README.md、src/index.ts、src/core/packager.ts、src/cli/cliRun.ts、repomix.config.json 等源码与配置整理。Repomix 是什么Repomix 是一款将整个代码仓库打包为单一、AI 友好文件的工具其定位是帮助你把自己的源代码喂给大语言模型LLM包括 ChatGPT、Claude、Gemini、Grok、DeepSeek、Perplexity、Gemma、Llama 等见 README.md 与 website/client/src/pt-br/guide/index.md。它省去了你逐个打开文件、手动复制粘贴的繁琐过程让 AI 一次性看到完整代码库上下文从而给出更快、更准确的分析结果。Repomix 可以配合 ChatGPT、Claude、Gemini、Grok 等任意订阅服务使用不必担心额外成本。在拿到完整代码库作为上下文后它可以支撑多种应用场景实现规划implementation planning、Bug 调查、第三方库安全审查、文档生成等。其项目自我声明如下README Repomix is a powerful tool that packs your entire repository into a single, AI-friendly file.快速开始一条命令打包整个仓库无需安装直接运行在项目目录中执行npx repomixlatest就这么简单。运行结束后你会在当前目录下看到一个repomix-output.xml文件里面以 AI 友好格式包含了整个仓库的内容。把这个文件交给 AI将生成的repomix-output.xml上传给任意 AI 助手配合一个简单的提示词例如This file contains all the files in the repository combined into one. I want to refactor the code, so please review it first.AI 会分析你的整个代码库并给出全面见解。官方文档用下面两张截图展示了实际使用效果第一张展示用户上传打包文件后请求代码审查AI 返回结构化的重构建议如针对src/utils/errorHandler.ts的自定义错误设计第二张展示用户进一步请求为fileHandler.ts补测试AI 通过依赖注入DI重构可测试性并生成对应的fileHandler.test.ts文件。提示上述截图源文件位于 website/client/src/public/images/docs/repomix-file-usage-1.png 与 website/client/src/public/images/docs/repomix-file-usage-2.png可在仓库中查看。其他安装方式除npx外也可以全局安装后重复使用详见 website/client/src/pt-br/guide/installation.md 与 README.md# npm npm install -g repomix # 或 yarn yarn global add repomix # 或 bun bun add -g repomix # 或 HomebrewmacOS/Linux brew install repomix # 然后在任意项目目录运行 repomix为什么选择 Repomix核心特性AI 优化输出AI-Optimized Output将代码格式化为易于 AI 理解与处理的结构。Token 计数Token Counting为每个文件及整个仓库提供 Token 数用于控制 LLM 上下文窗口。Git 感知Git-Aware自动尊重你的.gitignore、.ignore与.repomixignore文件并支持.git/info/exclude。安全优先Security-Focused集成 Secretlint检测匹配已知凭据格式的文件并将其排除在输出之外。多输出格式Multiple Output Formats可在纯文本、XML、Markdown、JSON 之间选择。代码压缩Code Compression--compress选项利用 Tree-sitter 提取关键代码元素在保留结构的同时降低 Token 数见 README.md。深入源码一次打包是如何完成的repomix命令的底层核心是pack()函数定义于 src/core/packager.ts。从源码结构看一次打包大致经历以下阶段搜索文件searchFiles()依据 include/ignore 规则、.gitignore、默认忽略模式等筛选出待打包文件路径src/core/file/fileSearch.ts。排序路径sortPaths()对文件路径排序默认还会结合 git 变更频率让“最常变更的文件”排在前面src/core/file/filePathSort.ts、src/core/output/outputSort.ts。收集文件collectFiles()读取文件内容同时getGitDiffs()/getGitLogs()并行收集 git diff 与提交日志src/core/file/fileCollect.ts、src/core/git/gitDiffHandle.ts、src/core/git/gitLogHandle.ts。安全检查validateFileSafety()/runSecurityCheck()在 worker 线程中扫描敏感信息src/core/security/validateFileSafety.ts、src/core/security/securityCheck.ts。处理文件processFiles()应用压缩、去注释等处理器src/core/file/fileProcess.ts、src/core/file/fileProcessorRun.ts。生成输出produceOutput()按所选样式生成最终文件src/packager/produceOutput.ts。计算指标calculateMetrics()计算每个文件的字符数与 Token 数src/core/metrics/calculateMetrics.ts。PackResult见 src/core/packager.ts会返回totalFiles、totalCharacters、totalTokens、fileCharCounts、fileTokenCounts、suspiciousFilesResults等结果供 CLI 报告展示。而所有面向库调用者的公开 API 都从 src/index.ts 导出例如pack、collectFiles、searchFiles、runSecurityCheck、TokenCounter、parseFile、loadFileConfig、cli等这意味着你可以在自己的脚本或工具中直接以编程方式复用这些能力。CLI 入口与命令分发CLI 入口在 src/cli/cliRun.ts 的run()基于 Commander 定义全部选项然后runCli()根据参数分发--init走runInitAction--remote走runRemoteAction--watch走runWatchAction--mcp走runMcpAction其余走runDefaultAction。值得一提的是runCli()还能自动识别位置参数中的 GitHub 简写owner/repo当该参数不是本地路径且能通过git ls-remote探测到仓库时会被当作远程仓库处理避免误克隆本地拼错的路径。实战核心用法与命令行参数以下用法均可在当前仓库源码中得到印证主要参数定义于 src/cli/cliRun.ts。打包指定目录或文件# 打包当前目录默认 repomix # 打包指定目录 repomix path/to/directory # 仅打包匹配 glob 模式的文件可同时打包多个位置位置参数也可用 glob repomix src/**/*.ts # 只包含特定文件/目录glob 模式 repomix --include src/**/*.ts,**/*.md # 排除特定文件/目录 repomix --ignore **/*.log,tmp/从文件列表打包stdin 管道--stdin选项允许你把文件路径列表通过管道喂给 Repomix灵活控制打包范围# 用 find 找 .ts 文件 find src -name *.ts -type f | repomix --stdin # 用 git 取已跟踪文件 git ls-files *.ts | repomix --stdin # 用 grep 找含 TODO 的文件 grep -l TODO **/*.ts | repomix --stdin # 用 ripgrep 找含 TODO/FIXME 的文件 rg -l TODO|FIXME --type ts | repomix --stdin # 用 fd 找文件 fd -e ts | repomix --stdin # 用 fzf 交互选择 fzf -m | repomix --stdin # 直接 echo 输入 echo -e src/index.ts\nsrc/utils.ts | repomix --stdin注意--stdin指定的文件会被并入 include 模式因此仍受 include/ignore 规则约束文件路径可以是相对或绝对路径Repomix 会自动处理路径解析与去重。包含 Git 日志与差异# 默认包含最近 50 条提交日志 repomix --include-logs # 指定提交数量 repomix --include-logs --include-logs-count 10 # 同时包含 git diff提供完整 git 上下文 repomix --include-logs --include-diffsGit 日志会包含每次提交的日期、消息与涉及的文件路径为 AI 分析代码演进与发展模式提供上下文。仓库自身的配置 repomix.config.json 中git.sortByChanges、git.includeDiffs、git.includeLogs、git.includeLogsCount均默认开启可作参考。输出格式选择选项说明--style xmlXML 格式默认层次化结构适合 Claude 等结构化解析场景--style markdownMarkdown 格式适合可读性要求高的对话场景--style jsonJSON 格式camelCase 属性适合程序化处理与 API 集成--style plain纯文本格式最大兼容性repomix --style markdown repomix --style json repomix --style plain从源码看各样式实现位于 src/core/output/outputStyles/markdownStyle.ts、plainStyle.ts、xmlStyle.ts输出结构的组装在 src/core/output/outputGenerate.ts。JSON 输出与 jq 配合使用# 列出所有文件路径 cat repomix-output.json | jq -r .files | keys[] # 统计文件总数 cat repomix-output.json | jq .files | keys | length # 提取指定文件内容 cat repomix-output.json | jq -r .files[README.md] # 按扩展名筛选 cat repomix-output.json | jq -r .files | keys[] | select(endswith(.ts)) # 提取目录结构 cat repomix-output.json | jq -r .directoryStructure配置repomix.config.json 与配置文件选项用--init可以生成默认配置文件repomix --init # 在 home 目录生成全局配置 repomix --init --global # 指定自定义配置文件 repomix -c my-config.json配置文件的核心结构与默认值可参考仓库根目录的 repomix.config.json主要字段如下配置段字段默认值说明inputmaxFileSize5000000050MB单文件大小上限outputfilePathrepomix-output.xml输出文件路径outputstylexml输出格式outputcompressfalse是否压缩代码outputheaderText自定义输出头部附加文本outputinstructionFilePathrepomix-instruction.md自定义指令文件路径outputtopFilesLength5摘要中展示的最大文件数outputshowLineNumbersfalse是否显示行号outputincludeEmptyDirectoriestrue是否包含空目录outputtruncateBase64true是否截断长 base64 数据outputtokenCountTree50000Token 树阈值output.gitsortByChangestrue按 git 变更频率排序output.gitincludeDiffstrue包含 git diffoutput.gitincludeLogstrue包含 git 日志output.gitincludeLogsCount50日志提交数ignoreuseGitignoretrue使用.gitignoreignoreuseDefaultPatternstrue使用内置默认忽略模式securityenableSecurityChecktrue启用安全扫描tokenCountencodingo200k_baseToken 计数编码说明ignore.customPatterns为空时仓库通过.repomixignore文件补充自定义忽略规则见 repomix.config.json 中的注释。压缩输出--compress 与 Tree-sitter当仓库太大、超出目标模型的上下文窗口时可以用--compress压缩输出repomix --compress # 远程仓库同样支持 repomix --remote yamadashy/repomix --compress其原理是利用 Tree-sitter采用web-tree-sitterWASM而非原生绑定原因在源码注释中有明确说明跨平台一致、无需编译工具、依赖更少、对 Node.js 版本更鲁棒。各语言解析策略位于 src/core/treeSitter/parseStrategies/如TypeScriptParseStrategy.ts、PythonParseStrategy.ts、GoParseStrategy.ts等。压缩示例官方文档 README.md// 原始代码 import { ShoppingItem } from ./shopping-item; /** * Calculate the total price of shopping items */ const calculateTotal ( items: ShoppingItem[] ) { let total 0; for (const item of items) { total item.price * item.quantity; } return total; }压缩后保留函数签名与注释骨架删除函数体以⋮----占位import { ShoppingItem } from ./shopping-item; ⋮---- /** * Calculate the total price of shopping items */ const calculateTotal ( items: ShoppingItem[] ) { ⋮----注意压缩是尽力而为的。从 src/core/treeSitter/parseFile.ts 的源码注释可以看到parseFile永不抛错任何失败都会回退到未压缩内容——单个病态文件不会导致整个打包崩溃。同时官方文档也提示这是一个实验性功能会基于用户反馈持续改进。按文件粒度控制内容级别output.patterns如果只想对部分文件压缩可用配置文件中的output.patterns按 glob 逐文件覆盖全局output.compress{ output: { compress: false, // 全局默认值兜底 patterns: [ { pattern: docs/**/*, compress: true }, { pattern: website/**/*, directoryStructureOnly: true } ] } }三种内容级别完整内容默认包含文件全部内容。压缩compress: true走与--compress相同的 Tree-sitter 流水线。仅目录结构directoryStructureOnly: true文件只出现在目录结构中内容块被完全省略。语义要点按数组顺序匹配、第一个匹配生效directoryStructureOnly优先于compress未匹配时使用全局行为。这是仅配置文件可用的选项没有对应 CLI 标志。远程仓库打包无需手动 clone即可直接分析任意公开 Git 仓库# 完整 URL repomix --remote https://github.com/yamadashy/repomix # GitHub 简写 repomix --remote yamadashy/repomix # 指定分支 repomix --remote https://github.com/yamadashy/repomix --remote-branch main # 指定提交 repomix --remote https://github.com/yamadashy/repomix --remote-branch 935b695 # 分支 URL 也支持 repomix --remote https://github.com/yamadashy/repomix/tree/main # 提交 URL 也支持 repomix --remote https://github.com/yamadashy/repomix/commit/836abcd7335137228ad77feb28655d85712680f1安全提示出于安全考虑远程仓库中的配置文件repomix.config.*默认不会被加载防止不可信仓库通过配置文件执行代码。你的全局配置与 CLI 参数仍然生效。若确实信任远程仓库的配置可用--remote-trust-config或设置REPOMIX_REMOTE_TRUST_CONFIGtrue交互终端下 Repomix 会先展示该配置并请求你确认相关实现见 src/cli/prompts/remoteConfigTrustPrompt.ts。另外--config与--remote一起使用时配置路径必须是绝对路径。Token 计数与上下文管理Token 计数原理Token 计数由 src/core/metrics/TokenCounter.ts 实现底层基于gpt-tokenizer通过resolveEncodingAsync惰性加载 BPE 词表再用GptEncoding计算 Token 数且把全部内容视为普通文本PLAIN_TEXT_OPTIONS避免特殊 token 干扰。默认编码为o200k_baseGPT-4o可通过--token-count-encoding切换如cl100k_base对应 GPT-3.5/4。repomix --token-count-encoding cl100k_baseToken 树与预算# 查看整棵文件的 Token 分布树 repomix --token-count-tree # 只显示 Token 数 ≥ 阈值的文件/目录 repomix --token-count-tree 1000 # 设置 Token 预算超过 N 时以非零退出码失败CI/Agent 护栏 repomix --token-budget 100000Token 树帮助你定位 Token 大户、用--include/--ignore优化文件选择、针对最大贡献者规划压缩策略。--token-budget在输出超过阈值时令进程以非零退出码失败输出仍会生成只通过退出码发出溢出信号适合在 CI 流水线中守护上下文窗口。安全扫描Secretlint 集成Repomix 集成 Secretlint 等文件。安全检查覆盖三类内容普通文件、git diff工作区与暂存区变更、git 日志提交历史runSecurityCheck()会把它们合并后分批交给 worker 线程处理src/core/security/securityCheck.ts。从实现看安全检查与文件处理并行执行检测出的可疑文件会在最终输出中被过滤掉src/core/packager.ts。# 跳过敏感数据API Key、密码等扫描 repomix --no-security-check官方文档同时提醒即使内置了安全检查把私有或敏感代码分享给任何 AI 服务前仍应人工复核生成的输出见 website/client/src/en/guide/index.md 的 LLM Usage Notes。安全功能详细介绍见 website/client/src/pt-br/guide/security.md。拆分输出与其他实用参数拆分大输出某些 AI 工具对文件大小有限制例如 Google AI Studio 的 1MB 限制可用--split-output自动拆分repomix --split-output 1mb生成repomix-output.1.xml、repomix-output.2.xml等编号文件。大小支持500kb、1mb、2mb、1.5mb等支持小数解析由parseHumanSizeToBytes完成见 src/shared/sizeParse.ts。文件按顶层目录分组以保持上下文单个文件或目录不会被拆分到多个输出文件中。其他高频参数速查选项说明-o, --output file输出路径默认repomix-output.xml-表示 stdout--stdout输出到 stdout静默日志可继续管道给其他命令--copy打包后复制到系统剪贴板--remove-comments打包前去注释--remove-empty-lines去掉空行--header-text text自定义输出头部文本--instruction-file-path path引入自定义指令文件对应output.instructionFilePath--output-show-line-numbers输出中每行加行号--no-file-summary省略文件摘要段--no-directory-structure省略目录树段--no-files仅元数据不包含文件内容用于仓库分析--top-files-len n摘要中展示的最大文件数默认 5-v, --version显示版本号--verbose/--quiet详细日志 / 静默模式组合示例# 自定义输出并指定格式 repomix -o output.xml --style xml # 输出到 stdout 后管道给 simonw/llm repomix --stdout | llm Please explain what this code does. # 只处理指定文件并排除测试 repomix --include src/**/*.ts --ignore **/*.test.ts # 去注释 去空行 压缩 repomix --remove-comments --remove-empty-lines --compress监听模式--watch 自动重打包# 监听文件变化并自动重打包 repomix --watch repomix -w --include src/**/*.ts监听模式会对快速变化做 300ms 防抖每次重建打印时间戳CtrlC停止。需要特别注意的是验证自 src/cli/cliRun.ts 的validateWatchOptions监听模式只支持本地目录不能与--remote、位置参数形式的远程 URL、--stdout、--stdin、--split-output、--skill-generate、--copy组合使用。进阶集成MCP Server、Docker 与更多MCP Server 集成Repomix 支持 Model Context ProtocolMCP让 AI 助手直接调用打包能力repomix --mcp可配合沙箱模式将文件工具限定在指定工作区内防止不可信客户端越权读取repomix --mcp --sandbox repomix --mcp --sandbox path/to/project在 VS Code 中安装 MCP Servercode --add-mcp {name:repomix,command:npx,args:[-y,repomix,--mcp]}或在cline_mcp_settings.json中配置{ mcpServers: { repomix: { command: npx, args: [-y, repomix, --mcp] } } }相关源码见 src/mcp/mcpServer.ts 与 src/mcp/tools/如packCodebaseTool.ts、readRepomixOutputTool.ts完整指南见 website/client/src/pt-br/guide/mcp-server.md。Docker 运行# 打包当前目录 docker run -v .:/app -it --rm ghcr.io/yamadashy/repomix # 打包指定目录 docker run -v .:/app -it --rm ghcr.io/yamadashy/repomix path/to/directory # 处理远程仓库并输出到 output 目录 docker run -v ./output:/app -it --rm ghcr.io/yamadashy/repomix --remote https://github.com/yamadashy/repomix更新 Repomixnpm update -g repomix yarn global upgrade repomix bun update -g repomix使用npx repomix通常更省心因为它总是使用最新版本。典型使用场景与提示词示例拿到打包文件后可以配合以下提示词开始使用详见 README.md 与 website/client/src/pt-br/guide/prompt-examples.md代码审查与重构This file contains my entire codebase. Please review the overall structure and suggest any improvements or refactoring opportunities, focusing on maintainability and scalability.生成项目文档Based on the codebase in this file, please generate a detailed README.md that includes an overview of the project, its main features, setup instructions, and usage examples.生成测试用例Analyze the code in this file and suggest a comprehensive set of unit tests for the main functions and classes. Include edge cases and potential error scenarios.代码质量评估Review the codebase for adherence to coding best practices and industry standards. Identify areas where the code could be improved in terms of readability, maintainability, and efficiency.库整体概览This file contains the entire codebase of library. Please provide a comprehensive overview of the library, including its main purpose, key features, and overall architecture.下一步学习路径安装指南不同安装方式使用指南基础与进阶功能配置指南按需定制安全特性安全检查细节输出格式为你的 AI 模型选择最佳格式MCP 服务器与 AI 助手直接集成远程仓库处理远程仓库打包详解FAQ格式、隐私、Token 用量等常见问题watch 模式文件监听重打包总结Repomix 以“一条命令打包整个仓库”为切入点解决了把代码库喂给 LLM 时的上下文准备问题。通过本文你可以看到它并不是简单的文件拼接工具底层有 Tree-sitter 驱动的代码压缩、gpt-tokenizer 驱动的 Token 统计、Secretlint 驱动的安全扫描、Git 感知的文件筛选与排序以及 MCP、watch、split-output 等面向真实工作流的工程化能力。无论是本地项目还是远程仓库、无论是普通对话还是 CI 自动化Repomix 都提供了一条把完整代码上下文交给 AI 的快速通道。【免费下载链接】repomix Repomix is a powerful tool that packs your entire repository into a single, AI-friendly file. Perfect for when you need to feed your codebase to Large Language Models (LLMs) or other AI tools like Claude, ChatGPT, DeepSeek, Perplexity, Gemini, Gemma, Llama, Grok, and more.项目地址: https://gitcode.com/GitHub_Trending/rep/repomix创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考