gitignore_clean.py: refactoring
1. Import only function `glob` from `glob` module 2. Extract `GITIGNORE_PATH` and functions `read_gitignore`, `delete`, `extend_wildcards` 3. Wrap runtime code in `if __name__ == "__main__"`
This commit is contained in:
parent
37d1988fcc
commit
bf23384cde
|
@ -1,31 +1,53 @@
|
|||
#!/usr/bin/python3
|
||||
|
||||
import os
|
||||
import glob
|
||||
from glob import glob
|
||||
from shutil import rmtree
|
||||
|
||||
GITIGNORE_PATH = "./.gitignore"
|
||||
DRY_RUN = False
|
||||
|
||||
|
||||
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 = os.path.isdir(file_path)
|
||||
is_file = os.path.isfile(file_path)
|
||||
|
||||
if not (is_dir or is_file):
|
||||
return
|
||||
|
||||
display_file_path = os.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 os.path.isdir(file_path):
|
||||
rmtree(file_path, ignore_errors=True)
|
||||
elif os.path.isfile(file_path):
|
||||
os.remove(file_path)
|
||||
|
||||
|
||||
def extend_wildcards(patterns: list):
|
||||
res = []
|
||||
for pattern in patterns:
|
||||
res.extend(glob(pattern, recursive=True))
|
||||
return res
|
||||
|
||||
|
||||
def clean_gitignored_files():
|
||||
gitignore_patterns = []
|
||||
with open(".gitignore", "r", encoding="utf-8-sig") as gitignore_file:
|
||||
gitignore_patterns = gitignore_file.read().splitlines()
|
||||
|
||||
ignored_files = []
|
||||
for pattern in gitignore_patterns:
|
||||
ignored_files.extend(glob.glob(pattern, recursive=True))
|
||||
|
||||
for file_path in ignored_files:
|
||||
display_file_path = os.path.abspath(file_path)
|
||||
if os.path.isdir(file_path):
|
||||
print("Removing directory", display_file_path)
|
||||
if not DRY_RUN:
|
||||
rmtree(file_path, ignore_errors=True)
|
||||
else:
|
||||
print("Removing file", display_file_path)
|
||||
if not DRY_RUN:
|
||||
os.remove(file_path)
|
||||
for file_path in extend_wildcards(read_gitignore()):
|
||||
delete(file_path)
|
||||
|
||||
|
||||
clean_gitignored_files()
|
||||
if __name__ == "__main__":
|
||||
clean_gitignored_files()
|
||||
|
|
Loading…
Reference in New Issue