Skip to content

Commit

Permalink
Core: Implement isfile API
Browse files Browse the repository at this point in the history
  • Loading branch information
yanghua committed Aug 26, 2024
1 parent e90e58a commit a5228cc
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
31 changes: 31 additions & 0 deletions tosfs/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,37 @@ def isdir(self, path: str) -> bool:
except Exception as e:
raise TosfsError(f"Tosfs failed with unknown error: {e}") from e

def isfile(self, path: str) -> bool:
"""Check if the path is a file.
Parameters
----------
path : str
The path to check.
Returns
-------
bool
True if the path is a file, False otherwise.
"""
if path.endswith("/"):
return False

bucket, key, _ = self._split_path(path)
try:
# Attempt to get the object metadata
self.tos_client.head_object(bucket, key)
return True
except tos.exceptions.TosClientError as e:
raise e
except tos.exceptions.TosServerError as e:
if e.status_code == SERVER_RESPONSE_CODE_NOT_FOUND:
return False
raise e
except Exception as e:
raise TosfsError(f"Tosfs failed with unknown error: {e}") from e

def _bucket_info(self, bucket: str) -> dict:
"""Get the information of a bucket.
Expand Down
10 changes: 10 additions & 0 deletions tosfs/tests/test_tosfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,14 @@ def test_isdir(tosfs: TosFileSystem, bucket: str, temporary_workspace: str) -> N
assert not tosfs.isdir(f"{bucket}/{temporary_workspace}/{file_name}")
assert not tosfs.isdir(f"{bucket}/{temporary_workspace}/{file_name}/")


def test_isfile(tosfs: TosFileSystem, bucket: str, temporary_workspace: str) -> None:
file_name = random_path()
tosfs.tos_client.put_object(bucket=bucket, key=f"{temporary_workspace}/{file_name}")
assert tosfs.isfile(f"{bucket}/{temporary_workspace}/{file_name}")
assert not tosfs.isfile(f"{bucket}/{temporary_workspace}/{file_name}/")
assert not tosfs.isfile(f"{bucket}/{temporary_workspace}/nonexistfile")
assert not tosfs.isfile(f"{bucket}/{temporary_workspace}")
assert not tosfs.isfile(f"{bucket}/{temporary_workspace}/")

tosfs._rm(f"{bucket}/{temporary_workspace}/{file_name}")

0 comments on commit a5228cc

Please sign in to comment.