Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core: Implement isfile API #33

Merged
merged 1 commit into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
yanghua marked this conversation as resolved.
Show resolved Hide resolved
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
12 changes: 12 additions & 0 deletions tosfs/tests/test_tosfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,15 @@ def test_isdir(tosfs: TosFileSystem, bucket: str, temporary_workspace: str) -> N
assert not tosfs.isdir(f"{bucket}/{temporary_workspace}/{file_name}/")

tosfs._rm(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}")