Skip to content

Commit

Permalink
Simplify File artifact implementation (#192)
Browse files Browse the repository at this point in the history
  • Loading branch information
themylogin authored May 14, 2024
1 parent d4e5d65 commit 5924ebb
Showing 1 changed file with 10 additions and 21 deletions.
31 changes: 10 additions & 21 deletions ixdiagnose/artifacts/items/file.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import contextlib
import os
import pathlib
import shutil

from ixdiagnose.utils.io import truncate_file
Expand All @@ -13,38 +13,27 @@ class File(Item):
def __init__(self, name: str, max_size: Optional[int] = None, truncate: Optional[bool] = True):
super().__init__(name, max_size)
self.truncate: bool = truncate
self.file_descriptor: Optional[int] = None

def initialize_context(self, item_path: str):
self.file_descriptor = os.open(item_path, os.O_RDONLY | os.O_NOFOLLOW)

def size(self, item_path: str) -> int:
return os.fstat(self.file_descriptor).st_size
try:
return pathlib.Path(item_path).lstat().st_size
except Exception:
return 0

def copy_impl(self, item_path: str, destination_path: str) -> list:
shutil.copy2(self.get_fd_path(), destination_path)
return [item_path]

def get_fd_path(self) -> str:
return os.path.join('/proc/self/fd', str(self.file_descriptor))
try:
shutil.copy2(item_path, destination_path)
return [item_path]
except Exception:
return []

def to_be_copied_checks(self, item_path: str) -> Tuple[bool, Optional[str]]:
to_copy, error = (True, None) if os.path.isfile(item_path) else (False, f'{item_path!r} is not a file')
if to_copy and not self.truncate:
return self.size_check(item_path)
return to_copy, error

def close_descriptor(self):
if self.file_descriptor:
with contextlib.suppress(OSError):
os.close(self.file_descriptor)
self.file_descriptor = None

def __del__(self):
self.close_descriptor()

def post_copy_hook(self, destination_path: str):
self.close_descriptor()
if self.max_size is None:
return

Expand Down

0 comments on commit 5924ebb

Please sign in to comment.