1
0
C-bytebeat-render/gitignore_clean.py

66 lines
1.6 KiB
Python

#!/usr/bin/env python3
from re import sub as re_sub
from glob import glob
from os import remove as os_remove
from os.path import isdir as path_isdir, isfile as path_isfile, abspath
from shutil import rmtree
GITIGNORE_PATH = "./.gitignore"
DRY_RUN = False
remove_comments = lambda s: re_sub(r"(?<!\\)#.*$", "", s).replace(r"\#", "#")
def read_gitignore():
res = ""
with open(GITIGNORE_PATH, "r", encoding="utf-8-sig") as gitignore_file:
res = gitignore_file.read().splitlines()
return res
def delete(file_path: str):
is_dir = path_isdir(file_path)
is_file = path_isfile(file_path)
if not (is_dir or is_file):
return
display_file_path = abspath(file_path)
if is_dir:
print("Removing directory", display_file_path)
elif is_file:
print("Removing file", display_file_path)
if DRY_RUN:
return
if is_dir:
rmtree(file_path, ignore_errors=True)
elif is_file:
os_remove(file_path)
def extend_wildcards(patterns: list):
res = []
for pattern in patterns:
processed_line = remove_comments(pattern).strip()
if processed_line.startswith("!"):
exception_pattern = processed_line[1:]
exceptions = glob(exception_pattern, recursive=True)
res = [path for path in res if path not in exceptions]
else:
res.extend(glob(processed_line, recursive=True))
return res
def clean_gitignored_files():
for file_path in extend_wildcards(read_gitignore()):
delete(file_path)
if __name__ == "__main__":
clean_gitignored_files()