Skip to content

Commit 2047613

Browse files
committed
refactored file_operations.py
1 parent 54f1568 commit 2047613

File tree

1 file changed

+71
-34
lines changed

1 file changed

+71
-34
lines changed

helper/file_operations.py

Lines changed: 71 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -12,67 +12,104 @@ def get_file_from_path(file_path):
1212
def get_file_name_without_extension(file):
1313
return file.rpartition(".")[0]
1414

15+
16+
def create_folder(folder_path: str) -> None:
17+
"""
18+
Creates a folder if it does not already exist.
19+
20+
Args:
21+
folder_path (str): The path to the folder.
22+
"""
23+
folder = Path(folder_path)
24+
if not folder.exists():
25+
folder.mkdir(parents=True, exist_ok=True)
26+
27+
1528
def create_database_folder() -> bool:
16-
"""Also returns a boolean to check if it's a users first time starting the tool"""
17-
if not Path.exists(Path("database/")):
18-
Path.mkdir(Path("database/"))
29+
"""
30+
Creates the 'database/' folder if it doesn't exist.
31+
32+
Returns:
33+
bool: True if the folder was created (indicating first-time use), False otherwise.
34+
"""
35+
database_path = Path("database/")
36+
if not database_path.exists():
37+
database_path.mkdir(parents=True, exist_ok=True)
1938
return True
39+
return False
2040

21-
def create_log_folder():
22-
if not Path.exists(Path("logs/")):
23-
Path.mkdir(Path("logs/"))
2441

25-
def create_temp_folder():
26-
if not Path.exists(Path("temp/")):
27-
Path.mkdir(Path("temp/"))
42+
def create_log_folder() -> None:
43+
create_folder("logs/")
2844

29-
def delete_temp_folder():
30-
if Path.exists(Path("temp/")):
31-
shutil.rmtree("temp/")
45+
46+
def create_temp_folder() -> None:
47+
create_folder("temp/")
48+
49+
50+
def delete_temp_folder() -> None:
51+
temp_path = Path("temp/")
52+
if temp_path.exists():
53+
shutil.rmtree(temp_path)
3254

3355
def get_file_size(file_path):
34-
return _convert_size(Path(file_path).stat().st_size)
56+
file = Path(file_path)
57+
if not file.exists():
58+
raise FileNotFoundError(f"File not found: {file_path}")
59+
return _convert_size(file.stat().st_size)
60+
3561

36-
def _convert_size(size_bytes):
37-
# Edge case for size 0 bytes
62+
def _convert_size(size_bytes: int) -> str:
63+
"""
64+
Converts a file size in bytes to a human-readable format.
65+
66+
Args:
67+
size_bytes (int): The file size in bytes.
68+
69+
Returns:
70+
str: The file size in human-readable format (e.g., KB, MB).
71+
"""
3872
if size_bytes == 0:
3973
return "0 B"
4074

41-
# List of size units
42-
size_units = ["B", "KB", "MB", "GB"]
75+
size_units = ["B", "KB", "MB", "GB", "TB"]
4376
i = 0
44-
45-
# Convert to larger units until size is below 1024
4677
while size_bytes >= 1024 and i < len(size_units) - 1:
4778
size_bytes /= 1024
4879
i += 1
4980

50-
# Return formatted size with 2 decimal places
5181
return f"{size_bytes:.2f} {size_units[i]}"
5282

53-
def limit_logger_files():
54-
"""Function to delete the oldest log file when there are already 3 present"""
83+
84+
def limit_logger_files() -> None:
85+
"""
86+
Deletes the oldest log files when the number of log files exceeds the limit.
87+
"""
5588
log_dir = Path("logs/")
56-
log_files = list(log_dir.iterdir()) # Get all files in the directory
5789

58-
if len(log_files) > 2:
59-
# Sort files by creation time (ascending order, oldest first)
60-
log_files_sorted = sorted(log_files, key=lambda f: f.stat().st_ctime)
90+
log_files = sorted(log_dir.iterdir(), key=lambda f: f.stat().st_ctime)
6191

62-
# Delete the oldest files to ensure only 2 are kept
92+
if len(log_files) > 2:
6393
files_to_delete = len(log_files) - 2
64-
for file in log_files_sorted[:files_to_delete]:
94+
for file in log_files[:files_to_delete]:
6595
file.unlink()
6696

67-
def create_logger():
97+
98+
def create_logger() -> logging.Logger:
99+
"""
100+
Sets up the logging configuration and creates a new log file.
101+
102+
Returns:
103+
logging.Logger: A configured logger instance.
104+
"""
68105
create_log_folder()
69106
limit_logger_files()
70-
now = datetime.now()
71-
now = now.strftime("%d.%m.%Y %H-%M-%S")
72-
log_file = f"logs/{now}.log"
107+
now = datetime.now().strftime("%d.%m.%Y %H-%M-%S")
108+
log_file = Path("logs") / f"{now}.log"
73109
logging.basicConfig(
74-
filename=log_file,
110+
filename=str(log_file),
75111
level=logging.INFO,
76-
format="%(asctime)s - %(levelname)s - %(message)s", datefmt='%m/%d/%Y %I:%M:%S'
112+
format="%(asctime)s - %(levelname)s - %(message)s",
113+
datefmt='%m/%d/%Y %I:%M:%S'
77114
)
78115
return logging.getLogger(__name__)

0 commit comments

Comments
 (0)