Skip to content
Closed
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
47 changes: 32 additions & 15 deletions sshfs/spec.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import asyncio
import posixpath
import shlex
import stat
import weakref
from contextlib import AsyncExitStack, suppress
Expand Down Expand Up @@ -35,11 +34,13 @@


def _quote(path):
"""Quote a path for a POSIX shell as a command's file argument."""
"""Quote a str or bytes path for a POSIX shell, as bytes."""
if isinstance(path, str):
path = path.encode()
# Without "./", commands read "-r" as an option and "-" as stdin
if path.startswith("-"):
path = "./" + path
return shlex.quote(path)
if path.startswith(b"-"):
path = b"./" + path
return b"'" + path.replace(b"'", b"'\\''") + b"'"


class SSHFileSystem(AsyncFileSystem):
Expand Down Expand Up @@ -136,6 +137,14 @@ def _get_kwargs_from_urls(urlpath):
out.pop("protocol", None)
return out

@classmethod
def _parent(cls, path):
path = cls._strip_protocol(path)
# The same parents as fsspec's _parent gives. _strip_protocol keeps
# trailing slashes in bytes paths, so they are removed here.
sep = b"/" if isinstance(path, bytes) else "/"
return path.rstrip(sep).rpartition(sep)[0]

@wrap_exceptions
async def _connect(
self,
Expand Down Expand Up @@ -223,14 +232,15 @@ async def _info(self, path, **kwargs):
attributes = await channel.stat(path)

info = self._decode_attributes(attributes)
path = path.rstrip("/")
sep = b"/" if isinstance(path, bytes) else "/"
path = path.rstrip(sep)
if info["type"] == "directory":
path += "/"
path += sep
info["name"] = path
return info

@wrap_exceptions
async def _modified(self, path: str, **kwargs) -> datetime:
async def _modified(self, path: str | bytes, **kwargs) -> datetime:
path_info = await self._info(path)
return path_info["mtime"]

Expand Down Expand Up @@ -290,8 +300,7 @@ async def _get_file(
async def _cp_file(self, lpath, rpath, **kwargs):
lpath = self._strip_protocol(lpath)
rpath = self._strip_protocol(rpath)
cmd = f"cp {_quote(lpath)} {_quote(rpath)}"
await self._execute(cmd)
await self._execute_with_paths(b"cp", lpath, rpath)

@wrap_exceptions
async def _ls(self, path, detail=True, **kwargs):
Expand All @@ -301,7 +310,7 @@ async def _ls(self, path, detail=True, **kwargs):

infos = []
for file_attr in file_attrs:
if file_attr.filename in ["", ".", ".."]:
if file_attr.filename in ("", ".", "..", b"", b".", b".."):
continue
info = self._decode_attributes(file_attr.attrs)
info["name"] = posixpath.join(path, file_attr.filename)
Expand Down Expand Up @@ -381,16 +390,15 @@ async def _checksum(self, path):
path = self._strip_protocol(path)
system = await self._get_system()
if system == "Linux":
command = "md5sum"
program = b"md5sum"
part = 0
elif system == "Darwin":
command = "md5"
program = b"md5"
part = -1
else:
raise ValueError(f"{system!r} doesn't support checksum operation")

cmd = f"{command} {_quote(path)}"
result = await self._execute(cmd)
result = await self._execute_with_paths(program, path)

parts = result.stdout.strip().split()
assert len(parts) >= 1
Expand All @@ -416,6 +424,15 @@ async def _execute(self, *args, **kwargs):

execute = sync_wrapper(_execute)

async def _execute_with_paths(self, program, *paths):
"""Run a program with str or bytes paths as its arguments."""
# asyncssh sends a bytes command as is, so paths that aren't valid
# UTF-8 reach the shell unchanged.
command = b" ".join((program, *map(_quote, paths)))
# Output can include those paths, and failing to decode it strictly
# closes the SSH connection.
return await self._execute(command, errors="replace")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI-generated — Copilot] Logic / simplification / alternatives:

  • Undocumented asyncssh behavior & ProcessError.command type: SSHClientConnection.create_session / SSHClientChannel.create type command as Optional[str]; passing bytes works today because asyncssh.packet.String accepts bytes. Building bytes for str paths too also changes ProcessError.command from str to bytes for str callers. That's a reasonable trade-off for a single code path, though only encoding to bytes when a path is bytes would keep str callers on the documented str path.
  • Simplification (and synergy with fix: prefix paths starting with - with ./ in cp, md5sum and md5 #92): Passing the command binary (b"cp", b"md5sum", b"md5") and building b" ".join((command, *map(_quote, paths))) (or (command, b"--", *map(_quote, paths)) with fix: prefix paths starting with - with ./ in cp, md5sum and md5 #92) avoids %s format strings and centralizes -- in one place.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in cc78957: _execute_with_paths(program, *paths) joins the quoted paths to the program.

I kept bytes commands for str paths too, so there's one code path. asyncssh's String() accepts bytes, and every cp_file and checksum test sends one, so CI would catch an asyncssh change. ProcessError.command does become bytes, but it isn't part of the fsspec API.

#92 now uses a ./ prefix inside a _quote helper instead of --, because -- doesn't help with a bare -. Whichever PR merges second folds it into this _quote.


def _open(self, path, *args, **kwargs):
path = self._strip_protocol(path)
return SSHFile(self, path, *args, **kwargs)
Expand Down
Loading
Loading