GitHub仓库扁平化工具

RepoStack是一个将GitHub仓库转换为Claude可读格式的工具,适用于代码审查、安全审计和学习新框架等场景。

  • by oms0401
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 oms0401/repopack-MCP-git-flatner

使用说明

🚀 Repopack-Claude的GitHub仓库扁平化工具

在几秒钟内将整个GitHub存储库打包到Claude就绪的上下文中。

RepoStack是一个功能强大的模型上下文协议(MCP)服务器,可以将任何GitHub存储库转换为一个格式精美的文件,Claude可以立即分析。无需手动复制,无需丢失文件——只需纯粹的代码库智能。

🎯 它做什么

RepoStack授权克劳德:

  • 📦 即刻进入 -使用单个命令获取任何GitHub存储库
  • 🔍 智能提取 -自动识别并提取相关代码文件
  • 📄 完美的格式 -将所有内容连接成一个干净、可导航的文档
  • 🤖 完整上下文 -为Claude提供任何代码库的完整图片

非常适合代码审查、安全审计、文档生成、学习新框架、架构分析和技术面试。

✨ 特性

  • ✅ 公共和私人仓库 -适用于任何GitHub存储库
  • ✅ 智能过滤 -排除依赖关系、构建文件和干扰
  • ✅ 40+语言 -Python、JavaScript、TypeScript、Go、Rust等
  • ✅ 可配置限制 -控制要包含的文件数量
  • ✅ 自动分支检测 -自动查找主/主
  • ✅ 美丽的输出 -清理分隔符和文件头
  • ✅ 迅速的 -异步操作以获得最大速度

🎬 演示

You: "RepoStack, analyze https://github.com/facebook/react"

Claude: *fetches entire React codebase*
        "React is a declarative JavaScript library for building user interfaces..."
        *provides deep insights from the actual source code*

📋 先决条件

  • Python 3.8+ 安装在您的系统上
  • 克劳德桌面 应用
  • GitHub账号 (私人回购)

🚀 快速开始

步骤1:安装

# Clone RepoStack
git clone <your-repo-url>
cd repostack

# Install dependencies
pip install fastmcp httpx

💡 专业提示: 使用虚拟环境:

python -m venv venv
venv\Scripts\activate  # Windows
source venv/bin/activate  # macOS/Linux
pip install fastmcp httpx

步骤2:配置Claude桌面

视窗🪟

  1. 按 Win + R 类型: %APPDATA%\Claude
  2. 创建或编辑 claude_desktop_config.json
  3. 添加此配置:
{
  "mcpServers": {
    "repostack": {
      "command": "python",
      "args": ["D:\\path\\to\\repostack\\github_flattener.py"]
    }
  }
}

macOS🍎

code ~/Library/Application\ Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "repostack": {
      "command": "python3",
      "args": ["/path/to/repostack/github_flattener.py"]
    }
  }
}

Linux🐧

nano ~/.config/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "repostack": {
      "command": "python3",
      "args": ["/path/to/repostack/github_flattener.py"]
    }
  }
}

第三步:重启克劳德

重要提示: 完全退出Claude Desktop(不仅仅是最小化)并重新启动它。

💬 用法

只需自然地与Claude聊天:

🎯 基本命令

"Flatten https://github.com/openai/whisper"
"Use RepoStack on github.com/vercel/next.js"
"Analyze the codebase at https://github.com/microsoft/typescript"

🎨 创意提示

代码审查:

"RepoStack https://github.com/user/project and review the code quality"

安全审计:

"Find security vulnerabilities in https://github.com/user/webapp"

架构分析:

"Explain the architecture of https://github.com/nestjs/nest"

学习:

"How does https://github.com/django/django handle authentication?"

文档:

"Create comprehensive docs for https://github.com/user/api"

迁移规划:

"How would I migrate https://github.com/user/js-app to TypeScript?"

⚙️ 配置

参数

参数 类型 必填 默认 说明
repo_url string ✅ 是 - GitHub URL或 owner/repo 格式
github_token string ❌ 否 无 私有仓库的个人访问令牌
max_files 编号 ❌ 否 100 要包含的最大文件数(防止上下文过多)

例子

限制文件:

"Flatten https://github.com/large/repo with max 50 files"

私有存储库:

"Flatten https://github.com/user/private with token ghp_your_token_here"

🔐 私人存储库

对于私有存储库,您需要一个GitHub个人访问令牌:

  1. 访问https://github.com/settings/tokens
  2. 点击 “生成新令牌(经典)”
  3. 命名它: RepoStack MCP
  4. 选择范围: repo (完全控制私有存储库)
  5. 点击 “生成令牌”
  6. 安全地复制并保存您的令牌

用途:

"Flatten https://github.com/mycompany/private-api with token ghp_abc123xyz"

📁 支持的文件类型

RepoStack智能地包括:

语言

py js ts jsx tsx java cpp c h cs go rs rb php swift kt scala r m sh

网络

html css scss sass less vue svelte

配置

json yaml yml toml xml md txt

特别

Makefile Dockerfile .gitignore .env.example

🚫 自动排除

RepoStack会自动跳过:

  • 📁 依赖关系: node_modules/, vendor/, dist/, build/
  • 🔒 隐藏物: __pycache__/, .next/, .nuxt/, coverage/
  • 🔐 环境: venv/, env/, .venv/
  • 📦 锁定文件: package-lock.json, yarn.lock, pnpm-lock.yaml
  • 🗜️ 缩小: .min.js, .min.css, bundle.js

🐛 故障排除

“ModuleNotFoundError:没有名为'fastmcp'的模块”

pip install fastmcp httpx

“服务器立即断开连接”

检查你的Python路径:

where python      # Windows
which python3     # macOS/Linux

使用更新配置 完整路径:

{
  "mcpServers": {
    "repostack": {
      "command": "C:\\Python313\\python.exe",
      "args": ["D:\\path\\to\\github_flattener.py"]
    }
  }
}

“超过了GitHub API速率限制”

您已达到GitHub的速率限制(无身份验证时每小时60个请求)。

解决方案: 添加一个GitHub令牌,将限制增加到5000/小时。

“在Claude中看不到RepoStack”

  1. ✅ 验证配置文件没有JSON语法错误
  2. ✅ 完全退出并重新启动Claude Desktop
  3. ✅ 检查日志:Claude→ Help → 查看日志
  4. ✅ 独立测试服务器(请参阅测试部分)

“未找到存储库(404)”

  • 验证存储库URL是否正确
  • 对于私有仓库,请确保您使用的是有效的令牌
  • 检查存储库是否未被删除或重命名

🧪 测试

方法1:MCP检查员(推荐)

npx @modelcontextprotocol/inspector

连接:

  • 命令: python (或完整路径)
  • Args: D:\path\to\github_flattener.py

方法2:直接测试脚本

创建 test.py:

import asyncio
import httpx
import os

# Copy the helper functions from your main file
CODE_EXTENSIONS = {
    '.py', '.js', '.ts', '.jsx', '.tsx', '.java', '.cpp', '.c', '.h', '.hpp',
    '.cs', '.go', '.rs', '.rb', '.php', '.swift', '.kt', '.scala', '.r',
    '.m', '.mm', '.sh', '.bash', '.zsh', '.sql', '.html', '.css', '.scss',
    '.sass', '.less', '.vue', '.svelte', '.json', '.yaml', '.yml', '.toml',
    '.xml', '.md', '.txt', '.gitignore', '.env.example', 'Makefile', 'Dockerfile'
}

EXCLUDE_PATTERNS = {
    'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',
    '.min.js', '.min.css', 'bundle.js'
}

async def fetch_repo_tree(owner: str, repo: str, token: str = None):
    url = f"https://api.github.com/repos/{owner}/{repo}/git/trees/main?recursive=1"
    headers = {"Accept": "application/vnd.github.v3+json"}
    if token:
        headers["Authorization"] = f"token {token}"
    
    async with httpx.AsyncClient() as client:
        response = await client.get(url, headers=headers, timeout=30.0)
        if response.status_code == 404:
            url = f"https://api.github.com/repos/{owner}/{repo}/git/trees/master?recursive=1"
            response = await client.get(url, headers=headers, timeout=30.0)
        
        response.raise_for_status()
        data = response.json()
        return data.get("tree", [])

async def fetch_file_content(owner: str, repo: str, path: str, token: str = None):
    url = f"https://raw.githubusercontent.com/{owner}/{repo}/main/{path}"
    headers = {}
    if token:
        headers["Authorization"] = f"token {token}"
    
    async with httpx.AsyncClient() as client:
        response = await client.get(url, headers=headers, timeout=30.0)
        if response.status_code == 404:
            url = f"https://raw.githubusercontent.com/{owner}/{repo}/master/{path}"
            response = await client.get(url, headers=headers, timeout=30.0)
        
        if response.status_code == 200:
            try:
                return response.text
            except:
                return f"[Binary file: {path}]"
        return ""

def should_include_file(path: str):
    for pattern in EXCLUDE_PATTERNS:
        if pattern in path:
            return False
    
    ignore_dirs = ['node_modules/', '.git/', 'dist/', 'build/', '__pycache__/', 
                   'venv/', 'env/', '.next/', '.nuxt/', 'coverage/']
    if any(ignore_dir in path for ignore_dir in ignore_dirs):
        return False
    
    _, ext = os.path.splitext(path)
    filename = os.path.basename(path)
    return ext.lower() in CODE_EXTENSIONS or filename in CODE_EXTENSIONS

async def test_flatten(repo_url: str, max_files: int = 20):
    """Test the flattening logic directly"""
    repo_url = repo_url.strip().rstrip('/')
    if "github.com/" in repo_url:
        parts = repo_url.split("github.com/")[1].split("/")
        owner, repo = parts[0], parts[1]
    else:
        parts = repo_url.split("/")
        owner, repo = parts[0], parts[1]
    
    print(f"Fetching repo: {owner}/{repo}")
    
    tree = await fetch_repo_tree(owner, repo)
    print(f"Total items in tree: {len(tree)}")
    
    files_to_fetch = [
        item for item in tree 
        if item["type"] == "blob" and should_include_file(item["path"])
    ][:max_files]
    
    print(f"Files to fetch: {len(files_to_fetch)}")
    
    output_lines = [
        f"# Flattened Repository: {owner}/{repo}",
        f"# Total files included: {len(files_to_fetch)}",
        "=" * 80,
        ""
    ]
    
    for item in files_to_fetch:
        path = item["path"]
        print(f"Fetching: {path}")
        content = await fetch_file_content(owner, repo, path)
        
        if content:
            output_lines.extend([
                "",
                f"{'=' * 80}",
                f"# FILE: {path}",
                f"{'=' * 80}",
                content,
                ""
            ])
    
    result = "\n".join(output_lines)
    return result

async def main():
    result = await test_flatten(
        repo_url="https://github.com/fastmcp/fastmcp",
        max_files=10
    )
    print("\n" + "="*80)
    print("RESULT (first 2000 chars):")
    print("="*80)
    print(result[:2000])
    print(f"\n... (Total length: {len(result)} characters)")

if __name__ == "__main__":
    asyncio.run(main())

运行:

python test.py

📊 演出

RepoStack针对速度进行了优化:

  • 小型仓库 (<50个文件):约2-5秒
  • 中等存储库 (50-200个文件):~5-15秒
  • 大型回购 (200+个文件):~15-30秒

时间因网络速度和文件大小而异

🔒 安全与隐私

  • ✅ 所有数据都保存在您、GitHub和Claude之间
  • ✅ RepoStack不存储或记录任何数据
  • ✅ 令牌仅用于API身份验证
  • ✅ 开源-自己审核代码

🛠️ 发展

项目结构

repostack/
├── github_flattener.py    # Main MCP server
├── requirements.txt       # Dependencies
├── README.md             # This file
├── LICENSE               # MIT License
└── tests/                # Test files
    └── test_mcp.py

贡献

我们热爱贡献!

  1. 分叉存储库
  2. 创建要素分支: git checkout -b feature/amazing-feature
  3. 提交您的更改: git commit -m 'Add amazing feature'
  4. 推到分支: git push origin feature/amazing-feature
  5. 打开拉取请求

📝 需求

创建 requirements.txt:

fastmcp>=0.1.0
httpx>=0.27.0

安装:

pip install -r requirements.txt

🎓 用例

面向开发者

  • 🔍 快速代码库探索
  • 🐛 大型项目中的漏洞搜寻
  • 📚 从流行的开源项目中学习
  • 🔄 重构协助

对于团队

  • 👀 代码审查自动化
  • 📖 文档生成
  • 🏗️ 体系结构分析
  • 🔐 安全审计

对于学习者

  • 📖 研究真实世界的代码库
  • 🎯 了解设计模式
  • 🚀 学习最佳实践
  • 💡 获取复杂代码的解释

🌟 专业提示

  1. 从小处着手: 首先使用较小的存储库进行测试(<50个文件)
  2. 使用代币: 始终使用GitHub令牌以避免费率限制
  3. 限制文件: 使用 max_files 对于非常大的存储库
  4. 具体来说: 向Claude询问有关代码的具体问题
  5. 组合工具: 与克劳德的其他工具配合使用,以获得最大功率

📜 许可证

MIT许可证-使用它,修改它,运送它!看 LICENSE 文件以获取详细信息。

🙏 鸣谢

用爱建造:

📞 支持

需要帮助?获取方法如下:

  1. 📖 检查 故障排除 章节
  2. 🔍 审查 MCP文件
  3. 💬 打开一个 GitHub上的问题
  4. 📧 联系人:your-email@example.com

🚀 接下来是什么?

即将推出的功能:

  • []支持GitLab和Bitbucket
  • []自定义文件筛选规则
  • []分支机构之间的差异分析
  • []直接Git克隆支持
  • []存储库比较工具
  • []代码统计和见解

⭐ 如果RepoStack对你有所帮助,请在GitHub上给它一颗星!

由以下材料制成❤️ 由Om Manoj Sharma为开发者社区撰写