3 """Utilities for working with files."""
14 from typing import Optional
16 from os.path import isfile, join, exists
17 from typing import List
18 from uuid import uuid4
21 logger = logging.getLogger(__name__)
24 def remove_newlines(x):
25 return x.replace('\n', '')
28 def strip_whitespace(x):
32 def remove_hash_comments(x):
33 return re.sub(r'#.*$', '', x)
39 skip_blank_lines=False,
43 if not file_is_readable(filename):
44 raise Exception(f'{filename} can\'t be read.')
45 with open(filename) as rf:
47 for transformation in line_transformers:
48 line = transformation(line)
49 if skip_blank_lines and line == '':
55 def remove(path: str) -> None:
56 """Deletes a file. Raises if path refers to a directory or a file
60 >>> filename = '/tmp/file_utils_test_file'
61 >>> os.system(f'touch {filename}')
63 >>> does_file_exist(filename)
66 >>> does_file_exist(filename)
73 def delete(path: str) -> None:
77 def without_extension(path: str) -> str:
78 """Remove one extension from a file or path.
80 >>> without_extension('foobar.txt')
83 >>> without_extension('/home/scott/frapp.py')
86 >>> without_extension('a.b.c.tar.gz')
89 >>> without_extension('foobar')
93 return os.path.splitext(path)[0]
96 def without_all_extensions(path: str) -> str:
97 """Removes all extensions from a path; handles multiple extensions
98 like foobar.tar.gz -> foobar.
100 >>> without_all_extensions('/home/scott/foobar.1.tar.gz')
105 path = without_extension(path)
109 def get_extension(path: str) -> str:
110 """Extract and return one extension from a file or path.
112 >>> get_extension('this_is_a_test.txt')
115 >>> get_extension('/home/scott/test.py')
118 >>> get_extension('foobar')
122 return os.path.splitext(path)[1]
125 def get_all_extensions(path: str) -> List[str]:
126 """Return the extensions of a file or path in order.
128 >>> get_all_extensions('/home/scott/foo.tar.gz.1')
129 ['.tar', '.gz', '.1']
134 ext = get_extension(path)
135 path = without_extension(path)
143 def without_path(filespec: str) -> str:
144 """Returns the base filename without any leading path.
146 >>> without_path('/home/scott/foo.py')
149 >>> without_path('foo.py')
153 return os.path.split(filespec)[1]
156 def get_path(filespec: str) -> str:
157 """Returns just the path of the filespec by removing the filename and
160 >>> get_path('/home/scott/foobar.py')
163 >>> get_path('~scott/frapp.txt')
167 return os.path.split(filespec)[0]
170 def get_canonical_path(filespec: str) -> str:
171 """Returns a canonicalized absolute path.
173 >>> get_canonical_path('/home/scott/../../home/lynn/../scott/foo.txt')
174 '/usr/home/scott/foo.txt'
177 return os.path.realpath(filespec)
180 def create_path_if_not_exist(path, on_error=None):
182 Attempts to create path if it does not exist. If on_error is
183 specified, it is called with an exception if one occurs, otherwise
184 exception is rethrown.
188 >>> path = os.path.join("/tmp", str(uuid.uuid4()), str(uuid.uuid4()))
189 >>> os.path.exists(path)
191 >>> create_path_if_not_exist(path)
192 >>> os.path.exists(path)
195 logger.debug(f"Creating path {path}")
196 previous_umask = os.umask(0)
199 os.chmod(path, 0o777)
200 except OSError as ex:
201 if ex.errno != errno.EEXIST and not os.path.isdir(path):
202 if on_error is not None:
207 os.umask(previous_umask)
210 def does_file_exist(filename: str) -> bool:
211 """Returns True if a file exists and is a normal file.
213 >>> does_file_exist(__file__)
216 return os.path.exists(filename) and os.path.isfile(filename)
219 def file_is_readable(filename: str) -> bool:
220 return does_file_exist(filename) and os.access(filename, os.R_OK)
223 def file_is_writable(filename: str) -> bool:
224 return does_file_exist(filename) and os.access(filename, os.W_OK)
227 def file_is_executable(filename: str) -> bool:
228 return does_file_exist(filename) and os.access(filename, os.X_OK)
231 def does_directory_exist(dirname: str) -> bool:
232 """Returns True if a file exists and is a directory.
234 >>> does_directory_exist('/tmp')
237 return os.path.exists(dirname) and os.path.isdir(dirname)
240 def does_path_exist(pathname: str) -> bool:
241 """Just a more verbose wrapper around os.path.exists."""
242 return os.path.exists(pathname)
245 def get_file_size(filename: str) -> int:
246 """Returns the size of a file in bytes."""
247 return os.path.getsize(filename)
250 def is_normal_file(filename: str) -> bool:
251 """Returns True if filename is a normal file.
253 >>> is_normal_file(__file__)
256 return os.path.isfile(filename)
259 def is_directory(filename: str) -> bool:
260 """Returns True if filename is a directory.
262 >>> is_directory('/tmp')
265 return os.path.isdir(filename)
268 def is_symlink(filename: str) -> bool:
269 """True if filename is a symlink, False otherwise.
271 >>> is_symlink('/tmp')
274 >>> is_symlink('/home')
278 return os.path.islink(filename)
281 def is_same_file(file1: str, file2: str) -> bool:
282 """Returns True if the two files are the same inode.
284 >>> is_same_file('/tmp', '/tmp/../tmp')
287 >>> is_same_file('/tmp', '/home')
291 return os.path.samefile(file1, file2)
294 def get_file_raw_timestamps(filename: str) -> Optional[os.stat_result]:
295 """Stats the file and returns an os.stat_result or None on error."""
297 return os.stat(filename)
298 except Exception as e:
303 def get_file_raw_timestamp(filename: str, extractor) -> Optional[float]:
304 tss = get_file_raw_timestamps(filename)
306 return extractor(tss)
310 def get_file_raw_atime(filename: str) -> Optional[float]:
311 return get_file_raw_timestamp(filename, lambda x: x.st_atime)
314 def get_file_raw_mtime(filename: str) -> Optional[float]:
315 return get_file_raw_timestamp(filename, lambda x: x.st_mtime)
318 def get_file_raw_ctime(filename: str) -> Optional[float]:
319 return get_file_raw_timestamp(filename, lambda x: x.st_ctime)
322 def get_file_md5(filename: str) -> str:
323 """Hashes filename's contents and returns an MD5."""
324 file_hash = hashlib.md5()
325 with open(filename, "rb") as f:
328 file_hash.update(chunk)
330 return file_hash.hexdigest()
333 def set_file_raw_atime(filename: str, atime: float):
334 mtime = get_file_raw_mtime(filename)
335 os.utime(filename, (atime, mtime))
338 def set_file_raw_mtime(filename: str, mtime: float):
339 atime = get_file_raw_atime(filename)
340 os.utime(filename, (atime, mtime))
343 def set_file_raw_atime_and_mtime(filename: str, ts: float = None):
345 os.utime(filename, (ts, ts))
347 os.utime(filename, None)
350 def convert_file_timestamp_to_datetime(
351 filename: str, producer
352 ) -> Optional[datetime.datetime]:
353 ts = producer(filename)
355 return datetime.datetime.fromtimestamp(ts)
359 def get_file_atime_as_datetime(filename: str) -> Optional[datetime.datetime]:
360 return convert_file_timestamp_to_datetime(filename, get_file_raw_atime)
363 def get_file_mtime_as_datetime(filename: str) -> Optional[datetime.datetime]:
364 return convert_file_timestamp_to_datetime(filename, get_file_raw_mtime)
367 def get_file_ctime_as_datetime(filename: str) -> Optional[datetime.datetime]:
368 return convert_file_timestamp_to_datetime(filename, get_file_raw_ctime)
371 def get_file_timestamp_age_seconds(filename: str, extractor) -> Optional[int]:
373 ts = get_file_raw_timestamps(filename)
376 result = extractor(ts)
380 def get_file_atime_age_seconds(filename: str) -> Optional[int]:
381 return get_file_timestamp_age_seconds(filename, lambda x: x.st_atime)
384 def get_file_ctime_age_seconds(filename: str) -> Optional[int]:
385 return get_file_timestamp_age_seconds(filename, lambda x: x.st_ctime)
388 def get_file_mtime_age_seconds(filename: str) -> Optional[int]:
389 return get_file_timestamp_age_seconds(filename, lambda x: x.st_mtime)
392 def get_file_timestamp_timedelta(
393 filename: str, extractor
394 ) -> Optional[datetime.timedelta]:
395 age = get_file_timestamp_age_seconds(filename, extractor)
397 return datetime.timedelta(seconds=float(age))
401 def get_file_atime_timedelta(filename: str) -> Optional[datetime.timedelta]:
402 return get_file_timestamp_timedelta(filename, lambda x: x.st_atime)
405 def get_file_ctime_timedelta(filename: str) -> Optional[datetime.timedelta]:
406 return get_file_timestamp_timedelta(filename, lambda x: x.st_ctime)
409 def get_file_mtime_timedelta(filename: str) -> Optional[datetime.timedelta]:
410 return get_file_timestamp_timedelta(filename, lambda x: x.st_mtime)
413 def describe_file_timestamp(filename: str, extractor, *, brief=False) -> Optional[str]:
414 from datetime_utils import describe_duration, describe_duration_briefly
416 age = get_file_timestamp_age_seconds(filename, extractor)
420 return describe_duration_briefly(age)
422 return describe_duration(age)
425 def describe_file_atime(filename: str, *, brief=False) -> Optional[str]:
426 return describe_file_timestamp(filename, lambda x: x.st_atime, brief=brief)
429 def describe_file_ctime(filename: str, *, brief=False) -> Optional[str]:
430 return describe_file_timestamp(filename, lambda x: x.st_ctime, brief=brief)
433 def describe_file_mtime(filename: str, *, brief=False) -> Optional[str]:
434 return describe_file_timestamp(filename, lambda x: x.st_mtime, brief=brief)
437 def touch_file(filename: str, *, mode: Optional[int] = 0o666) -> bool:
438 return pathlib.Path(filename, mode=mode).touch()
441 def expand_globs(in_filename: str):
442 for filename in glob.glob(in_filename):
446 def get_files(directory: str):
447 for filename in os.listdir(directory):
448 full_path = join(directory, filename)
449 if isfile(full_path) and exists(full_path):
453 def get_directories(directory: str):
454 for d in os.listdir(directory):
455 full_path = join(directory, d)
456 if not isfile(full_path) and exists(full_path):
460 def get_files_recursive(directory: str):
461 for filename in get_files(directory):
463 for subdir in get_directories(directory):
464 for file_or_directory in get_files_recursive(subdir):
465 yield file_or_directory
468 class FileWriter(object):
469 def __init__(self, filename: str) -> None:
470 self.filename = filename
472 self.tempfile = f'{filename}-{uuid}.tmp'
475 def __enter__(self) -> io.TextIOWrapper:
476 assert not does_path_exist(self.tempfile)
477 self.handle = open(self.tempfile, mode="w")
480 def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
481 if self.handle is not None:
483 cmd = f'/bin/mv -f {self.tempfile} {self.filename}'
486 raise Exception(f'{cmd} failed, exit value {ret>>8}')
490 if __name__ == '__main__':