怎样实现代码格式化脚本

wen 实用脚本 29

本文目录导读:

怎样实现代码格式化脚本

  1. 使用现有工具的组合脚本
  2. 通用多语言格式化脚本
  3. Node.js 脚本 + 配置文件
  4. Makefile 自动化
  5. Git Hooks (pre-commit)
  6. 使用示例
  7. 配置文件示例

使用现有工具的组合脚本

前端项目 (JavaScript/TypeScript)

#!/bin/bash
# format.sh - 前端代码格式化脚本
# 安装依赖先
echo "📦 检查依赖..."
npm install prettier eslint --save-dev 2>/dev/null
echo "🎨 开始格式化代码..."
# 使用 Prettier 格式化
npx prettier --write "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}"
# 使用 ESLint 修复
npx eslint "src/**/*.{js,jsx,ts,tsx}" --fix
echo "✅ 格式化完成!"

Python 项目

#!/usr/bin/env python3
# format.py - Python代码格式化脚本
import subprocess
import sys
import os
def format_python():
    print("🎨 格式化Python代码...")
    # 使用 black 格式化
    subprocess.run(["black", "."], check=False)
    # 使用 isort 排序导入
    subprocess.run(["isort", "."], check=False)
    # 使用 ruff 检查和修复
    subprocess.run(["ruff", "check", "--fix", "."], check=False)
    print("✅ 格式化完成!")
if __name__ == "__main__":
    if not all(
        os.system(f"which {tool} > /dev/null 2>&1") == 0 
        for tool in ["black", "isort", "ruff"]
    ):
        print("请安装: pip install black isort ruff")
        sys.exit(1)
    format_python()

通用多语言格式化脚本

#!/bin/bash
# format_all.sh - 多语言代码格式化脚本
set -e
echo "🚀 开始代码格式化"
# 根据文件类型选择格式化工具
format_file() {
    local file="$1"
    case "$file" in
        *.py)
            black "$file"
            isort "$file"
            ;;
        *.js|*.jsx|*.ts|*.tsx)
            npx prettier --write "$file"
            npx eslint --fix "$file" 2>/dev/null || true
            ;;
        *.java)
            # 需要安装 google-java-format
            google-java-format -i "$file"
            ;;
        *.go)
            gofmt -w "$file"
            ;;
        *.rs)
            rustfmt "$file"
            ;;
        *.c|*.cpp|*.h|*.hpp)
            clang-format -i "$file"
            ;;
        *.rb)
            rubocop -a "$file" 2>/dev/null || true
            ;;
        *.swift)
            swift format -i "$file"
            ;;
        *)
            echo "⚠️  不支持的文件类型: $file"
            return 1
            ;;
    esac
}
# 递归格式化目录
format_directory() {
    local dir="$1"
    find "$dir" -type f \( \
        -name "*.py" -o \
        -name "*.js" -o \
        -name "*.ts" -o \
        -name "*.java" -o \
        -name "*.go" -o \
        -name "*.rs" -o \
        -name "*.c" -o \
        -name "*.cpp" -o \
        -name "*.rb" \
    \) | while read file; do
        echo "📝 格式化: $file"
        format_file "$file"
    done
}
# 主逻辑
if [ $# -eq 0 ]; then
    echo "用法: $0 <文件或目录>"
    exit 1
fi
for target in "$@"; do
    if [ -d "$target" ]; then
        format_directory "$target"
    elif [ -f "$target" ]; then
        format_file "$target"
    else
        echo "❌ 路径不存在: $target"
    fi
done
echo "✅ 所有文件格式化完成!"

Node.js 脚本 + 配置文件

安装配置

// package.json
{
  "scripts": {
    "format": "node format.js",
    "format:check": "prettier --check .",
    "format:fix": "npm run format"
  },
  "devDependencies": {
    "prettier": "^3.0.0",
    "eslint": "^8.0.0",
    "@typescript-eslint/parser": "^6.0.0",
    "@typescript-eslint/eslint-plugin": "^6.0.0"
  }
}

主脚本

// format.js
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
class CodeFormatter {
    constructor() {
        this.extensions = {
            'js': ['prettier', 'eslint'],
            'ts': ['prettier', 'eslint'],
            'jsx': ['prettier', 'eslint'],
            'tsx': ['prettier', 'eslint'],
            'json': ['prettier'],
            'css': ['prettier'],
            'scss': ['prettier'],
            'md': ['prettier'],
            'yml': ['prettier'],
            'yaml': ['prettier'],
        };
    }
    async format() {
        console.log('🚀 开始格式化...');
        try {
            // 1. Prettier 格式化
            console.log('📝 使用 Prettier...');
            execSync('npx prettier --write "**/*.{js,ts,jsx,tsx,json,css,scss,md}"', {
                stdio: 'inherit'
            });
            // 2. ESLint 修复
            console.log('🔧 使用 ESLint...');
            execSync('npx eslint "src/**/*.{js,ts,jsx,tsx}" --fix', {
                stdio: 'inherit'
            });
            console.log('✅ 格式化完成!');
        } catch (error) {
            console.error('❌ 格式化失败:', error.message);
            process.exit(1);
        }
    }
}
// 运行
const formatter = new CodeFormatter();
formatter.format();

Makefile 自动化

# Makefile - 代码格式化
.PHONY: format format-check setup
# 安装工具
setup:
    npm install prettier eslint --save-dev
    pip install black isort ruff
# 格式化所有代码
format:
    @echo "🎨 格式化代码..."
    @npm run format 2>/dev/null || true
    @black . 2>/dev/null || true
    @isort . 2>/dev/null || true
    @echo "✅ 格式化完成"
# 检查格式化
format-check:
    @echo "🔍 检查代码格式..."
    @prettier --check "**/*.{js,ts,jsx,tsx,json,css,scss,md}" || exit 1
    @eslint "src/**/*.{js,ts,jsx,tsx}" || exit 1
    @black --check . || exit 1
    @isort --check . || exit 1
    @echo "✅ 格式检查通过"
# Git hooks 自动格式化
install-hooks:
    @echo "🔗 安装 Git hooks..."
    @cp scripts/pre-commit .git/hooks/
    @chmod +x .git/hooks/pre-commit
    @echo "✅ Git hooks 安装完成"

Git Hooks (pre-commit)

#!/bin/bash
# .git/hooks/pre-commit - Git提交前自动格式化
echo "🔍 检查代码格式..."
# 获取暂存的文件
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|ts|tsx|jsx|py)$')
if [ -z "$STAGED_FILES" ]; then
    echo "✅ 没有需要格式化的文件"
    exit 0
fi
echo "📝 格式化文件:"
echo "$STAGED_FILES"
# 格式化暂存的文件
for FILE in $STAGED_FILES; do
    case "$FILE" in
        *.py)
            black "$FILE"
            isort "$FILE"
            git add "$FILE"
            ;;
        *.js|*.ts|*.tsx|*.jsx)
            npx prettier --write "$FILE"
            npx eslint --fix "$FILE" 2>/dev/null || true
            git add "$FILE"
            ;;
    esac
done
echo "✅ 格式化完成"

使用示例

# 1. 格式化单个文件
./format.sh src/index.js
# 2. 格式化整个项目
./format_all.sh ./src
# 3. 使用 Makefile
make format
make format-check
# 4. 使用 Node.js 脚本
node format.js
# 5. 安装 Git hooks
make install-hooks

配置文件示例

Prettier 配置 (.prettierrc)

{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 4,
  "endOfLine": "lf"
}

ESLint 配置 (.eslintrc.js)

module.exports = {
    extends: ['eslint:recommended'],
    parserOptions: {
        ecmaVersion: 2020,
        sourceType: 'module'
    },
    rules: {
        'indent': ['error', 4],
        'quotes': ['error', 'single'],
        'semi': ['error', 'always']
    }
};

这套方案可以根据你的项目需求灵活选择或组合使用。

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