Coverage for addmo/util/load_save_utils.py: 49%
51 statements
« prev ^ index » next coverage.py v7.4.4, created at 2025-08-31 13:05 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2025-08-31 13:05 +0000
1import os
2import shutil
4def root_dir():
5 """
6 Finds the root directory of the git repository.
7 """
8 return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
10def create_or_clean_directory(path: str, user_input='y') -> str:
11 """
12 Creates a directory or optionally deletes its contents if it exists.
13 """
14 if not os.path.exists(path):
15 # Path does not exist, create it
16 os.makedirs(path)
17 elif not os.listdir(path):
18 # Path exists, but is empty
19 pass
20 else:
21 # Path exists, ask for confirmation to delete current contents
22 response = user_input
24 if response.lower() == 'd':
25 # Delete the contents of the directory
26 for filename in os.listdir(path):
27 file_path = os.path.join(path, filename)
28 if os.path.isfile(file_path) or os.path.islink(file_path):
29 os.unlink(file_path)
30 elif os.path.isdir(file_path):
31 shutil.rmtree(file_path)
32 elif response.lower() == 'y':
33 pass
34 else:
35 print("Operation cancelled.")
36 return None
38 return path
41def create_path_or_ask_to_override(filename, directory, override: bool = True) -> str:
42 """
43 Creates a file path and optionally overwrites the existing file.
44 """
45 path = create_dir_and_get_path(filename, directory)
46 _overwrite_file(path, override)
47 return path
50def create_dir_and_get_path(filename: str, directory: str) -> str:
51 """
52 Returns the full path for a given filename and directory.
53 """
54 if directory is not None: # check if directory is none
55 if not os.path.exists(directory): # check if path exists
56 os.makedirs(directory) # create new directory
57 return os.path.join(directory, filename) # calculate full path
58 else:
59 return filename
62def _overwrite_file(path: str, overwrite: bool):
63 """
64 Checks if a file exists and if it should be overwritten.
65 """
66 if os.path.exists(path) and not overwrite:
67 if not _get_bool(
68 f'The file "{path}" already exists. Do you want to override it?\n'
69 ):
70 return 0
73def _get_bool(message: str, true: list = None, false: list = None) -> bool or str:
74 """
75 Gets a boolean value from the user.
76 """
77 if false is None:
78 false = ["no", "nein", "false", "1", "n"]
79 if true is None:
80 true = ["yes", "ja", "true", "wahr", "0", "y"]
82 val = input(message).lower()
83 if val in true:
84 return True
85 elif val in false:
86 return False
87 else:
88 print("Please try again.")
89 print("True:", true)
90 print("False:", false)
91 _get_bool(message, true, false)
93 return val