批量添加文件尾注的脚本

wen 实用脚本 2

本文目录导读:

批量添加文件尾注的脚本

  1. Python 脚本版本
  2. 简化 Bash 脚本版本
  3. 使用示例
  4. 批量处理配置文件
  5. 功能特点
  6. 注意事项

我来帮你创建一个批量添加文件尾注的脚本,这个脚本支持多种文件格式,并提供了灵活的配置选项。

Python 脚本版本

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量文件尾注添加工具
支持文本文件、代码文件、配置文件等
"""
import os
import argparse
from pathlib import Path
from datetime import datetime
from typing import List, Optional
class BatchFooter:
    def __init__(self, 
                 footer_text: str,
                 file_extensions: List[str],
                 recursive: bool = True,
                 dry_run: bool = False,
                 backup: bool = True):
        """
        初始化尾部注释添加器
        Args:
            footer_text: 要添加的尾部注释文本
            file_extensions: 文件扩展名列表
            recursive: 是否递归搜索子目录
            dry_run: 是否模拟运行(不实际修改文件)
            backup: 是否创建备份
        """
        self.footer_text = footer_text
        self.file_extensions = file_extensions
        self.recursive = recursive
        self.dry_run = dry_run
        self.backup = backup
        self.processed_files = 0
        self.skipped_files = 0
        # 根据文件类型定义注释符号
        self.comment_styles = {
            # Python, YAML, Ruby, Shell
            '.py': '#', '.yml': '#', '.yaml': '#', '.rb': '#', '.sh': '#',
            # JavaScript, TypeScript, Java, C++, C, C#
            '.js': '//', '.jsx': '//', '.ts': '//', '.tsx': '//',
            '.java': '//', '.cpp': '//', '.hpp': '//', '.c': '//', '.h': '//', '.cs': '//',
            # HTML, XML
            '.html': '<!-- -->', '.htm': '<!-- -->', '.xml': '<!-- -->', '.vue': '<!-- -->',
            # Markdown
            '.md': '> ', '.markdown': '> ',
            # Text
            '.txt': '#', '.log': '#', '.ini': ';', '.cfg': '#', '.conf': '#',
            # SQL
            '.sql': '--',
            # CSS
            '.css': '/* */', '.scss': '/* */', '.less': '/* */',
            # PHP
            '.php': '//',
            # Swift, Kotlin
            '.swift': '//', '.kt': '//', '.kts': '//',
        }
    def get_comment_style(self, filepath: Path) -> Optional[tuple]:
        """根据文件扩展名获取注释风格"""
        ext = filepath.suffix.lower()
        if ext in self.comment_styles:
            style = self.comment_styles[ext]
            if style == '<!-- -->':
                return ('<!--', '-->')
            elif style == '/* */':
                return ('/*', '*/')
            else:
                return (style, None)  # 单行注释
        return None
    def generate_footer(self, comment_start: str, comment_end: Optional[str], filepath: Path) -> str:
        """生成尾部注释内容"""
        lines = []
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        filename = filepath.name
        # 添加时间戳和文件名
        header = f"Footer added: {timestamp}"
        footer_lines = self.footer_text.split('\n')
        if comment_end:  # 多行注释
            lines.append(comment_start)
            lines.append(f" * {header}")
            for line in footer_lines:
                lines.append(f" * {line}")
            lines.append(comment_end)
        else:  # 单行注释
            for line in [header] + footer_lines:
                lines.append(f"{comment_start} {line}")
        return '\n'.join(lines)
    def process_file(self, filepath: Path) -> bool:
        """处理单个文件"""
        try:
            # 获取注释风格
            comment_style = self.get_comment_style(filepath)
            if not comment_style:
                self.skipped_files += 1
                print(f"  跳过 {filepath} (不支持的格式)")
                return False
            # 读取文件内容
            with open(filepath, 'r', encoding='utf-8') as f:
                content = f.read()
            # 检查是否已有尾注
            if 'Footer added:' in content:
                self.skipped_files += 1
                print(f"  跳过 {filepath} (已存在尾注)")
                return False
            # 生成尾注
            footer = self.generate_footer(comment_style[0], comment_style[1], filepath)
            # 确保文件以换行结束
            if not content.endswith('\n'):
                content += '\n'
            # 添加尾注
            new_content = content + footer + '\n'
            if not self.dry_run:
                # 备份原文件
                if self.backup:
                    backup_path = filepath.with_suffix(filepath.suffix + '.bak')
                    with open(backup_path, 'w', encoding='utf-8') as f:
                        f.write(content)
                # 写入新内容
                with open(filepath, 'w', encoding='utf-8') as f:
                    f.write(new_content)
            self.processed_files += 1
            print(f"  已处理: {filepath}")
            if self.dry_run:
                print(f"    [模拟] 将添加以下内容:")
                print(f"    {footer}")
            return True
        except Exception as e:
            print(f"  错误处理 {filepath}: {str(e)}")
            return False
    def process_directory(self, directory: Path):
        """处理目录中的所有文件"""
        pattern = None
        if self.recursive:
            pattern = '**/*'
        else:
            pattern = '*'
        for filepath in directory.glob(pattern):
            if filepath.is_file():
                if filepath.suffix.lower() in self.file_extensions:
                    self.process_file(filepath)
    def run(self, paths: List[str]):
        """运行批量处理"""
        print(f"开始批量处理... (模拟模式: {self.dry_run})")
        print(f"目标文件类型: {', '.join(self.file_extensions)}")
        print("-" * 50)
        for path in paths:
            p = Path(path)
            if p.is_file():
                self.process_file(p)
            elif p.is_dir():
                print(f"\n处理目录: {p}")
                self.process_directory(p)
            else:
                print(f"路径不存在: {path}")
        print("-" * 50)
        print(f"处理完成! 成功: {self.processed_files} 个文件, 跳过: {self.skipped_files} 个文件")
        if self.dry_run:
            print("注意: 这是模拟运行,未实际修改任何文件")
def main():
    parser = argparse.ArgumentParser(description='批量添加文件尾注工具')
    parser.add_argument('paths', nargs='+', help='要处理的文件或目录路径')
    parser.add_argument('--text', '-t', required=True, help='要添加的尾注内容')
    parser.add_argument('--ext', '-e', nargs='+', default=['.py', '.js', '.txt', '.md'], 
                       help='要处理的文件扩展名 (默认: .py .js .txt .md)')
    parser.add_argument('--no-recursive', action='store_true', help='不递归处理子目录')
    parser.add_argument('--dry-run', action='store_true', help='模拟运行,不实际修改文件')
    parser.add_argument('--no-backup', action='store_true', help='不创建备份文件')
    args = parser.parse_args()
    footer = BatchFooter(
        footer_text=args.text,
        file_extensions=args.ext,
        recursive=not args.no_recursive,
        dry_run=args.dry_run,
        backup=not args.no_backup
    )
    footer.run(args.paths)
if __name__ == "__main__":
    main()

简化 Bash 脚本版本

#!/bin/bash
# 批量添加文件尾注脚本
# 配置
FOOTER_TEXT="This file was modified on $(date '+%Y-%m-%d %H:%M:%S')"
TARGET_DIR="${1:-.}"  # 默认当前目录
FILE_TYPES=("*.txt" "*.md" "*.py" "*.js")  # 要处理的文件类型
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${YELLOW}开始批量添加尾注...${NC}"
# 计数器
count=0
skip_count=0
find "$TARGET_DIR" -type f \( -name "*.txt" -o -name "*.md" -o -name "*.py" -o -name "*.js" \) | while read file; do
    # 检查文件是否已有尾注
    if grep -q "Footer added:" "$file" 2>/dev/null; then
        echo -e "${YELLOW}跳过 $file (已包含尾注)${NC}"
        skip_count=$((skip_count + 1))
        continue
    fi
    # 添加尾注
    {
        echo ""
        echo "# 文件尾注"
        echo "# $FOOTER_TEXT"
        echo "# Processing script: $(basename "$0")"
    } >> "$file"
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}已处理: $file${NC}"
        count=$((count + 1))
    else
        echo -e "${RED}处理失败: $file${NC}"
    fi
done
echo -e "${GREEN}处理完成! 成功: $count 个文件, 跳过: $skip_count 个文件${NC}"

使用示例

# Python 版本用法
# 1. 添加简单的尾注
python batch_footer.py /path/to/directory --text "Created by John Doe"
# 2. 指定文件类型
python batch_footer.py . -e .txt .md .py --text "Internal project - Confidential"
# 3. 模拟运行(不实际修改)
python batch_footer.py /my/projects -t "Check fail" --dry-run
# 4. 不递归处理子目录
python batch_footer.py . -t "Copyright 2024" --no-recursive
# 5. 多行尾注
python batch_footer.py . -t "Line 1\nLine 2\nLine 3"
# Bash 版本用法
./add_footer.sh /path/to/directory

批量处理配置文件

# config_batch_footer.py
# 配置文件模板
CONFIG_EXAMPLE = {
    "footer_templates": {
        "个人信息": "作者: {author}\n日期: {date}\n项目: {project}",
        "版权信息": "Copyright (c) {year} {company}. All rights reserved.",
        "公司标准": "Confidential - For internal use only\nProperty of {company}"
    }
}
# 使用示例
python batch_footer.py . \
    -t "作者: John\n日期: 2024\n项目: Internal" \
    -e .py .js .cpp \
    --dry-run

功能特点

  1. 多格式支持:支持常见的文件格式和注释风格
  2. 安全机制
    • 备份原文件(可关闭)
    • 检查重复添加
    • 模拟模式预览
  3. 灵活配置
    • 自定义文件类型
    • 递归/非递归目录
    • 多路径处理
  4. 错误处理:格式错误、权限问题等都有明确提示

注意事项

  • 建议先用 --dry-run 测试
  • 重要文件前建议手动备份
  • 检查生成的尾注格式是否符合需求
  • 确保有足够的文件读写权限

这个脚本可以灵活配置,适应不同场景的需求,如有特殊需求,可以修改注释风格或添加更多选项。

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