-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix_encoding.py
More file actions
225 lines (186 loc) · 8.83 KB
/
fix_encoding.py
File metadata and controls
225 lines (186 loc) · 8.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Скрипт для исправления кодировки и синтаксических ошибок файлов проекта MHook2
Все файлы .cpp и .h должны быть в UTF-8 with BOM (Codepage 65001)
"""
import os
import sys
import argparse
import re
from pathlib import Path
def fix_syntax_errors(content, filepath):
"""
Исправляет типичные синтаксические ошибки C++
"""
fixes_applied = []
# Исправление: class ClassName:public BaseClass -> class ClassName : public BaseClass
# Добавляем пробел перед двоеточием наследования
pattern_class = re.compile(r'(class\s+\w+):public')
if pattern_class.search(content):
content = pattern_class.sub(r'\1 : public', content)
fixes_applied.append('Добавлен пробел перед :public')
# Исправление: class ClassName:private -> class ClassName : private
pattern_class_private = re.compile(r'(class\s+\w+):private')
if pattern_class_private.search(content):
content = pattern_class_private.sub(r'\1 : private', content)
fixes_applied.append('Добавлен пробел перед :private')
# Исправление: class ClassName:protected -> class ClassName : protected
pattern_class_protected = re.compile(r'(class\s+\w+):protected')
if pattern_class_protected.search(content):
content = pattern_class_protected.sub(r'\1 : protected', content)
fixes_applied.append('Добавлен пробел перед :protected')
return content, fixes_applied
def fix_line_endings(content, filepath):
"""
Приводит все окончания строк к CRLF (стандарт Windows/Visual Studio)
Удаляет ВСЕ пустые строки
"""
# Skip resource.h - it needs empty lines
filepath_str = str(filepath)
if 'resource.h' in filepath_str:
return content, True
# First normalize to \n
content = content.replace('\r\n', '\n').replace('\r', '\n')
lines = content.split('\n')
# Remove all empty lines
result = [line.rstrip() for line in lines if line.strip()]
normalized = '\r\n'.join(result)
return normalized, True
def fix_file_encoding(filepath):
"""
Исправляет кодировку файла на UTF-8 with BOM и синтаксические ошибки
"""
try:
# Читаем файл в бинарном режиме
with open(filepath, 'rb') as f:
raw_content = f.read()
# Проверяем BOM
has_utf8_bom = raw_content.startswith(b'\xef\xbb\xbf')
has_utf16_le_bom = raw_content.startswith(b'\xff\xfe')
has_utf16_be_bom = raw_content.startswith(b'\xfe\xff')
# Если уже UTF-8 with BOM - пропускаем
if has_utf8_bom:
# Читаем в binary режиме чтобы не конвертировать окончания строк
content = raw_content[3:].decode('utf-8', errors='replace')
# Проверяем и исправляем синтаксис
content, syntax_fixes = fix_syntax_errors(content, filepath)
# Приводим окончания строк к CRLF (стандарт Windows/Visual Studio)
content, line_ending_fixed = fix_line_endings(content, filepath)
if line_ending_fixed:
print(f"[LINEEND] {filepath} - окончания строк приведены к CRLF")
# Записываем с UTF-8 with BOM (используем binary mode для правильного BOM)
with open(filepath, 'wb') as f:
# Пишем BOM bytes
f.write(b'\xef\xbb\xbf')
# Пишем контент как UTF-8
f.write(content.encode('utf-8'))
return True
# Определяем текущую кодировку и декодируем
content = None
if has_utf16_le_bom:
# UTF-16 LE with BOM
try:
content = raw_content.decode('utf-16-le')
print(f"[CONV] {filepath} - конвертация UTF-16 LE -> UTF-8 with BOM")
except:
pass
elif has_utf16_be_bom:
# UTF-16 BE with BOM
try:
content = raw_content.decode('utf-16-be')
print(f"[CONV] {filepath} - конвертация UTF-16 BE -> UTF-8 with BOM")
except:
pass
else:
# Пробуем разные кодировки
encodings = ['utf-8', 'windows-1251', 'cp1251', 'latin-1', 'iso-8859-1']
for encoding in encodings:
try:
content = raw_content.decode(encoding)
if encoding != 'utf-8':
print(f"[CONV] {filepath} - конвертация {encoding} -> UTF-8 with BOM")
else:
print(f"[CONV] {filepath} - добавление BOM к UTF-8")
break
except:
continue
if content is None:
print(f"[ERROR] {filepath} - не удалось определить кодировку")
return False
# Исправляем синтаксические ошибки
content, syntax_fixes = fix_syntax_errors(content, filepath)
# Приводим окончания строк к CRLF (стандарт Windows/Visual Studio)
content, line_ending_fixed = fix_line_endings(content, filepath)
if line_ending_fixed:
print(f"[LINEEND] {filepath} - окончания строк приведены к CRLF")
# Записываем с UTF-8 with BOM (используем binary mode для правильного BOM)
with open(filepath, 'wb') as f:
# Пишем BOM bytes
f.write(b'\xef\xbb\xbf')
# Пишем контент как UTF-8
f.write(content.encode('utf-8'))
if syntax_fixes:
print(f"[SYNTAX] {filepath}: {', '.join(syntax_fixes)}")
print(f"[FIXED] {filepath} - исправлено")
return True
except Exception as e:
print(f"[ERROR] {filepath} - ошибка: {e}")
return False
def process_directory(directory, extensions=None):
"""
Обрабатывает все файлы в директории с указанными расширениями
"""
if extensions is None:
extensions = ['.cpp', '.h', '.hpp']
directory = Path(directory)
fixed_count = 0
error_count = 0
syntax_count = 0
print(f"\n[SCAN] Поиск файлов в: {directory}")
print(f"[EXT] Расширения: {', '.join(extensions)}\n")
for ext in extensions:
for filepath in directory.rglob(f'*{ext}'):
# Пропускаем временные файлы и x64
if any(skip in str(filepath) for skip in ['temp', 'x64', 'Debug', 'Release']):
continue
if fix_file_encoding(filepath):
fixed_count += 1
else:
error_count += 1
print(f"\n[STATS] Статистика:")
print(f" [FIXED] Исправлено: {fixed_count}")
print(f" [ERROR] Ошибок: {error_count}")
return error_count == 0
def main():
parser = argparse.ArgumentParser(
description='Исправление кодировки и синтаксических ошибок файлов MHook2'
)
parser.add_argument(
'path',
nargs='?',
default='.',
help='Путь к директории или файлу (по умолчанию: текущая директория)'
)
parser.add_argument(
'--extensions',
'-e',
nargs='+',
default=['.cpp', '.h', '.hpp'],
help='Расширения файлов для обработки (по умолчанию: .cpp .h .hpp)'
)
args = parser.parse_args()
path = Path(args.path)
if not path.exists():
print(f"[ERROR] Ошибка: путь не существует: {path}")
sys.exit(1)
if path.is_file():
# Обрабатываем один файл
success = fix_file_encoding(path)
sys.exit(0 if success else 1)
else:
# Обрабатываем директорию
success = process_directory(path, args.extensions)
sys.exit(0 if success else 1)
if __name__ == '__main__':
main()