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)
36 def read_file_to_list(
37 filename: str, *, skip_blank_lines=False, line_transformations=[]
40 if not file_is_readable(filename):
41 raise Exception(f'{filename} can\'t be read.')
42 with open(filename) as rf:
44 for transformation in line_transformations:
45 line = transformation(line)
46 if skip_blank_lines and line == '':
52 def remove(path: str) -> None:
53 """Deletes a file. Raises if path refers to a directory or a file
57 >>> filename = '/tmp/file_utils_test_file'
58 >>> os.system(f'touch {filename}')
60 >>> does_file_exist(filename)
63 >>> does_file_exist(filename)
70 def delete(path: str) -> None:
74 def without_extension(path: str) -> str:
75 """Remove one extension from a file or path.
77 >>> without_extension('foobar.txt')
80 >>> without_extension('/home/scott/frapp.py')
83 >>> without_extension('a.b.c.tar.gz')
86 >>> without_extension('foobar')
90 return os.path.splitext(path)[0]
93 def without_all_extensions(path: str) -> str:
94 """Removes all extensions from a path; handles multiple extensions
95 like foobar.tar.gz -> foobar.
97 >>> without_all_extensions('/home/scott/foobar.1.tar.gz')
102 path = without_extension(path)
106 def get_extension(path: str) -> str:
107 """Extract and return one extension from a file or path.
109 >>> get_extension('this_is_a_test.txt')
112 >>> get_extension('/home/scott/test.py')
115 >>> get_extension('foobar')
119 return os.path.splitext(path)[1]
122 def get_all_extensions(path: str) -> List[str]:
123 """Return the extensions of a file or path in order.
125 >>> get_all_extensions('/home/scott/foo.tar.gz.1')
126 ['.tar', '.gz', '.1']
131 ext = get_extension(path)
132 path = without_extension(path)
140 def without_path(filespec: str) -> str:
141 """Returns the base filename without any leading path.
143 >>> without_path('/home/scott/foo.py')
146 >>> without_path('foo.py')
150 return os.path.split(filespec)[1]
153 def get_path(filespec: str) -> str:
154 """Returns just the path of the filespec by removing the filename and
157 >>> get_path('/home/scott/foobar.py')
160 >>> get_path('~scott/frapp.txt')
164 return os.path.split(filespec)[0]
167 def get_canonical_path(filespec: str) -> str:
168 """Returns a canonicalized absolute path.
170 >>> get_canonical_path('/home/scott/../../home/lynn/../scott/foo.txt')
171 '/usr/home/scott/foo.txt'
174 return os.path.realpath(filespec)
177 def create_path_if_not_exist(path, on_error=None):
179 Attempts to create path if it does not exist. If on_error is
180 specified, it is called with an exception if one occurs, otherwise
181 exception is rethrown.
185 >>> path = os.path.join("/tmp", str(uuid.uuid4()), str(uuid.uuid4()))
186 >>> os.path.exists(path)
188 >>> create_path_if_not_exist(path)
189 >>> os.path.exists(path)
192 logger.debug(f"Creating path {path}")
193 previous_umask = os.umask(0)
196 os.chmod(path, 0o777)
197 except OSError as ex:
198 if ex.errno != errno.EEXIST and not os.path.isdir(path):
199 if on_error is not None:
204 os.umask(previous_umask)
207 def does_file_exist(filename: str) -> bool:
208 """Returns True if a file exists and is a normal file.
210 >>> does_file_exist(__file__)
213 return os.path.exists(filename) and os.path.isfile(filename)
216 def file_is_readable(filename: str) -> bool:
217 return does_file_exist(filename) and os.access(filename, os.R_OK)
220 def file_is_writable(filename: str) -> bool:
221 return does_file_exist(filename) and os.access(filename, os.W_OK)
224 def file_is_executable(filename: str) -> bool:
225 return does_file_exist(filename) and os.access(filename, os.X_OK)
228 def does_directory_exist(dirname: str) -> bool:
229 """Returns True if a file exists and is a directory.
231 >>> does_directory_exist('/tmp')
234 return os.path.exists(dirname) and os.path.isdir(dirname)
237 def does_path_exist(pathname: str) -> bool:
238 """Just a more verbose wrapper around os.path.exists."""
239 return os.path.exists(pathname)
242 def get_file_size(filename: str) -> int:
243 """Returns the size of a file in bytes."""
244 return os.path.getsize(filename)
247 def is_normal_file(filename: str) -> bool:
248 """Returns True if filename is a normal file.
250 >>> is_normal_file(__file__)
253 return os.path.isfile(filename)
256 def is_directory(filename: str) -> bool:
257 """Returns True if filename is a directory.
259 >>> is_directory('/tmp')
262 return os.path.isdir(filename)
265 def is_symlink(filename: str) -> bool:
266 """True if filename is a symlink, False otherwise.
268 >>> is_symlink('/tmp')
271 >>> is_symlink('/home')
275 return os.path.islink(filename)
278 def is_same_file(file1: str, file2: str) -> bool:
279 """Returns True if the two files are the same inode.
281 >>> is_same_file('/tmp', '/tmp/../tmp')
284 >>> is_same_file('/tmp', '/home')
288 return os.path.samefile(file1, file2)
291 def get_file_raw_timestamps(filename: str) -> Optional[os.stat_result]:
292 """Stats the file and returns an os.stat_result or None on error."""
294 return os.stat(filename)
295 except Exception as e:
300 def get_file_raw_timestamp(filename: str, extractor) -> Optional[float]:
301 tss = get_file_raw_timestamps(filename)
303 return extractor(tss)
307 def get_file_raw_atime(filename: str) -> Optional[float]:
308 return get_file_raw_timestamp(filename, lambda x: x.st_atime)
311 def get_file_raw_mtime(filename: str) -> Optional[float]:
312 return get_file_raw_timestamp(filename, lambda x: x.st_mtime)
315 def get_file_raw_ctime(filename: str) -> Optional[float]:
316 return get_file_raw_timestamp(filename, lambda x: x.st_ctime)
319 def get_file_md5(filename: str) -> str:
320 """Hashes filename's contents and returns an MD5."""
321 file_hash = hashlib.md5()
322 with open(filename, "rb") as f:
325 file_hash.update(chunk)
327 return file_hash.hexdigest()
330 def set_file_raw_atime(filename: str, atime: float):
331 mtime = get_file_raw_mtime(filename)
332 os.utime(filename, (atime, mtime))
335 def set_file_raw_mtime(filename: str, mtime: float):
336 atime = get_file_raw_atime(filename)
337 os.utime(filename, (atime, mtime))
340 def set_file_raw_atime_and_mtime(filename: str, ts: float = None):
342 os.utime(filename, (ts, ts))
344 os.utime(filename, None)
347 def convert_file_timestamp_to_datetime(
348 filename: str, producer
349 ) -> Optional[datetime.datetime]:
350 ts = producer(filename)
352 return datetime.datetime.fromtimestamp(ts)
356 def get_file_atime_as_datetime(filename: str) -> Optional[datetime.datetime]:
357 return convert_file_timestamp_to_datetime(filename, get_file_raw_atime)
360 def get_file_mtime_as_datetime(filename: str) -> Optional[datetime.datetime]:
361 return convert_file_timestamp_to_datetime(filename, get_file_raw_mtime)
364 def get_file_ctime_as_datetime(filename: str) -> Optional[datetime.datetime]:
365 return convert_file_timestamp_to_datetime(filename, get_file_raw_ctime)
368 def get_file_timestamp_age_seconds(filename: str, extractor) -> Optional[int]:
370 ts = get_file_raw_timestamps(filename)
373 result = extractor(ts)
377 def get_file_atime_age_seconds(filename: str) -> Optional[int]:
378 return get_file_timestamp_age_seconds(filename, lambda x: x.st_atime)
381 def get_file_ctime_age_seconds(filename: str) -> Optional[int]:
382 return get_file_timestamp_age_seconds(filename, lambda x: x.st_ctime)
385 def get_file_mtime_age_seconds(filename: str) -> Optional[int]:
386 return get_file_timestamp_age_seconds(filename, lambda x: x.st_mtime)
389 def get_file_timestamp_timedelta(
390 filename: str, extractor
391 ) -> Optional[datetime.timedelta]:
392 age = get_file_timestamp_age_seconds(filename, extractor)
394 return datetime.timedelta(seconds=float(age))
398 def get_file_atime_timedelta(filename: str) -> Optional[datetime.timedelta]:
399 return get_file_timestamp_timedelta(filename, lambda x: x.st_atime)
402 def get_file_ctime_timedelta(filename: str) -> Optional[datetime.timedelta]:
403 return get_file_timestamp_timedelta(filename, lambda x: x.st_ctime)
406 def get_file_mtime_timedelta(filename: str) -> Optional[datetime.timedelta]:
407 return get_file_timestamp_timedelta(filename, lambda x: x.st_mtime)
410 def describe_file_timestamp(filename: str, extractor, *, brief=False) -> Optional[str]:
411 from datetime_utils import describe_duration, describe_duration_briefly
413 age = get_file_timestamp_age_seconds(filename, extractor)
417 return describe_duration_briefly(age)
419 return describe_duration(age)
422 def describe_file_atime(filename: str, *, brief=False) -> Optional[str]:
423 return describe_file_timestamp(filename, lambda x: x.st_atime, brief=brief)
426 def describe_file_ctime(filename: str, *, brief=False) -> Optional[str]:
427 return describe_file_timestamp(filename, lambda x: x.st_ctime, brief=brief)
430 def describe_file_mtime(filename: str, *, brief=False) -> Optional[str]:
431 return describe_file_timestamp(filename, lambda x: x.st_mtime, brief=brief)
434 def touch_file(filename: str, *, mode: Optional[int] = 0o666) -> bool:
435 return pathlib.Path(filename, mode=mode).touch()
438 def expand_globs(in_filename: str):
439 for filename in glob.glob(in_filename):
443 def get_files(directory: str):
444 for filename in os.listdir(directory):
445 full_path = join(directory, filename)
446 if isfile(full_path) and exists(full_path):
450 def get_directories(directory: str):
451 for d in os.listdir(directory):
452 full_path = join(directory, d)
453 if not isfile(full_path) and exists(full_path):
457 def get_files_recursive(directory: str):
458 for filename in get_files(directory):
460 for subdir in get_directories(directory):
461 for file_or_directory in get_files_recursive(subdir):
462 yield file_or_directory
465 class FileWriter(object):
466 def __init__(self, filename: str) -> None:
467 self.filename = filename
469 self.tempfile = f'{filename}-{uuid}.tmp'
472 def __enter__(self) -> io.TextIOWrapper:
473 assert not does_path_exist(self.tempfile)
474 self.handle = open(self.tempfile, mode="w")
477 def __exit__(self, exc_type, exc_val, exc_tb) -> bool:
478 if self.handle is not None:
480 cmd = f'/bin/mv -f {self.tempfile} {self.filename}'
483 raise Exception(f'{cmd} failed, exit value {ret>>8}')
487 if __name__ == '__main__':