Ai
1 Star 0 Fork 0

王英伟/kernel

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
apply_patch.py 1.76 KB
一键复制 编辑 原始数据 按行查看 历史
王英伟 提交于 2024-09-29 09:31 +08:00 . first commit
import os
import re
from pathlib import Path
def apply_patch(patch_file, target_folder):
with open(patch_file, 'r') as f:
patch_content = f.read()
# Split the patch into individual file diffs
file_diffs = re.split(r'diff --git ', patch_content)[1:]
for diff in file_diffs:
# Extract the file path
file_path = diff.split('\n')[0].split()[-1][2:]
target_file = Path(target_folder) / file_path
if not target_file.exists():
print(f"Warning: Target file {target_file} does not exist. Skipping.")
continue
# Read the original file content
with open(target_file, 'r') as f:
original_content = f.readlines()
# Parse the diff hunks
hunks = re.findall(r'@@ -(\d+),(\d+) \+(\d+),(\d+) @@([\s\S]+?)(?=@@|\Z)', diff)
# Apply the changes
new_content = original_content.copy()
offset = 0
for hunk in hunks:
start = int(hunk[2]) - 1 + offset
removed = int(hunk[1])
added = int(hunk[3])
changes = hunk[4].strip().split('\n')
# Remove lines
del new_content[start:start + removed]
# Add new lines
for change in changes:
if change.startswith('+'):
new_content.insert(start, change[1:] + '\n')
start += 1
offset += added - removed
# Write the modified content back to the file
with open(target_file, 'w') as f:
f.writelines(new_content)
print(f"Applied changes to {target_file}")
# Usage
patch_file = '/media/tom/1T-Disk/kernel/patch-5.10.209-rt101.patch'
target_folder = '/media/tom/1T-Disk/linux-5.10.209(test)'
apply_patch(patch_file, target_folder)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Dr_tree/kernel.git
git@gitee.com:Dr_tree/kernel.git
Dr_tree
kernel
kernel
master

搜索帮助