-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattach-fixer.py
More file actions
64 lines (51 loc) · 1.9 KB
/
attach-fixer.py
File metadata and controls
64 lines (51 loc) · 1.9 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
from pathlib import Path
import filetype
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
filename=Path.cwd() / "attach_fixer.log",
)
def find_references(key: Path, search_dir: Path):
for item in search_dir.iterdir():
if item.is_dir():
ref = find_references(key, item)
if ref:
return ref
elif item.is_file():
with open(item, "r", encoding="utf-8", errors="ignore") as file:
contents = file.read()
if key.name in contents:
return item
def detect_extension(file: Path) -> str:
return filetype.guess(file).extension
def apply_changes(attachment: Path, new_extension: str, ref: Path):
attachment.rename(attachment.with_suffix(f".{new_extension}"))
logging.info(
f"Renamed: {attachment} to {attachment.with_suffix(f'.{new_extension}')}"
)
with open(ref, "r", encoding="utf-8", errors="ignore") as file:
contents = file.read()
contents = contents.replace(
attachment.name, attachment.with_suffix(f".{new_extension}").name
)
with open(ref, "w", encoding="utf-8", errors="ignore") as file:
file.write(contents)
logging.info(f"Updated reference: {ref}")
def attach_fixer(attach_dir: Path, ref_dir: Path):
count = 0
found = 0
print("File | Detected ext | Reference")
for item in attach_dir.iterdir():
count += 1
if item.is_dir():
attach_fixer(item)
# Skip items with suffix
elif not item.suffix:
found += 1
ext = detect_extension(item)
ref = find_references(item, ref_dir)
# apply_changes(item, ext, ref)
print(f"{item.name} {ext} {ref}")
print(f"Total items reviewed: {count}")
print(f"Total items found: {found}")