-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
108 lines (87 loc) · 3.18 KB
/
Copy pathutils.py
File metadata and controls
108 lines (87 loc) · 3.18 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
import os
from pathlib import Path
from typing import List
def can_convert_to_int(s):
if not isinstance(s, str) or not s.strip():
return False
try:
int(s)
return True
except (ValueError, TypeError):
return False
def find_all_java_files(root_dir: str) -> List[str]:
"""
use pathlib to find java files recursively
"""
root = Path(root_dir)
return [str(f) for f in root.rglob("*.java") if f.is_file()]
def apply_modifications(modifications):
"""
apply modifications to local files
support :
- file_path
- edit (e.g., "line1\nline2")
:param modifications: dict,format:
{
"/absolute/path/to/File.java": [
(start_line, end_line, edit_string),
...
],
...
}
:return: success (bool), failed_files (list)
"""
failed_files = []
for file_path, edits in modifications.items():
# check if file exists
if not os.path.exists(file_path):
print(f"[ERROR] File not found: {file_path}")
failed_files.append(file_path)
continue
try:
# 1. read original file
with open(file_path, 'r', newline='', encoding='utf-8') as f:
lines = f.readlines()
# 2. line break char
line_ending = '\n'
if lines:
sample = lines[0]
if sample.endswith('\r\n'):
line_ending = '\r\n'
elif sample.endswith('\n'):
line_ending = '\n'
# 3. sort desc
sorted_edits = sorted(edits, key=lambda x: x[0], reverse=True)
new_lines = lines
for start_line, end_line, edit in sorted_edits:
start_idx = start_line - 1
edit_lines = edit.splitlines()
new_chunk = [line + line_ending for line in edit_lines]
if start_line > end_line:
insertion_point = start_idx + 1
new_lines = (
new_lines[:insertion_point] +
new_chunk +
new_lines[insertion_point:]
)
else:
end_idx = end_line - 1
new_lines = (
new_lines[:start_idx] +
new_chunk +
new_lines[end_idx + 1:]
)
# 4. write back
with open(file_path, 'w', newline='', encoding='utf-8') as f:
f.writelines(new_lines)
print(f"[SUCCESS] Applied edits to: {file_path}")
except Exception as e:
print(f"[ERROR] Failed to apply edits to {file_path}: {str(e)}")
failed_files.append(file_path)
success = len(failed_files) == 0
return success, failed_files
def test_apply_modifications():
demo_modifications = {
'./testcases/Xml.java': [[67, 66,' documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);']]
}
apply_modifications(modifications=demo_modifications)