Skip to content

Backend: add KIO backend for KDE platforms - #112

Open
glubsy wants to merge 2 commits into
arsenetar:masterfrom
glubsy:kio
Open

glubsy wants to merge 2 commits into
arsenetar:masterfrom
glubsy:kio

Conversation

@glubsy

@glubsy glubsy commented Aug 22, 2026

Copy link
Copy Markdown

Add a KDE-aware trash backend that uses kioclient/KIO on Linux when running in a KDE session and a usable KIO worker is available. KIO is more reliable when using BTRFS mounts, where GIO currently returns an error: "Trashing on system internal mounts is not supported".

Fixes #111

Add a KDE-aware trash backend that uses kioclient/KIO on Linux when running in a KDE session and a usable KIO worker is available.
KIO is more reliable when using BTRFS mounts, where GIO currently returns an
error: "Trashing on system internal mounts is not supported".
@arsenetar

arsenetar commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Gave this an AI review that raised a few things, and looking over them seem like several should be addressed:

🔴 Bugs / CI breakers

  1. test_send2trash_builds_kio_move_command will fail on Windows CI. The test suite runs on windows-latest (see default.yml matrix), and the test isn't platform-gated. On Windows, os.path.abspath("/tmp/send2trash test.txt") returns C:\tmp\send2trash test.txt, so the produced URL won't match the expected file:///tmp/send2trash%20test.txt. Other test modules guard with pytest.skip(..., allow_module_level=True) (e.g., test_plat_other.py); this file needs the same, or the path assertion must be made platform-neutral.
  2. Lint will fail: trailing whitespace (W291). The added line "XDG_CURRENT_DESKTOP", in _is_kde_session has a trailing space. The lint job runs flake8 with select = C,E,F,W,... (tox.ini), so this blocks CI.
  3. Non-UTF-8 filenames crash _path_to_url. preprocess_paths can yield bytes; os.fsdecode produces surrogate-escaped strings, and urllib.parse.quote() then raises UnicodeEncodeError (verified: 'utf-8' codec can't encode character '\udce9'). The existing plat_other.py backend deliberately supports such filenames (there are tests for them). Fix: quote the raw bytes, e.g. quote(os.fsencode(os.path.abspath(os.fsdecode(path)))) or pass errors="surrogateescape".

🟡 Design concerns

  1. Subprocess spawned at import time. is_available() runs kioclient stat trash:/ with a 2s timeout during import send2trash on every non-mac/win platform in a KDE session. That's a new import side effect: up to 2s of import latency and a process spawn, which can misbehave in sandboxed/headless environments. Consider deferring the probe to the first send2trash() call (lazy dispatch), as the import-time cost hits every consumer whether or not they trash anything.
  2. No TrashPermissionError mapping. plat_gio.py and plat_other raise TrashPermissionError for "can't trash here" cases; the KIO backend always raises bare OSError. Callers that catch TrashPermissionError to fall back to deletion will lose that behavior on KDE. Worth at least noting, ideally mapping known KIO error messages.
  3. ImportError for a missing executable (_kioclient) is unusual semantics. It's internal and handled, but if the cached binary disappears mid-session, send2trash() could leak an ImportError to callers. FileNotFoundError/OSError would be more conventional.

🟢 Minor

  1. Style: backslash line-continuations in the message = error.stderr.strip() \ ... block don't match the repo's black config (line-length = 120, pyproject.toml); black would rewrite these. Running black before pushing would normalize it.
  2. Tests replace os.environ wholesale via monkeypatch.setattr(plat_kio.os, "environ", {...}) — this patches the global os module. It works and is restored, but monkeypatch.setenv/delenv is the idiomatic, safer pattern.
  3. The selection logic in init.py is correct but convoluted (send2trash = None sentinel + nested try/else). A small _get_trash_impl() helper or early-return structure would read better; also, static type checkers will now infer send2trash: Optional[...].

Resolve and cache the trash backend on first use to avoid spawning
kioclient during import.

Preserve non-UTF-8 filename bytes in file URLs
and raise FileNotFoundError when kioclient is missing.

Gate KIO tests to Freedesktop platforms, isolate cached lookups and
environment variables, and cover lazy dispatch and backend fallbacks.
Normalize formatting and document KIO's error-mapping limitation.
@glubsy

glubsy commented Nov 14, 2026

Copy link
Copy Markdown
Author

Thanks for the review. Addressed the following:

  • Gated KIO tests to Freedesktop platforms.
  • Fixed trailing whitespace and normalized formatting with Black.
  • Preserved raw filesystem bytes when building URLs, including non-UTF-8 filenames.
  • Deferred backend selection and the KIO probe until the first send2trash() call, then cached the result.
  • Replaced ImportError with FileNotFoundError for a missing executable.
  • Switched environment mocks to monkeypatch.setenv/delenv and isolated cached lookups between tests.
  • Simplified backend selection with an early-return helper.

For TrashPermissionError, I documented the limitation rather than matching localized KIO messages. kioclient does not expose sufficiently specific structured errors to distinguish trash-directory permission failures reliably, so command failures still raise OSError.

Validation: 32 tests passed, 1 skipped; Black, flake8, and whitespace checks passed for the changed files.

I tested the changes with this small script (my /data mount is a BTRFS file system).

from pathlib import Path
from send2trash import send2trash

def main():
    path = Path("/data/test_file")
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("send2trash snippet test\n", encoding="utf-8")
    send2trash(path)

if __name__ == "__main__":
    main()

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

gio trash fails on BTRFS mounts

2 participants