Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
64 changes: 47 additions & 17 deletions fsspec/implementations/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,32 +266,62 @@ def _open(
**kwargs,
)

def _rm(self, path):
def rm(self, path, **kwargs):
self.rm_file(path, **kwargs)

def rm_file(self, path, branch=None, message=None, **kwargs):
"""
Remove a file from a specified branch using a given commit message.

Parameters
----------
path : str
The file's location relative to the repository root.
branch : str, optional
The branch containing the file. Defaults to the repository's default branch if not provided.
message : str, optional
The commit message for the deletion.
"""

if not self.username:
raise ValueError("Authentication required")

path = self._strip_protocol(path).lstrip("/")
path = self._strip_protocol(path)

# Get the file SHA
url = self.content_url.format(
# Attempt to get SHA from cache or Github API
sha = self._get_sha_from_cache(path)
if not sha:
url = self.content_url.format(
org=self.org, repo=self.repo, path=path.lstrip("/"), sha=self.root
)
r = requests.get(url, timeout=self.timeout, **self.kw)
if r.status_code == 404:
raise FileNotFoundError(path)
r.raise_for_status()
sha = r.json()["sha"]

# Delete the file
delete_url = self.content_url.format(
org=self.org, repo=self.repo, path=path, sha=self.root
)
r = requests.get(url, timeout=self.timeout, **self.kw)
if r.status_code == 404:
raise FileNotFoundError(path)
r.raise_for_status()
content_json = r.json()
sha = content_json["sha"]

# Delete the file using GitHub API
delete_url = url
data = {
"message": f"Delete {path}",
"message": message or f"Delete {path}",
"sha": sha,
"branch": self.root,
**({"branch": branch} if branch else {}),
}
r = requests.delete(delete_url, json=data, timeout=self.timeout, **self.kw)
if r.status_code not in (200, 204):
r.raise_for_status()
r.raise_for_status()

self.invalidate_cache(path)

def _get_sha_from_cache(self, path):
sha = None
for entries in self.dircache.values():
for entry in entries:
entry_path = entry.get("name")
if entry_path and entry_path == path and "sha" in entry:
sha = entry["sha"]
break
if sha:
break
return sha
2 changes: 1 addition & 1 deletion fsspec/implementations/tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,4 @@ def test_github_rm():
"github", org="mwaskom", repo="seaborn-data", username="user", token="token"
)
with pytest.raises(FileNotFoundError):
fs.rm("/this-file-doesnt-exist")
fs.rm("/this-file-doesnt-exist", branch="master", message="Delete my file")
Loading