forked from NUDT-compiler/nudt-compiler-cpp
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
100 lines
3.3 KiB
100 lines
3.3 KiB
#!/usr/bin/env python3
|
|
import sys
|
|
|
|
def read_file(filepath):
|
|
"""读取文件内容,返回行列表"""
|
|
try:
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
return f.readlines()
|
|
except FileNotFoundError:
|
|
print(f"错误:文件 '{filepath}' 不存在")
|
|
sys.exit(1)
|
|
|
|
def get_context(line, pos, context_len=10):
|
|
"""获取字符上下文"""
|
|
start = max(0, pos - context_len)
|
|
end = min(len(line), pos + context_len + 1)
|
|
prefix = "..." if start > 0 else ""
|
|
suffix = "..." if end < len(line) else ""
|
|
return prefix + line[start:end] + suffix
|
|
|
|
def compare_files(file1, file2):
|
|
"""比较两个文件,输出详细差异"""
|
|
lines1 = read_file(file1)
|
|
lines2 = read_file(file2)
|
|
|
|
print(f"比较文件: {file1} vs {file2}")
|
|
print("=" * 80)
|
|
|
|
max_lines = max(len(lines1), len(lines2))
|
|
differences = 0
|
|
|
|
for line_num in range(max_lines):
|
|
line1 = lines1[line_num] if line_num < len(lines1) else None
|
|
line2 = lines2[line_num] if line_num < len(lines2) else None
|
|
|
|
if line1 is None:
|
|
print(f"\n[新增行] 第 {line_num + 1} 行")
|
|
print(f" + {repr(line2)}")
|
|
differences += 1
|
|
continue
|
|
|
|
if line2 is None:
|
|
print(f"\n[删除行] 第 {line_num + 1} 行")
|
|
print(f" - {repr(line1)}")
|
|
differences += 1
|
|
continue
|
|
|
|
if line1 == line2:
|
|
continue
|
|
|
|
# 行内容不同,逐字符比较
|
|
print(f"\n[差异行] 第 {line_num + 1} 行")
|
|
|
|
max_chars = max(len(line1), len(line2))
|
|
for char_pos in range(max_chars):
|
|
char1 = line1[char_pos] if char_pos < len(line1) else None
|
|
char2 = line2[char_pos] if char_pos < len(line2) else None
|
|
|
|
if char1 == char2:
|
|
continue
|
|
|
|
# 找到差异字符
|
|
context1 = get_context(line1, char_pos) if line1 else ""
|
|
context2 = get_context(line2, char_pos) if line2 else ""
|
|
|
|
print(f" 字符位置 {char_pos + 1}:")
|
|
if char1 is not None:
|
|
print(f" - {repr(char1)} | 上下文: {repr(context1)}")
|
|
else:
|
|
print(f" - (缺失)")
|
|
if char2 is not None:
|
|
print(f" + {repr(char2)} | 上下文: {repr(context2)}")
|
|
else:
|
|
print(f" + (缺失)")
|
|
differences += 1
|
|
|
|
# 跳过一些连续差异,避免输出过多
|
|
while char_pos + 1 < max_chars:
|
|
next_char1 = line1[char_pos + 1] if char_pos + 1 < len(line1) else None
|
|
next_char2 = line2[char_pos + 1] if char_pos + 1 < len(line2) else None
|
|
if next_char1 != next_char2:
|
|
char_pos += 1
|
|
else:
|
|
break
|
|
|
|
print("\n" + "=" * 80)
|
|
print(f"比较完成,共发现 {differences} 处差异")
|
|
|
|
def main():
|
|
if len(sys.argv) != 3:
|
|
print("用法: python diff.py <文件1> <文件2>")
|
|
sys.exit(1)
|
|
|
|
file1 = sys.argv[1]
|
|
file2 = sys.argv[2]
|
|
|
|
compare_files(file1, file2)
|
|
|
|
if __name__ == "__main__":
|
|
main() |