代码规范检查脚本?

wen 实用脚本 43

本文目录导读:

代码规范检查脚本?

  1. Python代码规范检查脚本
  2. Bash版本(更简单)
  3. 使用示例
  4. 配置文件

我来为您提供一个代码规范检查脚本,可以根据需要选择不同语言的版本。

Python代码规范检查脚本

#!/usr/bin/env python3
"""
代码规范检查脚本
支持Python、JavaScript、Java等语言的规范检查
"""
import os
import sys
import subprocess
import argparse
from pathlib import Path
class CodeLinter:
    """代码规范检查器"""
    def __init__(self, path, fix=False, verbose=False):
        self.path = path
        self.fix = fix
        self.verbose = verbose
        self.exit_code = 0
    def check_python(self, files):
        """检查Python代码规范"""
        print("\n🔍 检查Python代码规范...")
        # 安装必要的工具
        tools = ['flake8', 'pylint', 'black', 'isort']
        for tool in tools:
            try:
                __import__(tool.replace('-', '_'))
            except ImportError:
                subprocess.run([sys.executable, '-m', 'pip', 'install', tool], 
                             capture_output=True)
        results = []
        # 1. Flake8 检查
        if self.fix:
            print("  ⚡ 运行 Black 格式化...")
            subprocess.run(['python', '-m', 'black', self.path])
            print("  ⚡ 运行 isort 排序导入...")
            subprocess.run(['python', '-m', 'isort', self.path])
        # 2. Flake8 检查
        print("  📋 运行 flake8 检查...")
        result = subprocess.run(
            ['python', '-m', 'flake8', '--max-line-length=120', self.path],
            capture_output=True, text=True
        )
        if result.stdout:
            results.append(("Flake8", result.stdout))
            self.exit_code = 1
        # 3. Pylint 检查
        if self.verbose:
            print("  📋 运行 pylint 检查...")
            result = subprocess.run(
                ['python', '-m', 'pylint', '--max-line-length=120', self.path],
                capture_output=True, text=True
            )
            if result.stdout:
                results.append(("Pylint", result.stdout[:500]))
        return results
    def check_javascript(self, files):
        """检查JavaScript代码规范"""
        print("\n🔍 检查JavaScript代码规范...")
        results = []
        # 检查是否有ESLint
        try:
            subprocess.run(['eslint', '--version'], capture_output=True)
        except FileNotFoundError:
            print("  ⚠️  ESLint未安装,请执行: npm install -g eslint")
            return results
        print("  📋 运行 ESLint 检查...")
        result = subprocess.run(
            ['eslint', self.path, '--ext', '.js,.jsx,.ts,.tsx'],
            capture_output=True, text=True
        )
        if result.stdout:
            results.append(("ESLint", result.stdout))
            self.exit_code = 1
        return results
    def check_cpp(self, files):
        """检查C/C++代码规范"""
        print("\n🔍 检查C/C++代码规范...")
        results = []
        # 检查是否有cpplint
        try:
            subprocess.run(['cpplint', '--version'], capture_output=True)
        except FileNotFoundError:
            print("  ⚠️  cpplint未安装,请执行: pip install cpplint")
            return results
        print("  📋 运行 cpplint 检查...")
        result = subprocess.run(
            ['cpplint', '--linelength=100'] + files,
            capture_output=True, text=True
        )
        if result.stdout:
            results.append(("CPPLint", result.stdout))
            self.exit_code = 1
        return results
    def run_all_checks(self):
        """运行所有检查"""
        print(f"\n{'='*50}")
        print(f"📁 检查路径: {self.path}")
        print(f"{'='*50}")
        # 收集所有文件
        path = Path(self.path)
        all_files = []
        if path.is_file():
            all_files.extend([str(path)])
        else:
            for ext in ['*.py', '*.js', '*.jsx', '*.ts', '*.tsx', '*.cpp', '*.h', '*.hpp']:
                all_files.extend([str(f) for f in path.rglob(ext)])
        if not all_files:
            print("❌ 未找到需要检查的文件")
            return self.exit_code
        # 按类型分组
        py_files = [f for f in all_files if f.endswith('.py')]
        js_files = [f for f in all_files if f.endswith(('.js', '.jsx', '.ts', '.tsx'))]
        cpp_files = [f for f in all_files if f.endswith(('.cpp', '.h', '.hpp'))]
        print(f"\n📊 文件统计:")
        print(f"  Python文件: {len(py_files)}个")
        print(f"  JavaScript文件: {len(js_files)}个")
        print(f"  C/C++文件: {len(cpp_files)}个")
        # 执行检查
        all_results = []
        if py_files:
            all_results.extend(self.check_python(py_files))
        if js_files:
            all_results.extend(self.check_javascript(js_files))
        if cpp_files:
            all_results.extend(self.check_cpp(cpp_files))
        # 输出结果
        if all_results:
            print(f"\n{'='*50}")
            print("❌ 发现以下问题:")
            print(f"{'='*50}")
            for tool, output in all_results:
                print(f"\n🔴 {tool} 报告:")
                print(output)
        else:
            print(f"\n✅ 代码规范检查通过!")
        return self.exit_code
def check_git_hooks():
    """检查Git hooks配置"""
    print("\n📋 检查Git hooks...")
    git_dir = Path('.git')
    if not git_dir.exists():
        print("  ⚠️  不是Git仓库")
        return
    hooks_dir = git_dir / 'hooks'
    pre_commit = hooks_dir / 'pre-commit'
    if pre_commit.exists():
        print("  ✅ pre-commit hook 已安装")
    else:
        print("  ❌ pre-commit hook 未安装")
def main():
    parser = argparse.ArgumentParser(description='代码规范检查工具')
    parser.add_argument('path', nargs='?', default='.',
                       help='要检查的文件或目录路径 (默认: 当前目录)')
    parser.add_argument('--fix', action='store_true',
                       help='自动修复可修复的问题')
    parser.add_argument('--verbose', '-v', action='store_true',
                       help='显示详细信息')
    parser.add_argument('--git-hooks', action='store_true',
                       help='检查Git hooks配置')
    args = parser.parse_args()
    if args.git_hooks:
        check_git_hooks()
        return
    linter = CodeLinter(args.path, args.fix, args.verbose)
    exit_code = linter.run_all_checks()
    sys.exit(exit_code)
if __name__ == '__main__':
    main()

Bash版本(更简单)

#!/bin/bash
# 代码规范检查脚本
# 使用方法: ./lint.sh [目录路径]
set -e
TARGET_DIR="${1:-.}"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo -e "${YELLOW}========================================${NC}"
echo -e "${YELLOW}  代码规范检查工具${NC}"
echo -e "${YELLOW}========================================${NC}"
echo -e "检查目录: ${TARGET_DIR}"
# 检查Python代码
check_python() {
    echo -e "\n${YELLOW}检查Python代码...${NC}"
    # 安装依赖
    pip install flake8 black isort -q 2>/dev/null
    # 运行flake8
    echo -e "${GREEN}运行 flake8...${NC}"
    flake8 "$TARGET_DIR" --max-line-length=120
    # 运行black检查
    echo -e "${GREEN}检查代码格式 (black)...${NC}"
    black --check "$TARGET_DIR" 2>/dev/null || {
        echo -e "${YELLOW}建议运行: black $TARGET_DIR${NC}"
    }
    echo -e "${GREEN}✓ Python检查完成${NC}"
}
# 检查JavaScript代码
check_javascript() {
    echo -e "\n${YELLOW}检查JavaScript代码...${NC}"
    # 检查是否有ESLint
    if command -v eslint &> /dev/null; then
        echo -e "${GREEN}运行 ESLint...${NC}"
        eslint "$TARGET_DIR" --ext .js,.jsx,.ts,.tsx
    else
        echo -e "${RED}ESLint 未安装,跳过JavaScript检查${NC}"
        echo -e "${YELLOW}安装: npm install -g eslint${NC}"
    fi
    echo -e "${GREEN}✓ JavaScript检查完成${NC}"
}
# 检查C/C++代码
check_cpp() {
    echo -e "\n${YELLOW}检查C/C++代码...${NC}"
    # 使用cppcheck
    if command -v cppcheck &> /dev/null; then
        echo -e "${GREEN}运行 cppcheck...${NC}"
        cppcheck --enable=all --suppress=missingIncludeSystem "$TARGET_DIR"
    else
        echo -e "${RED}cppcheck 未安装,跳过C/C++检查${NC}"
        echo -e "${YELLOW}安装: brew install cppcheck 或 apt install cppcheck${NC}"
    fi
}
# 检查提交信息规范
check_commit_message() {
    echo -e "\n${YELLOW}检查提交信息规范...${NC}"
    # 使用commitlint
    if command -v commitlint &> /dev/null; then
        echo -e "${GREEN}运行 commitlint...${NC}"
        # 检查最近一次提交信息
        commitlint --from HEAD~1 --to HEAD 2>/dev/null || true
    fi
    echo -e "${GREEN}✓ 提交信息检查完成${NC}"
}
# 检查文件命名规范
check_file_naming() {
    local issues=0
    echo -e "\n${YELLOW}检查文件命名规范...${NC}"
    # 检查不规范的命名
    while IFS= read -r file; do
        # 检查空格
        if [[ "$file" =~ " " ]]; then
            echo -e "${RED}⚠ 文件名包含空格: $file${NC}"
            ((issues++))
        fi
        # 检查大写字母(除了特定文件)
        if [[ "$file" =~ [A-Z] && ! "$file" =~ ^\.git && ! "$file" =~ Dockerfile ]]; then
            # 允许特定的大写文件名
            case "$file" in
                *Makefile*|*Dockerfile*|*README*|*LICENSE*|*CHANGELOG*)
                    ;;
                *)
                    echo -e "${YELLOW}⚠ 文件名包含大写字母: $file${NC}"
                    ((issues++))
                    ;;
            esac
        fi
    done < <(find "$TARGET_DIR" -type f -not -path '*/\.*' 2>/dev/null)
    if [ $issues -eq 0 ]; then
        echo -e "${GREEN}✓ 文件命名规范${NC}"
    else
        echo -e "${YELLOW}发现 $issues 个文件命名问题${NC}"
    fi
}
# 主函数
main() {
    # 检查目录是否存在
    if [ ! -d "$TARGET_DIR" ] && [ ! -f "$TARGET_DIR" ]; then
        echo -e "${RED}错误: 路径不存在: $TARGET_DIR${NC}"
        exit 1
    fi
    # 检查是否有代码文件
    local file_count=$(find "$TARGET_DIR" -type f \( -name "*.py" -o -name "*.js" -o -name "*.cpp" \) 2>/dev/null | wc -l)
    if [ "$file_count" -eq 0 ]; then
        echo -e "${RED}未找到需要检查的代码文件${NC}"
        exit 0
    fi
    echo -e "发现 ${file_count} 个代码文件\n"
    # 执行检查
    check_file_naming
    check_python
    check_javascript
    check_cpp
    check_commit_message
    echo -e "\n${GREEN}========================================${NC}"
    echo -e "${GREEN}  代码规范检查完成!${NC}"
    echo -e "${GREEN}========================================${NC}"
}
# 运行主函数
main

使用示例

# Python脚本使用
python lint.py                                    # 检查当前目录
python lint.py /path/to/project                    # 检查指定目录
python lint.py --fix                               # 自动修复问题
python lint.py --verbose                           # 显示详细信息
# Bash脚本使用
chmod +x lint.sh                                   # 添加执行权限
./lint.sh                                          # 检查当前目录
./lint.sh src/                                     # 检查src目录

配置文件

创建 .flake8 配置文件:

[flake8]
max-line-length = 120
exclude = .git,__pycache__,venv,node_modules,migrations
ignore = E203, W503

创建 .pylintrc 配置文件:

[MASTER]
ignore = .git,__pycache__,venv,node_modules
max-line-length=120
[MESSAGES CONTROL]
disable = C0111, C0103, W0612

这个脚本支持多种语言的代码规范检查,可以根据需要启用或禁用特定语言的检查。

抱歉,评论功能暂时关闭!