You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cbmc/codedetect/CONTRIBUTING.md

11 KiB

CodeDetect 贡献指南

感谢您对CodeDetect项目的关注本文档将指导您如何为项目做出贡献。

目录

行为准则

我们的承诺

为了营造开放和友好的环境,我们作为贡献者和维护者承诺:

  • 友善和包容
  • 尊重不同观点和经验
  • 耐心接受建设性批评
  • 关注社区最大利益

不当行为

不当行为包括:

  • 使用性暗示语言或图像
  • 人身攻击或侮辱性评论
  • 公开或私下骚扰
  • 未经明确许可发布他人信息

开始贡献

寻找要贡献的内容

  1. 查看 Issues 中标记为 "good first issue" 的问题
  2. 查看 Features 中请求的功能
  3. 改进文档
  4. 修复拼写错误或格式问题
  5. 添加测试用例

与团队沟通

  • 在开始工作之前先创建Issue讨论
  • 在Issue中@相关维护者
  • 加入我们的社区讨论

开发环境设置

前提条件

  • Python 3.8+
  • Git
  • CBMC (可选,用于运行完整测试)

克隆仓库

git clone https://github.com/your-username/codedetect.git
cd codedetect

设置开发环境

# 创建虚拟环境
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# 安装依赖
pip install -r requirements.txt
pip install -r requirements-dev.txt

# 安装pre-commit hooks
pre-commit install

验证设置

# 运行测试
python -m pytest tests/unit/ -v

# 检查代码风格
black --check src/ tests/
flake8 src/ tests/
isort --check-only src/ tests/

# 检查类型
mypy src/

代码规范

Python代码风格

我们遵循以下工具和规范:

  • Black: 代码格式化
  • flake8: 代码风格检查
  • isort: 导入排序
  • mypy: 类型检查

格式化代码

# 格式化代码
black src/ tests/
isort src/ tests/

# 检查格式
black --check src/ tests/
isort --check-only src/ tests/

代码风格规则

# 好的示例
import os
from typing import List, Dict

class CodeProcessor:
    """代码处理器类"""

    def __init__(self, config: Dict[str, Any]):
        self.config = config

    def process_code(self, code: str) -> List[str]:
        """处理代码

        Args:
            code: 要处理的代码字符串

        Returns:
            处理后的代码行列表
        """
        if not code:
            return []

        return code.split('\n')

# 避免的做法
class codeProcessor:  # 类名应该使用CamelCase
    def __init__(self,config):  # 缺少空格和类型注解
        self.config=config

文档规范

文档字符串

使用Google风格的文档字符串

def verify_function(
    function_name: str,
    source_code: str,
    options: Optional[Dict[str, Any]] = None
) -> VerificationResult:
    """验证函数的内存安全性。

    Args:
        function_name: 要验证的函数名
        source_code: 包含函数的源代码
        options: 可选的验证选项

    Returns:
        VerificationResult: 验证结果对象

    Raises:
        ValueError: 如果函数名或源代码无效
        VerificationError: 如果验证过程失败
    """
    pass

注释规范

# 好的注释
def process_data(data: List[str]) -> Dict[str, int]:
    """处理输入数据并返回统计信息。

    这个函数会去除空行,统计每个单词的出现频率,
    并返回频率最高的前10个单词。
    """
    # 过滤空行和空白字符
    filtered_data = [line.strip() for line in data if line.strip()]

    # 统计词频
    word_counts = {}
    for line in filtered_data:
        for word in line.split():
            word_counts[word] = word_counts.get(word, 0) + 1

    return word_counts

# 避免的注释
def bad_example(data):
    # 这个函数处理数据
    result = []  # 初始化结果列表
    for item in data:  # 遍历数据
        result.append(item)  # 添加到结果
    return result  # 返回结果

测试规范

测试结构

tests/
├── unit/           # 单元测试
├── integration/    # 集成测试
├── performance/    # 性能测试
├── regression/     # 回归测试
└── fixtures/       # 测试固件

编写测试

单元测试示例

import pytest
from unittest.mock import Mock, patch
from src.processor import CodeProcessor

class TestCodeProcessor:
    """代码处理器测试"""

    @pytest.fixture
    def processor(self):
        """创建处理器实例"""
        return CodeProcessor({"max_length": 100})

    def test_process_simple_code(self, processor):
        """测试简单代码处理"""
        code = "int main() { return 0; }"
        result = processor.process_code(code)

        assert len(result) == 1
        assert result[0] == "int main() { return 0; }"

    def test_process_empty_code(self, processor):
        """测试空代码处理"""
        result = processor.process_code("")
        assert result == []

    @patch('src.processor.external_api')
    def test_process_with_external_dependency(self, mock_api, processor):
        """测试有外部依赖的代码处理"""
        mock_api.return_value = {"status": "success"}

        result = processor.process_with_api("test code")

        mock_api.assert_called_once()
        assert result["status"] == "success"

集成测试示例

import pytest
from src.main import CodeDetectApp

class TestCodeDetectIntegration:
    """CodeDetect集成测试"""

    @pytest.fixture
    def app(self):
        """创建应用实例"""
        return CodeDetectApp()

    def test_full_verification_pipeline(self, app):
        """测试完整验证管道"""
        test_code = """
        int add(int a, int b) {
            return a + b;
        }
        """

        result = app.verify_code(test_code)

        assert result["success"] is True
        assert "verification_result" in result
        assert result["verification_result"]["status"] == "SUCCESS"

测试覆盖率要求

  • 单元测试: 最低80%行覆盖率
  • 集成测试: 覆盖所有主要功能路径
  • 性能测试: 覆盖关键性能指标
  • 回归测试: 覆盖所有已修复的问题

运行测试

# 运行所有测试
python -m pytest

# 运行特定测试类型
python -m pytest tests/unit/
python -m pytest tests/integration/

# 运行覆盖率测试
python -m pytest --cov=src/ --cov-report=html

# 运行性能测试
python -m pytest tests/performance/ -m "not slow"

# 并行运行测试
python -m pytest -n auto

提交规范

提交消息格式

<类型>(<范围>): <描述>

[可选的详细描述]

[可选的脚注]

提交类型

  • feat: 新功能
  • fix: 修复bug
  • docs: 文档更新
  • style: 代码格式化
  • refactor: 代码重构
  • test: 测试相关
  • chore: 构建或工具变动

提交示例

# 好的提交
feat(verification): add support for array bounds checking
- Add array bounds checking functionality
- Update verification result format
- Add unit tests for new feature

fix(parser): fix null pointer dereference in code parsing
- Add null check before pointer access
- Fix issue #123
- Add regression test

docs(api): update API documentation
- Add new endpoint documentation
- Fix broken links
- Update examples

# 避免的提交
fix bug
update docs
minor changes

提交前检查

# 运行所有检查
./scripts/run-comprehensive-tests.sh

# 或者单独运行
python -m pytest
black --check src/ tests/
flake8 src/ tests/
mypy src/

Pull Request流程

PR流程

  1. Fork仓库
  2. 创建功能分支
  3. 编写代码和测试
  4. 确保所有测试通过
  5. 提交代码
  6. 创建Pull Request
  7. 响应审查意见
  8. 合并代码

分支命名

feature/your-feature-name
fix/your-fix-name
docs/your-docs-update

PR模板

## 变更描述

简要描述这个PR的目的和变更内容。

## 变更类型

- [ ] Bug修复
- [ ] 新功能
- [ ] 文档更新
- [ ] 重构
- [ ] 测试
- [ ] 其他: ___

## 相关Issue

Closes #123
Related to #456

## 测试

- [ ] 添加了单元测试
- [ ] 添加了集成测试
- [ ] 手动测试通过
- [ ] 所有现有测试通过

## 检查清单

- [ ] 代码遵循项目规范
- [ ] 文档已更新
- [ ] 测试覆盖率满足要求
- [ ] 无安全漏洞
- [ ] 性能影响已考虑

PR审查指南

审查者检查清单

  • 代码是否清晰易懂
  • 是否遵循项目规范
  • 测试是否充分
  • 文档是否更新
  • 是否有潜在的安全问题
  • 性能影响是否合理
  • 错误处理是否完善

审查评论示例

### 代码审查

**总体印象**: 代码质量很好,逻辑清晰。

**建议**:
1. 在第45行建议添加错误处理
```python
try:
    result = dangerous_operation()
except Exception as e:
    logger.error(f"Operation failed: {e}")
    return None
  1. 考虑将这个函数拆分成更小的函数以提高可读性

问题:

  • 为什么选择使用这种算法而不是其他替代方案?

表扬:

  • 测试覆盖很全面
  • 错误处理很好

## 问题报告

### 报告Bug

使用GitHub Issue模板报告bug

```markdown
## Bug描述

简要描述bug现象。

## 复现步骤

1. 执行操作A
2. 点击按钮B
3. 观察现象C

## 期望行为

描述期望的正确行为。

## 实际行为

描述实际观察到的行为。

## 环境信息

- 操作系统: Ubuntu 20.04
- Python版本: 3.9.0
- CodeDetect版本: v1.0.0
- CBMC版本: 5.10

## 其他信息

添加任何其他相关信息、截图、日志等。

功能请求

## 功能描述

描述你希望添加的功能。

## 使用场景

描述这个功能的使用场景和用户需求。

## 建议实现

如果你有实现建议,请描述。

## 替代方案

描述你考虑过的替代方案。

## 附加信息

添加任何其他相关信息。

发布流程

版本号规范

  • 主版本号: 不兼容的API变更
  • 次版本号: 向后兼容的功能新增
  • 修订号: 向后兼容的问题修复

发布检查清单

  • 所有测试通过
  • 文档已更新
  • 变更日志已更新
  • 版本号已更新
  • 安全检查通过
  • 性能测试通过

获取帮助

如果您在贡献过程中遇到问题:

  1. 查看 文档
  2. 搜索现有的 Issues
  3. Discussions 中提问
  4. 联系维护者

致谢

感谢所有为CodeDetect项目做出贡献的开发者

特别感谢:

  • 所有Issue报告者
  • 所有Pull Request贡献者
  • 所有文档改进者
  • 所有测试编写者

您的贡献使CodeDetect变得更好🎉