summaryrefslogtreecommitdiff
path: root/lib/spack/llnl/util
diff options
context:
space:
mode:
Diffstat (limited to 'lib/spack/llnl/util')
-rw-r--r--lib/spack/llnl/util/filesystem.py25
1 files changed, 25 insertions, 0 deletions
diff --git a/lib/spack/llnl/util/filesystem.py b/lib/spack/llnl/util/filesystem.py
index 330ee35911..4dfea7975d 100644
--- a/lib/spack/llnl/util/filesystem.py
+++ b/lib/spack/llnl/util/filesystem.py
@@ -2630,3 +2630,28 @@ def temporary_dir(
yield tmp_dir
finally:
remove_directory_contents(tmp_dir)
+
+
+def filesummary(path, print_bytes=16) -> Tuple[int, bytes]:
+ """Create a small summary of the given file. Does not error
+ when file does not exist.
+
+ Args:
+ print_bytes (int): Number of bytes to print from start/end of file
+
+ Returns:
+ Tuple of size and byte string containing first n .. last n bytes.
+ Size is 0 if file cannot be read."""
+ try:
+ n = print_bytes
+ with open(path, "rb") as f:
+ size = os.fstat(f.fileno()).st_size
+ if size <= 2 * n:
+ short_contents = f.read(2 * n)
+ else:
+ short_contents = f.read(n)
+ f.seek(-n, 2)
+ short_contents += b"..." + f.read(n)
+ return size, short_contents
+ except OSError:
+ return 0, b""