olas-operate-middleware 0.11.5__py3-none-any.whl → 0.12.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
operate/utils/__init__.py CHANGED
@@ -19,6 +19,8 @@
19
19
 
20
20
  """Helper utilities."""
21
21
 
22
+ import os
23
+ import platform
22
24
  import shutil
23
25
  import time
24
26
  import typing as t
@@ -107,3 +109,47 @@ def subtract_dicts(
107
109
  else:
108
110
  result[key] = max((va or 0) - (vb or 0), 0) # type: ignore
109
111
  return result
112
+
113
+
114
+ def safe_file_operation(operation: t.Callable, *args: t.Any, **kwargs: t.Any) -> None:
115
+ """Safely perform file operation with retries on Windows."""
116
+ max_retries = 3 if platform.system() == "Windows" else 1
117
+
118
+ for attempt in range(max_retries):
119
+ try:
120
+ operation(*args, **kwargs)
121
+ return
122
+ except (PermissionError, FileNotFoundError, OSError) as e:
123
+ if attempt == max_retries - 1:
124
+ raise e
125
+
126
+ if platform.system() == "Windows":
127
+ # On Windows, wait a bit and retry
128
+ time.sleep(0.1)
129
+
130
+
131
+ def unrecoverable_delete(file_path: Path, passes: int = 3) -> None:
132
+ """Delete a file unrecoverably."""
133
+ if not file_path.exists():
134
+ return
135
+
136
+ if not file_path.is_file():
137
+ raise ValueError(f"{file_path} is not a file")
138
+
139
+ try:
140
+ file_size = os.path.getsize(file_path)
141
+
142
+ with open(file_path, "r+b") as f:
143
+ for _ in range(passes):
144
+ # Overwrite with random bytes
145
+ f.seek(0)
146
+ random_data = os.urandom(file_size)
147
+ f.write(random_data)
148
+ f.flush() # Ensure data is written to disk
149
+
150
+ # Finally, delete the file
151
+ safe_file_operation(os.remove, file_path)
152
+ except PermissionError:
153
+ print(f"Permission denied to securely delete file '{file_path}'.")
154
+ except Exception as e: # pylint: disable=broad-except
155
+ print(f"Error during secure deletion of '{file_path}': {e}")