-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
repoTree.py
75 lines (63 loc) · 2.72 KB
/
repoTree.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import os
import fnmatch
def read_gitignore(startpath):
gitignore_path = os.path.join(startpath, ".gitignore")
ignore_list = [".git", ".husky", "__pycache__"] # Default ignores
if os.path.isfile(gitignore_path):
with open(gitignore_path, "r", encoding="utf-8") as f:
for line in f.readlines():
stripped_line = line.strip()
if stripped_line and not stripped_line.startswith("#"):
ignore_list.append(stripped_line)
return ignore_list
def is_ignored(path, ignore_list, startpath):
rel_path = os.path.relpath(path, start=startpath)
for pattern in ignore_list:
if pattern.startswith("/"):
pattern = pattern[1:]
if fnmatch.fnmatch(rel_path, pattern):
return True
else:
if fnmatch.fnmatch(rel_path, pattern) or fnmatch.fnmatch(
os.path.basename(path), pattern
):
return True
return False
def generate_tree(startpath):
ignore_list = read_gitignore(startpath)
tree_lines = []
print_tree(startpath, " ", tree_lines, ignore_list, startpath)
return "\n".join(tree_lines)
def print_tree(path, indent, tree_lines, ignore_list, root_path):
entries = sorted(os.listdir(path))
for entry in entries:
entry_path = os.path.join(path, entry)
if is_ignored(entry_path, ignore_list, root_path):
continue
if os.path.isdir(entry_path):
tree_lines.append(
f"{indent}- [**{entry}**](./{os.path.relpath(entry_path, root_path).replace(os.sep, '/').replace(' ', '%20')})"
)
new_indent = indent + " "
print_tree(entry_path, new_indent, tree_lines, ignore_list, root_path)
else:
tree_lines.append(
f"{indent}- [{entry}](./{os.path.relpath(entry_path, root_path).replace(os.sep, '/').replace(' ', '%20')})"
)
def update_readme_with_tree(readme_path, tree_content):
with open(readme_path, "r", encoding="utf-8") as file:
content = file.read()
start_marker = "<!-- tree generated by repoTree.py starts here -->"
end_marker = "<!-- tree generated by repoTree.py ends here -->"
start_index = content.find(start_marker) + len(start_marker)
end_index = content.find(end_marker)
updated_content = (
content[:start_index] + "\n\n" + tree_content + "\n" + content[end_index:]
)
with open(readme_path, "w", encoding="utf-8") as file:
file.write(updated_content)
# Define the start path for generating the tree and the README.md file path
start_path = "."
readme_path = "README.md"
tree_content = generate_tree(start_path)
update_readme_with_tree(readme_path, tree_content)