Skip to content

Latest commit

 

History

History
1097 lines (824 loc) · 32.6 KB

File metadata and controls

1097 lines (824 loc) · 32.6 KB

📦 Repomix (Python 版本)

English | 简体中文

🎯 1. 简介

Repomix 是一个强大的工具,可以将你的整个仓库打包成一个单一的、对 AI 友好的文件。当你需要将你的代码库输入到大型语言模型 (LLM) 或其他 AI 工具(如 Claude、ChatGPT 和 Gemini)时,它非常完美。

最初的 Repomix 是用 JavaScript 编写的,这是移植的 Python 版本。

⭐ 2. 功能特性

  • AI 优化: 以一种易于人工智能理解和处理的方式格式化你的代码库。
  • Token 计数: 使用 tiktoken 为每个文件和整个仓库提供 token 计数,支持可配置的编码方式(--token-count-encoding)。
  • 简单易用: 只需一个命令即可打包整个仓库。
  • 多目录支持: 在一个命令中处理多个目录(repomix src lib tests)。
  • 可定制: 轻松配置要包含或排除的内容。
  • Git 感知: 自动遵守你的 .gitignore.repomixignore.ignore 文件。
  • 安全至上: 内置安全检查,以检测并防止包含敏感信息(基于 detect-secrets)。
  • 代码压缩: 高级代码压缩功能,提供多种模式以减少输出大小同时保留关键信息。
  • 语义 CLI 建议: 未知的 CLI 选项会建议最接近的有效替代项(例如 --exclude → "Did you mean: --ignore?")。
  • 静默模式: 使用 --quiet 抑制除错误外的所有控制台输出。
  • 性能: 利用多进程或多线程在多核系统上实现更快的分析。
  • ⚙️ 编码感知: 自动检测并处理除 UTF-8 之外的多种文件编码(使用 chardet),增强健壮性。

🚀 3. 快速开始

使用 uvx 快速运行(推荐)

使用 Repomix 最简单的方式是通过 uvx - 无需安装:

uvx repomix

就这么简单!这将把你当前目录打包成一个 AI 友好的文件。

更多示例:

# 使用 JSON 输出打包
uvx repomix --style json

# 打包远程仓库
uvx repomix --remote https://github.com/username/repo

# 使用特定模式打包
uvx repomix --include "src/**/*.py" --ignore "tests/**"

# 使用特定版本
uvx repomix@0.5.0

你也可以使用 pipxpipx run repomix

使用 pip 安装

如果需要频繁使用,可以全局安装 Repomix:

pip install repomix

然后在任何项目目录下运行:

repomix

Docker 使用

你也可以在不本地安装的情况下使用 Docker 运行 Repomix:

# 构建 Docker 镜像
docker build -t repomix .

# 在当前目录运行 repomix
docker run --rm -v "$(pwd)":/app repomix

# 使用特定选项运行 repomix
docker run --rm -v "$(pwd)":/app repomix --style markdown --output custom-output.md

# 在不同目录运行 repomix
docker run --rm -v "/path/to/your/project":/app repomix

Docker 优势:

  • 隔离环境:无需在宿主机安装 Python 依赖即可运行 repomix
  • 一致性结果:确保跨不同机器的环境一致性
  • 易于分发:与团队共享确切的 repomix 版本和配置
  • 免装即用:无需 pip install 即可立即使用 repomix

就这样!Repomix 将会在你当前目录下生成一个 repomix-output.md 文件(默认),其中包含你整个仓库的 AI 友好格式。

📖 4. 用法

4.1 命令行用法

要打包你的整个仓库:

repomix

要打包特定目录:

repomix path/to/directory

要同时打包多个目录:

repomix src lib tests

要打包一个远程仓库:

repomix --remote https://github.com/username/repo

要打包远程仓库的特定分支:

repomix --remote https://github.com/username/repo --remote-branch feature-branch

要初始化一个新的配置文件:

repomix --init
# 使用 --global 创建一个全局配置文件(详见下文配置选项)
repomix --init --global

4.2 配置选项

在你的项目根目录创建一个 repomix.config.json 文件来进行自定义配置。Repomix 也会自动加载全局配置文件(如果存在,例如 Linux 上的 ~/.config/repomix/repomix.config.json),其优先级低于本地配置和命令行选项。

{
  "input": {
    "max_file_size": 52428800
  },
  "output": {
    "file_path": "repomix-output.md",
    "style": "markdown",
    "header_text": "",
    "instruction_file_path": "",
    "remove_comments": false,
    "remove_empty_lines": false,
    "top_files_length": 5,
    "show_line_numbers": false,
    "copy_to_clipboard": false,
    "include_empty_directories": false,
    "calculate_tokens": false,
    "show_file_stats": false,
    "show_directory_structure": true,
    "include_full_directory_structure": false,
    "split_output": null,
    "token_count_tree": false,
    "git": {
      "sort_by_changes": true,
      "sort_by_changes_max_commits": 100,
      "include_diffs": false,
      "include_logs": false,
      "include_logs_count": 50
    }
  },
  "security": {
    "enable_security_check": true,
    "exclude_suspicious_files": true
  },
  "ignore": {
    "custom_patterns": [],
    "use_gitignore": true,
    "use_default_ignore": true,
    "use_dot_ignore": true
  },
  "compression": {
    "enabled": false,
    "keep_signatures": true,
    "keep_docstrings": true,
    "keep_interfaces": true
  },
  "remote": {
    "url": "",
    "branch": ""
  },
  "include": [],
  "token_count": {
    "encoding": "o200k_base"
  }
}

Note

关于 remove_comments 的注意:此功能能够感知语言,可以正确处理多种语言的注释语法,而不是使用简单的通用模式。支持的语言: Python, JavaScript, TypeScript, JSX, TSX, Vue, Svelte, Java, C, C++, C#, Go, Rust, Ruby, PHP, Swift, Kotlin, HTML, CSS, XML, YAML

远程仓库配置

remote 部分允许你配置远程仓库处理:

  • url: 要处理的远程 Git 仓库的 URL
  • branch: 要处理的特定分支、标签或提交哈希(可选,默认为仓库的默认分支)

当在配置中指定远程 URL 时,Repomix 将处理远程仓库而不是本地目录。这可以通过 CLI 参数覆盖。

你可以使用多种 URL 格式配合 --remote

# GitHub 简写
repomix --remote user/repo

# 完整 GitHub URL
repomix --remote https://github.com/user/repo

# 指定分支
repomix --remote https://github.com/user/repo --remote-branch feature-branch

# 指定标签
repomix --remote https://github.com/user/repo --remote-branch v1.0.0

# 指定提交
repomix --remote https://github.com/user/repo --remote-branch abc123

命令行选项

  • repomix [directories...]: 目标目录(默认为当前目录)。支持多个目录。
  • -v, --version: 显示版本。
  • -o, --output <file>: 指定输出文件名。
  • --style <style>: 指定输出样式 (plain, xml, markdown, json)。
  • --remote <url>: 处理远程 Git 仓库。
  • --remote-branch <name>: 指定远程仓库的分支、标签或提交。
  • --init: 在当前目录初始化配置文件 (repomix.config.json)。
  • --global: 与 --init 配合使用,用于创建/管理全局配置文件(位于特定于平台的用户配置目录,例如 Linux 上的 ~/.config/repomix)。如果全局配置存在,它会被自动加载。
  • --no-security-check: 禁用安全检查。
  • --include <patterns>: 逗号分隔的包含模式列表 (glob 格式)。
  • -i, --ignore <patterns>: 额外的逗号分隔的忽略模式。
  • -c, --config <path>: 自定义配置文件的路径。
  • --copy: 将生成的输出复制到系统剪贴板。
  • --top-files-len <number>: 在摘要中显示的最大文件数量(按大小)。
  • --output-show-line-numbers: 在输出代码块中添加行号。
  • --stdin: 从标准输入读取文件路径(每行一个),而不是自动发现文件。
  • --verbose: 启用详细日志记录,用于调试。
  • --quiet: 抑制除错误外的所有控制台输出。不能与 --verbose 同时使用。
  • --parsable-style: 通过转义和格式化,确保输出可以作为其类型的文档被解析。
  • --stdout: 输出到标准输出而不是写入文件。
  • --remove-comments: 从源代码中移除注释。
  • --remove-empty-lines: 从源代码中移除空行。
  • --truncate-base64: 启用 base64 数据字符串的截断。
  • --include-empty-directories: 在输出中包含空目录。
  • --include-diffs: 在输出中包含 git diff。
  • --include-logs: 在输出中包含 git 日志历史。
  • --include-logs-count <count>: 与 --include-logs 配合使用,指定包含的最近提交数量(默认: 50)。
  • --sort-by-changes: 按 git 变更频率排序文件(最常变更的在前)。
  • --no-file-summary: 从输出中省略文件摘要部分。
  • --no-directory-structure: 从输出中省略目录树可视化。
  • --no-files: 仅生成元数据,不包含文件内容。
  • --no-gitignore: 不使用 .gitignore 规则过滤文件。
  • --no-dot-ignore: 不使用 .ignore 规则过滤文件。
  • --no-default-patterns: 不应用内置忽略模式。
  • --no-git-sort-by-changes: 不按 git 变更频率排序文件。
  • --include-full-directory-structure: 使用 --include 模式时仍显示完整的仓库目录树。
  • --token-count-encoding <encoding>: 用于计数的分词器编码(例如 o200k_base 用于 GPT-4o,cl100k_base 用于 GPT-3.5/4)。
  • --token-count-tree [threshold]: 显示带有 token 计数的文件树;可选阈值仅显示 ≥N tokens 的文件。
  • --split-output <size>: 将输出分割为多个编号文件(例如 500kb2mb)。
  • --header-text <text>: 在输出开头包含的自定义文本。
  • --instruction-file-path <path>: 包含自定义指令的文件路径,将包含在输出中。
  • --compress: 启用基于 tree-sitter 的代码压缩。
  • --skill-generate [name]: 生成 Claude Agent Skills 格式输出到 .claude/skills/<name>/ 目录。
  • --skill-output <path>: 直接指定 skill 输出目录路径。
  • -f, --force: 跳过所有确认提示(当前用于: skill 目录覆盖)。

4.3 安全检查

Repomix 包含内置的安全检查,使用 detect-secrets 库来检测潜在的敏感信息(API 密钥、凭证等)。默认情况下 (exclude_suspicious_files: true),检测到的文件会从输出中排除。

可通过配置或命令行禁用检查:

repomix --no-security-check

4.4 自定义指令

你可以在输出文件中添加自定义指令,引导 AI 工具如何解读和使用打包的代码库。

创建一个 markdown 文件(如 repomix-instruction.md),写入你的指令:

## 项目背景
这是一个使用 FastAPI 的 Python Web 应用。
建议代码修改时请遵循 PEP 8 规范。

然后通过 CLI 或配置指定路径:

# 通过 CLI
repomix --instruction-file-path repomix-instruction.md

# 通过配置 (repomix.config.json)
{
  "output": {
    "instruction_file_path": "repomix-instruction.md"
  }
}

指令内容将包含在输出文件的 "Instruction" 部分中。

4.5 Token 计数

Repomix 提供 token 计数功能,帮助你了解代码库在 AI 模型 token 维度上的大小。

选择编码

使用 --token-count-encoding 选择分词器编码:

# 使用 GPT-4o 编码(默认)
repomix --token-count-encoding o200k_base

# 使用 GPT-3.5/4 编码
repomix --token-count-encoding cl100k_base

可视化 Token 分布

使用 --token-count-tree 显示带有 token 计数的文件树:

# 显示所有文件的 token 计数
repomix --token-count-tree

# 仅显示 token 数 ≥100 的文件
repomix --token-count-tree 100

4.6 大型代码库输出分割

对于超出 AI 模型上下文限制的大型代码库,你可以将输出分割为多个文件:

# 分割为约 500KB 的文件
repomix --split-output 500kb

# 分割为约 2MB 的文件
repomix --split-output 2mb

输出文件将按顺序编号(如 repomix-output.1.mdrepomix-output.2.md 等)。文件在目录边界处分割,以保持相关文件在一起。

4.7 Agent Skills 生成

Repomix 可以生成 Claude Agent Skills 格式的输出,为 AI 编码助手提供结构化的参考材料。

# 使用自动检测的名称生成 skills
repomix --skill-generate

# 使用自定义名称生成 skills
repomix --skill-generate my-project

# 直接指定输出目录路径
repomix --skill-output ./my-skills-dir

这将创建以下目录结构:

.claude/skills/<name>/
├── SKILL.md                          # 入口文件,包含使用指南
└── references/
    ├── summary.md                    # 用途、格式说明和统计信息
    ├── project-structure.md          # 带行数的目录树
    ├── files.md                      # 所有文件内容
    └── tech-stack.md                 # 语言、框架和依赖

4.8 代码压缩

Repomix 提供高级代码压缩功能,可以在保留关键信息的同时减少输出大小。此功能在处理大型代码库或需要专注于代码特定方面时特别有用。

4.8.1 压缩模式

接口模式 (keep_interfaces: true)

  • 保留函数和类签名及其完整的类型注解
  • 保留所有文档字符串以提供全面的 API 文档
  • 移除实现细节,用 pass 语句替换
  • 非常适合生成 API 文档或理解代码结构

签名模式 (keep_signatures: true, keep_interfaces: false)

  • 保留函数和类定义
  • 根据 keep_docstrings 设置选择性保留文档字符串
  • 保持完整的实现代码
  • 适用于标准代码压缩同时保持功能性

最小模式 (keep_signatures: false)

  • 移除所有函数和类定义
  • 仅保留全局变量、导入和模块级代码
  • 最大压缩,专注于配置和常量

4.8.2 配置选项

{
  "compression": {
    "enabled": false,           // 启用/禁用压缩
    "keep_signatures": true,    // 保留函数/类签名
    "keep_docstrings": true,    // 保留文档字符串
    "keep_interfaces": true     // 接口模式(仅签名 + 文档字符串)
  }
}

4.8.3 使用示例

生成 API 文档:

# 创建仅接口的输出用于 API 文档
repomix --config-override '{"compression": {"enabled": true, "keep_interfaces": true}}'

压缩实现细节:

# 保留签名但移除实现以获得代码概览
repomix --config-override '{"compression": {"enabled": true, "keep_interfaces": false, "keep_signatures": true, "keep_docstrings": false}}'

仅提取配置:

# 仅保留全局变量和常量
repomix --config-override '{"compression": {"enabled": true, "keep_signatures": false}}'

4.8.4 语言支持

目前,高级压缩功能完全支持:

  • Python: 基于 AST 的完整压缩,支持所有模式
  • JavaScript/TypeScript: 基于 Tree-sitter 的压缩
  • Go: 基于 Tree-sitter 的压缩
  • Java: 基于 Tree-sitter 的压缩
  • C/C++: 基于 Tree-sitter 的压缩
  • C#: 基于 Tree-sitter 的压缩
  • Rust: 基于 Tree-sitter 的压缩
  • Ruby: 基于 Tree-sitter 的压缩
  • PHP: 基于 Tree-sitter 的压缩
  • Swift: 基于 Tree-sitter 的压缩
  • CSS: 基于 Tree-sitter 的压缩
  • 其他语言: 基础压缩并显示警告(计划未来增强)

4.8.5 示例输出

原始 Python 代码:

def calculate_sum(a: int, b: int) -> int:
    """
    计算两个整数的和。
    
    Args:
        a: 第一个整数
        b: 第二个整数
        
    Returns:
        a 和 b 的和
    """
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("两个参数都必须是整数")
    
    result = a + b
    print(f"计算 {a} + {b} = {result}")
    return result

接口模式输出:

def calculate_sum(a: int, b: int) -> int:
    """
    计算两个整数的和。
    
    Args:
        a: 第一个整数
        b: 第二个整数
        
    Returns:
        a 和 b 的和
    """
    pass

4.9 忽略模式

Repomix 使用多个来源的忽略模式,并按以下优先级顺序应用:

  1. 配置文件中的自定义模式 (ignore.custom_patterns)
  2. .repomixignore 文件
  3. .ignore 文件(如果 ignore.use_dot_ignore 为 true)
  4. .gitignore 文件(如果 ignore.use_gitignore 为 true)
  5. 默认模式(如果 ignore.use_default_ignore 为 true)

忽略方法

.gitignore

默认情况下,Repomix 使用项目 .gitignore 文件中列出的模式。此行为可以通过配置文件中的 ignore.use_gitignore 选项来控制:

{
  "ignore": {
    "use_gitignore": true
  }
}
默认模式

Repomix 包含一个默认的常用排除文件和目录列表(例如,__pycache__.git,二进制文件)。此功能可以通过 ignore.use_default_ignore 选项进行控制:

{
  "ignore": {
    "use_default_ignore": true
  }
}

完整的默认忽略模式列表可以在 default_ignore.py 中找到。

.repomixignore

你可以在你的项目根目录下创建一个 .repomixignore 文件来定义 Repomix 特有的忽略模式。这个文件的格式与 .gitignore 相同。

.ignore

Repomix 也支持 .ignore 文件,格式与 .gitignore 相同。这对于多个工具共享同一个忽略文件非常有用。此行为可以通过 ignore.use_dot_ignore 配置选项或 --no-dot-ignore CLI 标志来控制。

自定义模式

可以使用配置文件中的 ignore.custom_patterns 选项来指定额外的忽略模式:

{
  "ignore": {
    "custom_patterns": [
      "*.log",
      "*.tmp",
      "tests/**/*.pyc"
    ]
  }
}

注释

  • 二进制文件默认不包含在打包输出中,但它们的路径会列在输出文件的"仓库结构"部分。这提供了仓库结构的完整概览,同时保持打包文件的高效性和基于文本的特性。
  • 忽略模式通过确保排除安全敏感文件和大型二进制文件来帮助优化生成的打包文件的大小,同时防止泄露机密信息。
  • 所有忽略模式都使用类似于 .gitignore 的 glob 模式语法。

🔒 5. 输出文件格式

Repomix 生成一个单独的文件,其中不同代码部分之间有清晰的分隔符。为了增强 AI 的理解能力,输出文件以面向 AI 的解释开头,使 AI 模型更容易理解打包存储库的上下文和结构。

5.1 纯文本格式(默认)

This file is a merged representation of the entire codebase, combining all repository files into a single document.

================================================================
File Summary
================================================================
(Metadata and usage AI instructions)

================================================================
Repository Structure
================================================================
src/
  cli/
    cliOutput.py
    index.py
  config/
    configLoader.py

(...remaining directories)

================================================================
Repository Files
================================================================

================
File: src/index.py
================
# File contents here

================
File: src/utils.py
================
# File contents here

(...remaining files)

================================================================
Statistics
================================================================
(File statistics and metadata)

5.2 Markdown 格式

要生成 Markdown 格式的输出,请使用 --style markdown 选项:

python -m repomix --style markdown

Markdown 格式以可读的方式构建内容:

# File Summary
(Metadata and usage AI instructions)

# Repository Structure

src/ cli/ cliOutput.py index.py


# Repository Files

## File: src/index.py
```python
# File contents here

File: src/utils.py

# File contents here

Statistics

  • Total Files: 19
  • Total Characters: 37377
  • Total Tokens: 11195

### 5.3 XML 格式

要生成 XML 格式的输出,请使用 `--style xml` 选项:


```bash
python -m repomix --style xml

XML格式以分层方式组织内容:

<?xml version="1.0" encoding="UTF-8"?>
<repository>
<repository_structure>
(Directory and file structure)
</repository_structure>

<repository_files>
<file>
  <path>src/index.py</path>
  <stats>
    <chars>1234</chars>
    <tokens>567</tokens>
  </stats>
  <content>
    # File contents here
  </content>
</file>
(...remaining files)
</repository_files>

<statistics>
  <total_files>19</total_files>
  <total_chars>37377</total_chars>
  <total_tokens>11195</total_tokens>
</statistics>
</repository>

5.4 JSON 格式

要生成 JSON 格式的输出,请使用 --style json 选项:

repomix --style json

JSON 格式提供机器可读的结构化输出:

{
  "summary": {
    "total_files": 19,
    "total_chars": 37377,
    "total_tokens": 11195,
    "generation_date": "2025-01-28T12:00:00"
  },
  "file_tree": {
    "src": {
      "index.py": "",
      "utils.py": ""
    }
  },
  "files": [
    {
      "path": "src/index.py",
      "content": "# File contents here",
      "chars": 1234,
      "tokens": 567
    }
  ]
}

JSON 格式非常适合:

  • 与其他工具和脚本集成
  • 对代码库分析进行程序化处理
  • 构建自定义管道和工作流

你可以使用 jq 从 JSON 输出中提取特定信息:

# 提取文件路径
cat repomix-output.json | jq '.files[].path'

# 获取总 token 数
cat repomix-output.json | jq '.summary.total_tokens'

# 查找 token 数超过 1000 的文件
cat repomix-output.json | jq '.files[] | select(.tokens > 1000) | {path, tokens}'

🛠️ 6. 高级用法

6.1 库的使用

你可以在你的项目中使用 Repomix 作为 Python 库。这是一个基本示例:

from repomix import RepoProcessor

# 基本用法
processor = RepoProcessor(".")
result = processor.process()

# 处理指定分支的远程仓库
processor = RepoProcessor(repo_url="https://github.com/username/repo", branch="feature-branch")
result = processor.process()

# 访问处理结果
print(f"总文件数: {result.total_files}")
print(f"总字符数: {result.total_chars}")
print(f"总标记数: {result.total_tokens}")
print(f"输出保存至: {result.config.output.file_path}")

6.2 高级配置

from repomix import RepoProcessor, RepomixConfig

# 创建自定义配置
config = RepomixConfig()

# 输出设置
config.output.file_path = "custom-output.md"
config.output.style = "markdown"  # 支持 "plain", "markdown" 和 "xml"
config.output.show_line_numbers = True

# 安全设置
config.security.enable_security_check = True
config.security.exclude_suspicious_files = True

# 压缩设置
config.compression.enabled = True
config.compression.keep_signatures = True
config.compression.keep_docstrings = True
config.compression.keep_interfaces = True  # 接口模式用于 API 文档

# 包含/忽略模式
config.include = ["src/**/*", "tests/**/*"]
config.ignore.custom_patterns = ["*.log", "*.tmp"]
config.ignore.use_gitignore = True

# 远程仓库配置
config.remote.url = "https://github.com/username/repo"
config.remote.branch = "feature-branch"

# 使用自定义配置处理仓库
processor = RepoProcessor(".", config=config)
result = processor.process()

6.2.1 压缩功能示例

from repomix import RepoProcessor, RepomixConfig

# 示例 1: 生成 API 文档(接口模式)
config = RepomixConfig()
config.compression.enabled = True
config.compression.keep_interfaces = True  # 仅保留签名 + 文档字符串
config.output.file_path = "api-documentation.md"

processor = RepoProcessor(".", config=config)
result = processor.process()
print(f"API 文档已生成: {result.config.output.file_path}")

# 示例 2: 代码概览,不包含实现细节
config = RepomixConfig()
config.compression.enabled = True
config.compression.keep_signatures = True
config.compression.keep_docstrings = False
config.compression.keep_interfaces = False  # 保留完整签名但移除文档字符串
config.output.file_path = "code-overview.md"

processor = RepoProcessor(".", config=config)
result = processor.process()

# 示例 3: 仅提取配置和常量
config = RepomixConfig()
config.compression.enabled = True
config.compression.keep_signatures = False  # 移除所有函数/类
config.output.file_path = "config-only.md"

processor = RepoProcessor(".", config=config)
result = processor.process()

更多示例代码,请查看 examples 目录:

  • basic_usage.py: 基本用法示例
  • custom_config.py: 自定义配置示例
  • security_check.py: 安全检查功能示例
  • file_statistics.py: 文件统计示例
  • remote_repo_usage.py: 远程仓库处理示例
  • json_output.py: JSON 输出格式示例
  • git_integration.py: Git diff、log 和排序示例
  • output_split.py: 大型代码库输出分割
  • token_count_tree.py: Token 分布可视化
  • full_directory_structure.py: 完整目录树显示
  • tree_sitter_compression.py: Tree-sitter 压缩示例

6.3 环境变量

  • REPOMIX_COCURRENCY_STRATEGY: 设置为 threadprocess 来手动控制用于文件处理的并发策略(默认为 process,但在 AWS Lambda 等环境中或显式设置时可能会自动使用 thread)。
  • REPOMIX_LOG_LEVEL: 设置日志级别。可用的值有 TRACEDEBUGINFOSUCCESSWARNERROR(默认为 INFO)。此设置控制日志输出的详细程度,不受 --verbose 标志的影响。

🤖 7. AI 使用指南

7.1 提示示例

一旦你使用 Repomix 生成了打包文件,你就可以将其与 Claude、ChatGPT 和 Gemini 等 AI 工具一起使用。以下是一些提示示例,可帮助你入门:

代码审查和重构

对于全面的代码审查和重构建议:

这个文件包含了我的全部代码库。请审查整体结构,并提出任何改进或重构的机会,重点关注可维护性和可扩展性。

文档生成

生成项目文档:

基于此文件中的代码库,请生成一个详细的README.md,其中包含项目概述、主要功能、设置说明和使用示例。

测试用例生成

用于生成测试用例:

分析此文件中的代码,并为主要函数和类提出一套全面的单元测试。包括边缘情况和潜在的错误场景。

代码质量评估

评估代码质量和对最佳实践的遵循情况:

审查代码库,检查其是否符合编码最佳实践和行业标准。找出在可读性、可维护性和效率方面可以改进的代码区域。提出具体的修改建议,使代码与最佳实践保持一致。

库概述

对库进行高层次的理解

这个文件包含了库的整个代码库。请提供该库的全面概述,包括其主要目的、关键特性和整体架构。

API 文档审查

用于审查 API 接口(使用接口模式压缩时):

这个文件包含了我的代码库的 API 接口,所有实现细节都已移除。请审查 API 设计,建议一致性改进,并识别任何缺失的文档或不清楚的方法签名。

代码架构分析

用于分析代码结构(使用签名模式压缩时):

这个文件包含了代码结构和函数签名,但实现细节很少。请分析整体架构,识别使用的设计模式,并建议改进以获得更好的模块化和关注点分离。

配置分析

用于分析配置和常量(使用最小模式压缩时):

这个文件仅包含我的代码库中的配置、常量和全局变量。请审查这些设置,识别潜在的配置问题,并建议配置管理的最佳实践。

7.2 MCP (Model Context Protocol) 服务器

Repomix 可以作为 MCP 服务器运行,允许 AI 助手如 Claude 直接与你的代码库交互,无需手动文件准备。

📦 需要安装: 在使用 MCP 功能之前,请确保已安装 repomix:pip install repomix

启动 MCP 服务器

# 启动 MCP 服务器(详细日志输出到 stderr)
repomix --mcp

启动后你会看到类似这样的日志:

📦 Repomix v0.3.0

Starting Repomix MCP Server...
🔧 Creating MCP server...
📦 Registering MCP tools...
  ✅ pack_codebase
  ✅ pack_remote_repository
  ✅ read_repomix_output
  ✅ grep_repomix_output
  ✅ file_system_read_file
  ✅ file_system_read_directory
  ✅ generate_skill
🎯 Repomix MCP Server configured with 7 tools
🚀 Starting Repomix MCP Server on stdio transport...
📡 Waiting for MCP client connections...
💡 Use Ctrl+C to stop the server
──────────────────────────────────────────────────

在 AI 助手中配置

Claude Desktopclaude_desktop_config.json 中添加:

{
  "mcpServers": {
    "repomix": {
      "command": "repomix",
      "args": ["--mcp"],
      "cwd": "/path/to/your/project"
    }
  }
}

VS Code / Clinecline_mcp_settings.json 中添加:

{
  "mcpServers": {
    "repomix": {
      "command": "repomix",
      "args": ["--mcp"],
      "cwd": "/path/to/your/project"
    }
  }
}

Claude Code

# 安装 repomix 后可从任意目录运行
claude mcp add repomix -- repomix --mcp

关于 cwd 参数

MCP 配置中的 cwd(当前工作目录)参数决定 repomix 命令的运行位置。以下是推荐的设置:

  • 通用使用: 设置 cwd 为你的主目录或任何稳定位置,如 "/Users/yourusername"(macOS)或 "/home/yourusername"(Linux)
  • 特定项目: 设置 cwd 为你经常分析的主项目目录
  • 开发用途: 你可以使用任何目录,因为 repomix 可以处理工具调用中指定的任何路径

示例:

// 通用使用 - 从任何地方工作
"cwd": "/Users/yourusername"

// 项目特定 - 方便频繁分析
"cwd": "/Users/yourusername/projects/my-main-project"

// 开发 - 灵活的起始点
"cwd": "/Users/yourusername/dev"

💡 专业提示: MCP 工具允许你在工具参数中指定目标目录,所以 cwd 只是起始位置。无论服务器从哪里启动,你都可以分析任何可访问的目录。

可用 MCP 工具

  1. pack_codebase - 打包本地代码库为 XML 格式

    • 参数: directory, compress, include_patterns, ignore_patterns, top_files_length
  2. read_repomix_output - 读取生成的输出文件

    • 参数: output_id, start_line, end_line
  3. grep_repomix_output - 在输出文件中搜索

    • 参数: output_id, pattern, context_lines, ignore_case
  4. file_system_read_file - 从文件系统读取文件

    • 参数: path
  5. file_system_read_directory - 列出目录内容

    • 参数: path
  6. pack_remote_repository - 打包远程仓库

    • 参数: remote, compress, include_patterns, ignore_patterns
  7. generate_skill - 从代码库生成 Claude Agent Skills

    • 参数: directory, skill_name, include_patterns, ignore_patterns

工具调用日志

当 AI 助手调用工具时,你会在服务器终端看到详细日志:

🔨 MCP Tool Called: pack_codebase
   📁 Directory: /path/to/project
   🗜️ Compress: false
   📊 Top files: 10
   🏗️ Creating workspace...
   📝 Output will be saved to: /tmp/repomix_mcp_xxx/repomix-output.xml
   🔄 Processing repository...
   ✅ Processing completed!
   📊 Files processed: 45
   📝 Characters: 125,432
   🎯 Tokens: 0
   🎉 MCP response generated successfully

功能特点

  • ✅ 完整的 MCP 协议支持
  • ✅ 详细的操作日志
  • ✅ 安全文件检查
  • ✅ 多种输出格式
  • ✅ 文件搜索和读取
  • ✅ 临时文件管理
  • ✅ 代码压缩功能(基于 Tree-sitter)
  • 🔄 远程仓库支持(开发中)

7.3 最佳实践

  • 具体明确: 在提示 AI 时,尽可能具体地说明你想要什么。你提供的上下文越多,结果就越好。
  • 迭代: 不要害怕迭代你的提示。如果你第一次没有得到想要的结果,请改进你的提示并再次尝试。
  • 结合人工审查: 虽然 AI 是一个强大的工具,但它并非完美。始终将 AI 生成的输出与人工审查和编辑相结合。
  • 安全第一: 在使用代码库时,始终注意安全。使用 Repomix 的内置安全检查,并避免与 AI 工具共享敏感信息。

📄 8. 许可证

本项目根据 MIT 许可证获得许可。


有关用法和配置选项的更多详细信息,请访问仓库