使用 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 repomix@latest就这么简单。运行结束后,你会在当前目录下看到一个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 # 或 Homebrew(macOS/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 xml | XML 格式(默认),层次化结构,适合 Claude 等结构化解析场景 |
--style markdown | Markdown 格式,适合可读性要求高的对话场景 |
--style json | JSON 格式(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,主要字段如下:
| 配置段 | 字段 | 默认值 | 说明 |
|---|---|---|---|
input | maxFileSize | 50000000(50MB) | 单文件大小上限 |
output | filePath | repomix-output.xml | 输出文件路径 |
output | style | xml | 输出格式 |
output | compress | false | 是否压缩代码 |
output | headerText | 自定义 | 输出头部附加文本 |
output | instructionFilePath | repomix-instruction.md | 自定义指令文件路径 |
output | topFilesLength | 5 | 摘要中展示的最大文件数 |
output | showLineNumbers | false | 是否显示行号 |
output | includeEmptyDirectories | true | 是否包含空目录 |
output | truncateBase64 | true | 是否截断长 base64 数据 |
output | tokenCountTree | 50000 | Token 树阈值 |
output.git | sortByChanges | true | 按 git 变更频率排序 |
output.git | includeDiffs | true | 包含 git diff |
output.git | includeLogs | true | 包含 git 日志 |
output.git | includeLogsCount | 50 | 日志提交数 |
ignore | useGitignore | true | 使用.gitignore |
ignore | useDefaultPatterns | true | 使用内置默认忽略模式 |
security | enableSecurityCheck | true | 启用安全扫描 |
tokenCount | encoding | o200k_base | Token 计数编码 |
说明:
ignore.customPatterns为空时,仓库通过.repomixignore文件补充自定义忽略规则(见 repomix.config.json 中的注释)。
压缩输出:--compress 与 Tree-sitter
当仓库太大、超出目标模型的上下文窗口时,可以用--compress压缩输出:
repomix --compress # 远程仓库同样支持 repomix --remote yamadashy/repomix --compress其原理是利用 Tree-sitter,采用web-tree-sitter(WASM)而非原生绑定,原因在源码注释中有明确说明:跨平台一致、无需编译工具、依赖更少、对 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_CONFIG=true,交互终端下 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_base(GPT-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 防抖,每次重建打印时间戳,Ctrl+C停止。需要特别注意的是(验证自 src/cli/cliRun.ts 的validateWatchOptions):监听模式只支持本地目录,不能与--remote、位置参数形式的远程 URL、--stdout、--stdin、--split-output、--skill-generate、--copy组合使用。
进阶集成:MCP Server、Docker 与更多
MCP Server 集成
Repomix 支持 Model Context Protocol(MCP),让 AI 助手直接调用打包能力:
repomix --mcp可配合沙箱模式将文件工具限定在指定工作区内,防止不可信客户端越权读取:
repomix --mcp --sandbox repomix --mcp --sandbox path/to/project在 VS Code 中安装 MCP Server:
code --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更新 Repomix
npm 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),仅供参考