Skip to content

epath.Path.replace() silently destroys the destination file on Windows when the source is a directory #816

Open

Description

@MohammedAlkindi

_OsPathBackend.replace() guards only the destination:

def replace(self, path: PathLike, dst: PathLike) -> None:
  if self.isdir(dst):
    raise IsADirectoryError(f'Cannot overwrite: {dst} is a directory')
  os.replace(path, dst)

Nothing checks for source is a directory, destination is an existing file. On Windows os.replace accepts that, and the destination file's contents are gone.

# Windows 11, CPython 3.13.13
os.mkdir(srcdir)
open(os.path.join(srcdir, 'payload.txt'), 'w').write('inside the source dir')
open(dst, 'w').write('IRREPLACEABLE DESTINATION CONTENT')

os.replace(srcdir, dst)      # returns, no exception
os.path.isdir(dst)           # True
os.listdir(dst)              # ['payload.txt'] - original bytes gone

On POSIX rename(2) returns ENOTDIR itself, so the missing guard never mattered there, and pytest_and_autopublish.yml runs ubuntu-latest only.

The sibling _FileSystemSpecBackend.replace() already has the check at backend.py:548-551, so the two backends currently disagree about the same Backend contract.

test_backend[_test_replace] already asserts the correct behaviour and reports SUBFAILED[os/dst-folder0-file.txt] - Failed: DID NOT RAISE NotADirectoryError. It has never run on Windows, because the module fails collection there on import grp.

Two things I hit attempting a patch, which is why this is an issue and not a PR:

exists and isdir delegate straight to os.path.exists and os.path.isdir (backend.py:135-139), and both dereference symlinks where rename(2) does not. Copying the sibling's guard verbatim would raise for a symlink-to-directory source, which POSIX permits. Adding not os.path.islink(path) restores that, but Windows directory symlinks carry FILE_ATTRIBUTE_DIRECTORY on the link entry itself, so I could not establish the carve-out is safe on the platform the guard exists for. Creating a symlink here needs a privilege this account lacks (WinError 1314).

Separately, backend.py:217-218 raises for any directory dst, while rename(2) succeeds onto an empty one.

I have no Linux or macOS machine, so every POSIX statement above is read from the contract rather than measured.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions