3 """Utilities for working with files."""
13 from typing import Optional
15 from os.path import isfile, join, exists
16 from uuid import uuid4
19 logger = logging.getLogger(__name__)
22 # os.remove(file) you fuckwit.
25 def create_path_if_not_exist(path, on_error=None):
27 Attempts to create path if it does not exist. If on_error is
28 specified, it is called with an exception if one occurs, otherwise
29 exception is rethrown.
33 >>> path = os.path.join("/tmp", str(uuid.uuid4()), str(uuid.uuid4()))
34 >>> os.path.exists(path)
36 >>> create_path_if_not_exist(path)
37 >>> os.path.exists(path)
40 logger.debug(f"Creating path {path}")
41 previous_umask = os.umask(0)
46 if ex.errno != errno.EEXIST and not os.path.isdir(path):
47 if on_error is not None:
52 os.umask(previous_umask)
55 def does_file_exist(filename: str) -> bool:
56 """Returns True if a file exists and is a normal file.
58 >>> does_file_exist(__file__)
61 return os.path.exists(filename) and os.path.isfile(filename)
64 def does_directory_exist(dirname: str) -> bool:
65 """Returns True if a file exists and is a directory.
67 >>> does_directory_exist('/tmp')
70 return os.path.exists(dirname) and os.path.isdir(dirname)
73 def does_path_exist(pathname: str) -> bool:
74 """Just a more verbose wrapper around os.path.exists."""
75 return os.path.exists(pathname)
78 def get_file_size(filename: str) -> int:
79 """Returns the size of a file in bytes."""
80 return os.path.getsize(filename)
83 def is_normal_file(filename: str) -> bool:
84 """Returns True if filename is a normal file.
86 >>> is_normal_file(__file__)
89 return os.path.isfile(filename)
92 def is_directory(filename: str) -> bool:
93 """Returns True if filename is a directory.
95 >>> is_directory('/tmp')
98 return os.path.isdir(filename)
101 def is_symlink(filename: str) -> bool:
102 return os.path.islink(filename)
105 def is_same_file(file1: str, file2: str) -> bool:
106 return os.path.samefile(file1, file2)
109 def get_file_raw_timestamps(filename: str) -> Optional[os.stat_result]:
111 return os.stat(filename)
112 except Exception as e:
117 def get_file_raw_timestamp(filename: str, extractor) -> Optional[float]:
118 tss = get_file_raw_timestamps(filename)
120 return extractor(tss)
124 def get_file_raw_atime(filename: str) -> Optional[float]:
125 return get_file_raw_timestamp(filename, lambda x: x.st_atime)
128 def get_file_raw_mtime(filename: str) -> Optional[float]:
129 return get_file_raw_timestamp(filename, lambda x: x.st_mtime)
132 def get_file_raw_ctime(filename: str) -> Optional[float]:
133 return get_file_raw_timestamp(filename, lambda x: x.st_ctime)
136 def get_file_md5(filename: str) -> str:
137 file_hash = hashlib.md5()
138 with open(filename, "rb") as f:
141 file_hash.update(chunk)
143 return file_hash.hexdigest()
146 def set_file_raw_atime(filename: str, atime: float):
147 mtime = get_file_raw_mtime(filename)
148 os.utime(filename, (atime, mtime))
151 def set_file_raw_mtime(filename: str, mtime: float):
152 atime = get_file_raw_atime(filename)
153 os.utime(filename, (atime, mtime))
156 def set_file_raw_atime_and_mtime(filename: str, ts: float = None):
158 os.utime(filename, (ts, ts))
160 os.utime(filename, None)
163 def convert_file_timestamp_to_datetime(
164 filename: str, producer
165 ) -> Optional[datetime.datetime]:
166 ts = producer(filename)
168 return datetime.datetime.fromtimestamp(ts)
172 def get_file_atime_as_datetime(filename: str) -> Optional[datetime.datetime]:
173 return convert_file_timestamp_to_datetime(filename, get_file_raw_atime)
176 def get_file_mtime_as_datetime(filename: str) -> Optional[datetime.datetime]:
177 return convert_file_timestamp_to_datetime(filename, get_file_raw_mtime)
180 def get_file_ctime_as_datetime(filename: str) -> Optional[datetime.datetime]:
181 return convert_file_timestamp_to_datetime(filename, get_file_raw_ctime)
184 def get_file_timestamp_age_seconds(filename: str, extractor) -> Optional[int]:
186 ts = get_file_raw_timestamps(filename)
189 result = extractor(ts)
193 def get_file_atime_age_seconds(filename: str) -> Optional[int]:
194 return get_file_timestamp_age_seconds(filename, lambda x: x.st_atime)
197 def get_file_ctime_age_seconds(filename: str) -> Optional[int]:
198 return get_file_timestamp_age_seconds(filename, lambda x: x.st_ctime)
201 def get_file_mtime_age_seconds(filename: str) -> Optional[int]:
202 return get_file_timestamp_age_seconds(filename, lambda x: x.st_mtime)
205 def get_file_timestamp_timedelta(
206 filename: str, extractor
207 ) -> Optional[datetime.timedelta]:
208 age = get_file_timestamp_age_seconds(filename, extractor)
210 return datetime.timedelta(seconds=float(age))
214 def get_file_atime_timedelta(filename: str) -> Optional[datetime.timedelta]:
215 return get_file_timestamp_timedelta(filename, lambda x: x.st_atime)
218 def get_file_ctime_timedelta(filename: str) -> Optional[datetime.timedelta]:
219 return get_file_timestamp_timedelta(filename, lambda x: x.st_ctime)
222 def get_file_mtime_timedelta(filename: str) -> Optional[datetime.timedelta]:
223 return get_file_timestamp_timedelta(filename, lambda x: x.st_mtime)
226 def describe_file_timestamp(
227 filename: str, extractor, *, brief=False
229 from datetime_utils import describe_duration, describe_duration_briefly
230 age = get_file_timestamp_age_seconds(filename, extractor)
234 return describe_duration_briefly(age)
236 return describe_duration(age)
239 def describe_file_atime(filename: str, *, brief=False) -> Optional[str]:
240 return describe_file_timestamp(filename, lambda x: x.st_atime, brief=brief)
243 def describe_file_ctime(filename: str, *, brief=False) -> Optional[str]:
244 return describe_file_timestamp(filename, lambda x: x.st_ctime, brief=brief)
247 def describe_file_mtime(filename: str, *, brief=False) -> Optional[str]:
248 return describe_file_timestamp(filename, lambda x: x.st_mtime, brief=brief)
251 def touch_file(filename: str) -> bool:
252 return pathlib.Path(filename).touch()
255 def expand_globs(in_filename: str):
256 for filename in glob.glob(in_filename):
260 def get_files(directory: str):
261 for filename in os.listdir(directory):
262 full_path = join(directory, filename)
263 if isfile(full_path) and exists(full_path):
267 def get_directories(directory: str):
268 for d in os.listdir(directory):
269 full_path = join(directory, d)
270 if not isfile(full_path) and exists(full_path):
274 def get_files_recursive(directory: str):
275 for filename in get_files(directory):
277 for subdir in get_directories(directory):
278 for file_or_directory in get_files_recursive(subdir):
279 yield file_or_directory
282 class FileWriter(object):
283 def __init__(self, filename: str) -> None:
284 self.filename = filename
286 self.tempfile = f'{filename}-{uuid}.tmp'
289 def __enter__(self) -> io.TextIOWrapper:
290 assert not does_path_exist(self.tempfile)
291 self.handle = open(self.tempfile, mode="w")
294 def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
295 if self.handle is not None:
297 cmd = f'/bin/mv -f {self.tempfile} {self.filename}'
300 raise Exception(f'{cmd} failed, exit value {ret>>8}')
304 if __name__ == '__main__':