-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilename_as_comment.py
60 lines (48 loc) · 2.06 KB
/
filename_as_comment.py
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
import os
import re
def process_file(filepath):
with open(filepath, 'r', encoding='utf-8') as file:
lines = file.readlines()
correct_path_comment = f"// {filepath}\n"
rs_comment_pattern = r'^// .+\.rs$'
action = None
if len(lines) > 0 and re.match(rs_comment_pattern, lines[0]):
if lines[0] != correct_path_comment:
lines[0] = correct_path_comment
action = "replaced"
else:
lines.insert(0, correct_path_comment)
action = "added"
# Ensure there's a blank line after the path-filename reference
if len(lines) == 1 or (len(lines) > 1 and lines[1].strip() != ""):
lines.insert(1, "\n")
action = "added blank line" if not action else action
with open(filepath, 'w', encoding='utf-8') as file:
file.writelines(lines)
if action:
print(f"{action.title()} path comment in {filepath}")
else:
print(f"Path comment unchanged in {filepath}")
def process_directory(root_dir):
ignored_dirs = {'src/generated', 'target'}
ignored_prefix = '.'
for root, dirs, files in os.walk(root_dir):
dirs[:] = [d for d in dirs if not d.startswith(ignored_prefix) and os.path.relpath(os.path.join(root, d), root_dir).replace('\\', '/') not in ignored_dirs]
for file in files:
if file.lower().endswith('.rs'):
filepath = os.path.join(root, file)
relative_path = os.path.relpath(filepath, root_dir).replace('\\', '/')
process_file(relative_path)
def find_root_directory():
cwd = os.getcwd()
if os.path.isfile(os.path.join(cwd, 'cargo.toml')):
return cwd
while True:
root_dir = input("Enter the project root directory: ")
if os.path.isfile(os.path.join(root_dir, 'cargo.toml')):
return root_dir
else:
print("No cargo.toml found in the specified directory. Please try again.")
if __name__ == "__main__":
project_root = find_root_directory()
process_directory(project_root)