#!/usr/bin/env python # -*- coding: utf-8 -*- """ 转换项目中的所有文件编码为UTF-8无BOM格式(Linux兼容) """ import os import codecs def convert_file_to_utf8_no_bom(file_path): """将单个文件转换为UTF-8无BOM格式""" try: # 尝试自动检测文件编码并读取内容 with open(file_path, 'rb') as f: content = f.read() # 尝试几种常见的编码格式 encodings = ['utf-8', 'utf-8-sig', 'gbk', 'gb2312', 'latin-1'] text = None for encoding in encodings: try: text = content.decode(encoding) break except UnicodeDecodeError: continue if text is None: # 如果无法解码,使用二进制模式复制 print(f"警告: 无法解码文件 {file_path},使用二进制模式复制") with open(file_path + '.tmp', 'wb') as f: f.write(content) os.replace(file_path + '.tmp', file_path) return False # 以UTF-8无BOM格式写入文件 with open(file_path + '.tmp', 'w', encoding='utf-8') as f: f.write(text) # 替换原文件 os.replace(file_path + '.tmp', file_path) print(f"已转换: {file_path}") return True except Exception as e: print(f"错误: 转换文件 {file_path} 失败 - {str(e)}") return False def main(): """主函数""" # 设置项目根目录 project_root = os.path.dirname(os.path.abspath(__file__)) # 定义需要转换的文件列表 files_to_convert = [ # 根目录下的文件 '.gitignore', 'CMakeLists.txt', 'README.md', 'build.sh', 'build_windows.bat', 'test_cmake_config.cmd', 'test_compile.cmd', # include目录下的文件 os.path.join('include', 'rpc_common.h'), os.path.join('include', 'rpc_message.h'), os.path.join('include', 'rpc_transport.h'), # src目录下的文件 os.path.join('src', 'CMakeLists.txt'), os.path.join('src', 'rpc_client.c'), os.path.join('src', 'rpc_common.c'), os.path.join('src', 'rpc_message.c'), os.path.join('src', 'rpc_server.c'), os.path.join('src', 'rpc_transport.c') ] print(f"开始转换项目文件编码为UTF-8无BOM格式(Linux兼容)...") print(f"项目根目录: {project_root}") print("=" * 60) # 转换每个文件 success_count = 0 error_count = 0 for file_rel_path in files_to_convert: file_abs_path = os.path.join(project_root, file_rel_path) if os.path.exists(file_abs_path): if convert_file_to_utf8_no_bom(file_abs_path): success_count += 1 else: error_count += 1 else: print(f"警告: 文件不存在 - {file_abs_path}") error_count += 1 print("=" * 60) print(f"转换完成!成功: {success_count}, 失败: {error_count}") print("所有文件已转换为UTF-8无BOM格式,可以在Linux环境下正常使用。") # 让窗口保持打开状态 input("按Enter键退出...") if __name__ == "__main__": main()