existing-repo existing-repo

现有代码库技能,用于分析和维护代码库结构,设置最佳实践和护栏,避免破坏现有代码。

架构设计 0 次安装 0 次浏览 更新于 3/5/2026

现有代码库技能

加载于:base.md + security.md

对于处理现有代码库 - 分析结构,尊重约定,并设置适当的护栏,不要破坏任何东西。

来源: Husky | lint-staged | pre-commit | commitlint


核心原则

在修改之前先理解。 现有代码库有约定、模式和历史。你的工作是在它们内部工作,而不是重新组织它们。


第一阶段:代码库分析

加入现有代码库时首先运行此分析。

1.1 基本检测

# 检查 git 状态
git remote -v 2>/dev/null
git branch -a 2>/dev/null
git log --oneline -5 2>/dev/null

# 检查现有配置
ls -la .* 2>/dev/null | head -20
ls *.json *.toml *.yaml *.yml 2>/dev/null

1.2 技术栈检测

# JavaScript/TypeScript
ls package.json tsconfig.json 2>/dev/null

# Python
ls pyproject.toml setup.py requirements*.txt 2>/dev/null

# 移动开发
ls pubspec.yaml 2>/dev/null          # Flutter
ls android/build.gradle 2>/dev/null   # Android
ls ios/*.xcodeproj 2>/dev/null        # iOS

# 其他
ls Cargo.toml 2>/dev/null             # Rust
ls go.mod 2>/dev/null                 # Go
ls Gemfile 2>/dev/null                # Ruby

1.3 代码库结构类型

模式 检测 含义
Monorepo packages/, apps/, workspaces 在 package.json 中 多个项目,共享工具
Full-Stack Monolith frontend/ + backend/ 在同一个代码库中 单一团队,紧密耦合
Separate Concerns 只有前端或后端代码 分开的代码库,分开部署
Microservices 多个 service-* 或领域目录 分布式架构
# 检测代码库结构类型
if [ -d "packages" ] || [ -d "apps" ]; then
    echo "MONOREPO detected"
elif [ -d "frontend" ] && [ -d "backend" ]; then
    echo "FULL-STACK MONOLITH detected"
elif [ -d "src" ] || [ -d "app" ]; then
    # 检查它是前端还是后端
    grep -q "react\|vue\|angular" package.json 2>/dev/null && echo "FRONTEND detected"
    grep -q "fastapi\|express\|django" package.json pyproject.toml 2>/dev/null && echo "BACKEND detected"
fi

1.4 目录映射

# 获取目录结构(最多3级)
find . -type d -maxdepth 3 \
    -not -path "*/node_modules/*" \
    -not -path "*/.git/*" \
    -not -path "*/venv/*" \
    -not -path "*/__pycache__/*" \
    -not -path "*/dist/*" \
    -not -path "*/build/*" \
    2>/dev/null | head -50

# 识别关键目录
for dir in src app lib core services api routes components pages hooks utils models; do
    [ -d "$dir" ] && echo "Found: $dir/"
done

1.5 入口点

# 查找主要入口点
ls index.ts index.js main.ts main.py app.py server.ts server.js 2>/dev/null
cat package.json 2>/dev/null | grep -A1 '"main"'
cat pyproject.toml 2>/dev/null | grep -A1 'scripts'

第二阶段:约定检测

在做出改变之前识别并记录现有的模式。

2.1 代码风格

# 检查格式化程序
ls .prettierrc* .editorconfig .eslintrc* biome.json 2>/dev/null  # JS/TS
ls pyproject.toml | xargs grep -l "ruff\|black\|isort" 2>/dev/null  # Python

# 从现有文件中检查缩进风格
head -20 src/**/*.ts 2>/dev/null | grep "^\s" | head -1  # tabs vs spaces

2.2 测试设置

# JS/TS 测试
grep -l "jest\|vitest\|mocha\|playwright" package.json 2>/dev/null
ls jest.config.* vitest.config.* playwright.config.* 2>/dev/null

# Python 测试
grep -l "pytest\|unittest" pyproject.toml 2>/dev/null
ls pytest.ini conftest.py 2>/dev/null

# 测试目录
ls -d tests/ test/ __tests__/ spec/ 2>/dev/null

2.3 CI/CD 设置

# 检查现有工作流
ls -la .github/workflows/ 2>/dev/null
ls .gitlab-ci.yml Jenkinsfile .circleci/ 2>/dev/null

# 检查部署配置
ls vercel.json render.yaml fly.toml railway.json Dockerfile 2>/dev/null

2.4 文档风格

# 查找 README 模式
head -30 README.md 2>/dev/null

# 查找现有文档
ls -la docs/ documentation/ wiki/ 2>/dev/null
ls CONTRIBUTING.md CHANGELOG.md 2>/dev/null

第三阶段:护栏审核

检查存在的护栏和缺失的护栏。

3.1 预提交钩子状态

# 检查钩子管理器
ls .husky/ 2>/dev/null && echo "Husky installed"
ls .pre-commit-config.yaml 2>/dev/null && echo "pre-commit framework installed"
ls .git/hooks/pre-commit 2>/dev/null && echo "Manual pre-commit hook exists"

# 检查运行的钩子
cat .husky/pre-commit 2>/dev/null
cat .pre-commit-config.yaml 2>/dev/null

3.2 代码检查状态

# JS/TS 代码检查
grep -q "eslint" package.json && echo "ESLint configured"
grep -q "biome" package.json && echo "Biome configured"
ls .eslintrc* biome.json 2>/dev/null

# Python 代码检查
grep -q "ruff" pyproject.toml && echo "Ruff configured"
grep -q "flake8" pyproject.toml setup.cfg && echo "Flake8 configured"

3.3 类型检查状态

# TypeScript
ls tsconfig.json 2>/dev/null && echo "TypeScript configured"
grep "strict" tsconfig.json 2>/dev/null

# Python 类型检查
grep -q "mypy" pyproject.toml && echo "mypy configured"
grep -q "pyright" pyproject.toml && echo "pyright configured"
ls py.typed 2>/dev/null

3.4 提交消息执行

# commitlint
ls commitlint.config.* 2>/dev/null && echo "commitlint configured"
cat .husky/commit-msg 2>/dev/null
grep "conventional" package.json 2>/dev/null

3.5 安全扫描

# 检查安全工具
grep -q "detect-secrets\|trufflehog" .pre-commit-config.yaml package.json 2>/dev/null
ls .github/workflows/*.yml | xargs grep -l "security\|audit" 2>/dev/null

第四阶段:护栏设置

只添加缺失的护栏。永远不要覆盖现有配置。

4.1 JavaScript/TypeScript 项目

Husky + lint-staged(如果不存在)

# 检查是否已安装
if [ ! -d ".husky" ]; then
    # 安装 Husky
    npm install -D husky lint-staged
    npx husky init

    # 创建 pre-commit 钩子
    echo 'npx lint-staged' > .husky/pre-commit
    chmod +x .husky/pre-commit
fi

lint-staged 配置(如果缺失,添加到 package.json):

{
  "lint-staged": {
    "*.{ts,tsx,js,jsx}": [
      "eslint --fix",
      "prettier --write"
    ],
    "*.{json,md,yml,yaml}": [
      "prettier --write"
    ]
  }
}

ESLint(如果不存在)

# 检查 eslint 是否存在
if ! grep -q "eslint" package.json; then
    npm install -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
fi

eslint.config.js(ESLint 9+ 扁平配置):

import eslint from '@eslint/js'
import tseslint from 'typescript-eslint'

export default tseslint.config(
  eslint.configs.recommended,
  ...tseslint.configs.recommended,
  {
    rules: {
      '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
      '@typescript-eslint/explicit-function-return-type': 'off',
      'no-console': ['warn', { allow: ['warn', 'error'] }]
    }
  },
  {
    ignores: ['dist/', 'node_modules/', 'coverage/']
  }
)

Prettier(如果不存在)

if ! grep -q "prettier" package.json; then
    npm install -D prettier
fi

.prettierrc(尊重现有风格或使用合理的默认值):

{
  "semi": false,
  "singleQuote": true,
  "trailingComma": "es5",
  "tabWidth": 2,
  "printWidth": 100
}

commitlint(如果不存在)

if [ ! -f "commitlint.config.js" ]; then
    npm install -D @commitlint/cli @commitlint/config-conventional
    echo "npx commitlint --edit \$1" > .husky/commit-msg
    chmod +x .husky/commit-msg
fi

commitlint.config.js

export default {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      ['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore', 'ci', 'perf', 'revert']
    ],
    'subject-case': [2, 'always', 'lower-case'],
    'subject-max-length': [2, 'always', 72]
  }
}

4.2 Python 项目

pre-commit 框架(如果不存在)

# 安装 pre-commit
if [ ! -f ".pre-commit-config.yaml" ]; then
    pip install pre-commit
    pre-commit install
fi

.pre-commit-config.yaml

repos:
  # Ruff - 代码检查和格式化(替代 black, isort, flake8)
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.14.13
    hooks:
      - id: ruff
        args: [--fix, --exit-non-zero-on-fix]
      - id: ruff-format

  # 类型检查
  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.16.0
    hooks:
      - id: mypy
        additional_dependencies: [types-requests]
        args: [--ignore-missing-imports]

  # 安全
  - repo: https://github.com/Yelp/detect-secrets
    rev: v1.5.0
    hooks:
      - id: detect-secrets
        args: ['--baseline', '.secrets.baseline']

  # 通用
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
      - id: check-merge-conflict

  # 提交消息
  - repo: https://github.com/compilerla/conventional-pre-commit
    rev: v4.0.0
    hooks:
      - id: conventional-pre-commit
        stages: [commit-msg]

pyproject.toml 补充(如果不存在)

[tool.ruff]
target-version = "py312"
line-length = 100

[tool.ruff.lint]
select = [
    "E",   # pycodestyle 错误
    "F",   # pyflakes
    "I",   # isort
    "B",   # flake8-bugbear
    "UP",  # pyupgrade
    "S",   # flake8-bandit (安全)
]
ignore = ["E501"]  # 行长度由格式化程序处理

[tool.mypy]
python_version = "3.12"
strict = true
ignore_missing_imports = true

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --cov=src --cov-report=term-missing --cov-fail-under=80"

4.3 分支保护(用户文档)

推荐这些 GitHub 分支保护规则:

## 推荐的分支保护(主分支)

1. **在合并前需要拉取请求**
   - 需要 1 个批准
   - 在新提交上丢弃过时的审查

2. **需要状态检查**
   - 代码检查
   - 类型检查
   - 测试
   - 安全扫描

3. **需要签名的提交**(可选,但推荐)

4. **不允许绕过上述设置**

第五阶段:结构保护规则

永不做这些

  • 不要重新组织目录结构 - 在现有模式内工作
  • 不要为了“一致性”重命名文件 - 匹配现有的命名约定
  • 不要添加新模式 - 使用代码库中已有的模式
  • 不要改变导入样式 - 匹配现有的(相对 vs 绝对等)
  • 不要改变格式化 - 匹配现有的风格或使用现有的格式化器配置
  • 不要轻易添加新依赖 - 检查是否存在等效的

总是做这些

  • 先读现有代码 - 在写新代码之前理解模式
  • 匹配现有约定 - 命名、结构、错误处理
  • 使用现有工具 - 不要重新发明已经存在的东西
  • 遵循现有的测试模式 - 匹配测试文件的命名和结构
  • 保留现有配置 - 只添加,不要修改除非修复错误

约定检测清单

在编写任何代码之前,识别:

约定 示例 检查哪里
命名 camelCase vs snake_case 现有文件名
文件结构 feature/ vs type/ 目录布局
导出风格 default vs named 现有模块
错误处理 throw vs return Error 现有函数
日志记录 console vs logger 现有代码
测试 describe/it vs test() 现有测试
注释 JSDoc vs inline 现有代码

第六阶段:分析报告模板

运行分析后,生成此报告:

# 代码库分析报告

## 概览
- **代码库类型**:[Monorepo | Full-Stack | Frontend | Backend | Microservices]
- **主要语言**:[TypeScript | Python | ...]
- **框架**:[React | FastAPI | ...]
- **年龄**:[X 提交,Y 贡献者]

## 目录结构

[tree output]


## 技术栈
| 类别 | 技术 | 配置文件 |
|----------|------------|-------------|
| 语言 | TypeScript | tsconfig.json |
| 框架 | React | - |
| 测试 | Vitest | vitest.config.ts |
| 代码检查 | ESLint | eslint.config.js |
| 格式化 | Prettier | .prettierrc |

## 护栏状态

### 现有
- [x] ESLint 配置
- [x] Prettier 配置
- [x] TypeScript 严格模式

### 缺失(推荐)
- [ ] 预提交钩子(Husky + lint-staged)
- [ ] 提交消息验证(commitlint)
- [ ] CI 中的安全扫描

## 检测到的约定
| 模式 | 观察到的 | 示例 |
|---------|----------|---------|
| 命名 | camelCase | `getUserById.ts` |
| 导入 | 绝对 | `@/components/Button` |
| 测试 | 同位 | `Button.test.tsx` |
| 导出 | 命名 | `export { Button }` |

## 建议
1. 添加 Husky + lint-staged 用于预提交钩子
2. 添加 commitlint 用于常规提交
3. 在 GitHub Actions 中添加安全工作流

## 首先审查的文件
- `src/index.ts` - 主入口点
- `src/utils/` - 共享工具
- `tests/setup.ts` - 测试配置

逐步实施策略

不要一次添加所有护栏。按照这个时间线:

重点 为什么
1 格式化(Prettier/Ruff) 非破坏性,容易赢
2 代码检查(ESLint/Ruff) 捕获明显问题
3 预提交钩子 自动化第 1-2 周
4 提交消息验证 团队一致性
5 类型检查严格性 捕获运行时错误
6 安全扫描 捕获漏洞

处理独立代码库

当前端和后端在不同的代码库中时:

前端代码库设置

# 克隆并分析
git clone [frontend-repo]
cd frontend

# 运行分析
# 预期:React/Vue/Angular,无后端代码

# 添加前端特定的护栏
# - Husky + lint-staged
# - ESLint + Prettier
# - 组件测试(Vitest/Jest)

后端代码库设置

# 克隆并分析
git clone [backend-repo]
cd backend

# 运行分析
# 预期:FastAPI/Express/Django,无前端代码

# 添加后端特定的护栏
# - pre-commit 框架
# - Ruff + mypy
# - API 测试(pytest/Jest)

跨代码库协调

问题 解决方案
共享类型 从 OpenAPI 规范生成
API 契约 契约测试(Pact)
部署 通过 CI/CD 触发器协调
版本控制 两个都使用语义版本控制

反模式

  • 添加未使用的护栏 - 只添加团队将使用的
  • 第一天就严格规则 - 逐步引入
  • 在警告上阻塞 - 开始宽容,随时间收紧
  • 忽略现有模式 - 与现有工作
  • 过度工程 - 简单规则 > 复杂系统
  • 跳过分析阶段 - 总是先理解再改变

快速参考:检测命令

# 一键代码库分析
echo "=== Repo Type ===" && \
ls -d packages apps frontend backend 2>/dev/null || echo "Standard repo" && \
echo "=== Tech Stack ===" && \
ls *.json *.toml *.yaml 2>/dev/null && \
echo "=== Existing Guardrails ===" && \
ls .husky .pre-commit-config.yaml .eslintrc* 2>/dev/null || echo "None detected" && \
echo "=== Entry Points ===" && \
ls index.* main.* app.* server.* 2>/dev/null