mirror of
https://github.com/arsenetar/send2trash.git
synced 2026-01-25 16:11:39 +00:00
Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
484913ba0f
|
|||
|
d249f0106b
|
|||
|
94e1ec007a
|
|||
|
84c220cbd9
|
|||
|
6612545110
|
|||
|
d52b4f206c
|
|||
|
33171dde82
|
|||
| 077598d2ce | |||
|
|
436686bf0f | ||
|
23ce7b8c16
|
|||
|
9b0d5796c1
|
|||
|
c8bcaea1e8
|
|||
| 530e9b4bc6 | |||
|
10c7693d11
|
|||
|
356509120b
|
|||
|
f9fcdb8d8c
|
|||
|
af0c1ba704
|
|||
|
37be84d46e
|
|||
|
9f76fbf036
|
|||
|
a324923ffa
|
|||
|
dbdcce8b04
|
|||
|
054d56c564
|
|||
|
33ed07811b
|
|||
| 5d3835735e | |||
|
|
741c7ad51f | ||
| 2eb3242cd9 | |||
| 60bcb2c834 | |||
| c411f4eae4 | |||
| f64c69f905 | |||
|
00dfe77e40
|
|||
| 16a7115ff1 | |||
| ec73b44c43 | |||
|
|
f62b4f1ffd | ||
|
|
38ae2b63d2 | ||
|
|
cd8d9fb95e | ||
|
|
20bbab0b4c |
25
.travis.yml
25
.travis.yml
@@ -3,26 +3,31 @@ matrix:
|
||||
include:
|
||||
- os: windows
|
||||
language: sh
|
||||
python: 3
|
||||
python: "3.8"
|
||||
env: "PATH=/c/Python38:/c/Python38/Scripts:$PATH"
|
||||
# Perform the manual steps on windows to install python3
|
||||
before_install:
|
||||
- choco install python3 --params "/InstallDir:C:\Python"
|
||||
- export PATH="/c/Python:/c/Python/Scripts:$PATH"
|
||||
- choco install python --version=3.8.6
|
||||
- python -m pip install --upgrade pip
|
||||
- python -m pip install pywin32
|
||||
before_script:
|
||||
- export TOXENV=py3-win
|
||||
|
||||
- export TOXENV=py38
|
||||
- python: "2.7"
|
||||
- python: "3.4"
|
||||
- python: "3.5"
|
||||
- python: "3.6"
|
||||
# Obtain Python 3.7 from xenial as per https://github.com/travis-ci/travis-ci/issues/9815
|
||||
- python: "3.7"
|
||||
dist: xenial
|
||||
- python: "3.8"
|
||||
- python: "3.9"
|
||||
- python: "nightly" # 3.10
|
||||
before_script:
|
||||
- export TOXENV=py310
|
||||
- python: "2.7"
|
||||
arch: ppc64le
|
||||
- python: "3.6"
|
||||
arch: ppc64le
|
||||
install:
|
||||
- pip install tox
|
||||
- python -m pip install tox
|
||||
before_script:
|
||||
- export TOXENV=$(echo py$TRAVIS_PYTHON_VERSION | tr -d .)
|
||||
script:
|
||||
- tox
|
||||
- python -m tox
|
||||
|
||||
29
CHANGES.rst
29
CHANGES.rst
@@ -1,6 +1,35 @@
|
||||
Changes
|
||||
=======
|
||||
|
||||
Version 1.8.0 -- 2021/08/08
|
||||
---------------------------
|
||||
|
||||
* Add compatibility with pathlib paths (#49)
|
||||
* Fix thread compatibility of modern windows implementation (#59)
|
||||
* Fix handling of UNC names in legacy windows implementation (#57)
|
||||
|
||||
Version 1.7.1 -- 2021/06/21
|
||||
---------------------------
|
||||
|
||||
* Release stable version with changes from last 3 releases
|
||||
* Fix handling of UNC names (#57)
|
||||
|
||||
Version 1.7.0a1 -- 2021/05/14
|
||||
-----------------------------
|
||||
|
||||
* Changed conditional for when to try to use pyobjc version (#51)
|
||||
|
||||
Version 1.7.0a0 -- 2021/04/20
|
||||
-----------------------------
|
||||
|
||||
* Add console_script entry point (#50)
|
||||
* Increased python CI versions (#52, #54)
|
||||
* Fix minor issue in setup.py (#53)
|
||||
* Fix issue with windows tests importing modules on non-windows (#55)
|
||||
* Unit test cleanups, rewrites, and flake8 cleanups
|
||||
* Windows: Fix legacy windows platform for multi-byte unicode and add tests
|
||||
* macOS: Add alternative pyobjc version to potentially improve compatibility (#51)
|
||||
|
||||
Version 1.6.0b1 -- 2020/06/18
|
||||
-----------------------------
|
||||
|
||||
|
||||
18
README.rst
18
README.rst
@@ -3,11 +3,11 @@ Send2Trash -- Send files to trash on all platforms
|
||||
==================================================
|
||||
|
||||
Send2Trash is a small package that sends files to the Trash (or Recycle Bin) *natively* and on
|
||||
*all platforms*. On OS X, it uses native ``FSMoveObjectToTrashSync`` Cocoa calls. On Windows, it
|
||||
uses native ``IFileOperation`` call if on Vista or newer and pywin32 is installed or falls back
|
||||
to ``SHFileOperation`` calls. On other platforms, if `PyGObject`_ and `GIO`_ are available, it
|
||||
will use this. Otherwise, it will fallback to its own implementation of the `trash specifications
|
||||
from freedesktop.org`_.
|
||||
*all platforms*. On OS X, it uses native ``FSMoveObjectToTrashSync`` Cocoa calls or can use pyobjc
|
||||
with NSFileManager. On Windows, it uses native ``IFileOperation`` call if on Vista or newer and
|
||||
pywin32 is installed or falls back to ``SHFileOperation`` calls. On other platforms, if `PyGObject`_
|
||||
and `GIO`_ are available, it will use this. Otherwise, it will fallback to its own implementation of
|
||||
the `trash specifications from freedesktop.org`_.
|
||||
|
||||
``ctypes`` is used to access native libraries, so no compilation is necessary.
|
||||
|
||||
@@ -22,9 +22,13 @@ issues and fixes would be most appreciated.
|
||||
Installation
|
||||
------------
|
||||
|
||||
You can download it with pip::
|
||||
You can download it with pip:
|
||||
|
||||
pip install Send2Trash
|
||||
python -m pip install -U send2trash
|
||||
|
||||
To install with pywin32 or pyobjc required specify the extra `nativeLib`:
|
||||
|
||||
python -m pip install -U send2trash[nativeLib]
|
||||
|
||||
or you can download the source from http://github.com/arsenetar/send2trash and install it with::
|
||||
|
||||
|
||||
105
send2trash/IFileOperationProgressSink.py
Normal file
105
send2trash/IFileOperationProgressSink.py
Normal file
@@ -0,0 +1,105 @@
|
||||
# Sample implementation of IFileOperationProgressSink that just prints
|
||||
# some basic info
|
||||
|
||||
import pythoncom
|
||||
from win32com.shell import shell, shellcon
|
||||
from win32com.server.policy import DesignatedWrapPolicy
|
||||
|
||||
|
||||
class FileOperationProgressSink(DesignatedWrapPolicy):
|
||||
_com_interfaces_ = [shell.IID_IFileOperationProgressSink]
|
||||
_public_methods_ = [
|
||||
"StartOperations",
|
||||
"FinishOperations",
|
||||
"PreRenameItem",
|
||||
"PostRenameItem",
|
||||
"PreMoveItem",
|
||||
"PostMoveItem",
|
||||
"PreCopyItem",
|
||||
"PostCopyItem",
|
||||
"PreDeleteItem",
|
||||
"PostDeleteItem",
|
||||
"PreNewItem",
|
||||
"PostNewItem",
|
||||
"UpdateProgress",
|
||||
"ResetTimer",
|
||||
"PauseTimer",
|
||||
"ResumeTimer",
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
self._wrap_(self)
|
||||
self.newItem = None
|
||||
|
||||
def PreDeleteItem(self, flags, item):
|
||||
# Can detect cases where to stop via flags and condition below, however the operation
|
||||
# does not actual stop, we can resort to raising an exception as that does stop things
|
||||
# but that may need some additional considerations before implementing.
|
||||
return (
|
||||
0 if flags & shellcon.TSF_DELETE_RECYCLE_IF_POSSIBLE else 0x80004005
|
||||
) # S_OK, or E_FAIL
|
||||
|
||||
def PostDeleteItem(self, flags, item, hrDelete, newlyCreated):
|
||||
if newlyCreated:
|
||||
self.newItem = newlyCreated.GetDisplayName(shellcon.SHGDN_FORPARSING)
|
||||
|
||||
def StartOperations(self):
|
||||
pass
|
||||
|
||||
def FinishOperations(self, Result):
|
||||
pass
|
||||
|
||||
def PreRenameItem(self, Flags, Item, NewName):
|
||||
pass
|
||||
|
||||
def PostRenameItem(self, Flags, Item, NewName, hrRename, NewlyCreated):
|
||||
pass
|
||||
|
||||
def PreMoveItem(self, Flags, Item, DestinationFolder, NewName):
|
||||
pass
|
||||
|
||||
def PostMoveItem(
|
||||
self, Flags, Item, DestinationFolder, NewName, hrMove, NewlyCreated
|
||||
):
|
||||
pass
|
||||
|
||||
def PreCopyItem(self, Flags, Item, DestinationFolder, NewName):
|
||||
pass
|
||||
|
||||
def PostCopyItem(
|
||||
self, Flags, Item, DestinationFolder, NewName, hrCopy, NewlyCreated
|
||||
):
|
||||
pass
|
||||
|
||||
def PreNewItem(self, Flags, DestinationFolder, NewName):
|
||||
pass
|
||||
|
||||
def PostNewItem(
|
||||
self,
|
||||
Flags,
|
||||
DestinationFolder,
|
||||
NewName,
|
||||
TemplateName,
|
||||
FileAttributes,
|
||||
hrNew,
|
||||
NewItem,
|
||||
):
|
||||
pass
|
||||
|
||||
def UpdateProgress(self, WorkTotal, WorkSoFar):
|
||||
pass
|
||||
|
||||
def ResetTimer(self):
|
||||
pass
|
||||
|
||||
def PauseTimer(self):
|
||||
pass
|
||||
|
||||
def ResumeTimer(self):
|
||||
pass
|
||||
|
||||
|
||||
def CreateSink():
|
||||
return pythoncom.WrapObject(
|
||||
FileOperationProgressSink(), shell.IID_IFileOperationProgressSink
|
||||
)
|
||||
@@ -2,7 +2,7 @@ import errno
|
||||
from .compat import PY3
|
||||
|
||||
if PY3:
|
||||
_permission_error = PermissionError
|
||||
_permission_error = PermissionError # noqa: F821
|
||||
else:
|
||||
_permission_error = OSError
|
||||
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
|
||||
from gi.repository import GObject, Gio
|
||||
from .exceptions import TrashPermissionError
|
||||
from .util import preprocess_paths
|
||||
|
||||
|
||||
def send2trash(paths):
|
||||
if not isinstance(paths, list):
|
||||
paths = [paths]
|
||||
paths = preprocess_paths(paths)
|
||||
for path in paths:
|
||||
try:
|
||||
f = Gio.File.new_for_path(path)
|
||||
|
||||
@@ -4,53 +4,17 @@
|
||||
# which should be included with this package. The terms are also available at
|
||||
# http://www.hardcoded.net/licenses/bsd_license
|
||||
|
||||
from __future__ import unicode_literals
|
||||
from platform import mac_ver
|
||||
from sys import version_info
|
||||
|
||||
from ctypes import cdll, byref, Structure, c_char, c_char_p
|
||||
from ctypes.util import find_library
|
||||
|
||||
from .compat import binary_type
|
||||
|
||||
Foundation = cdll.LoadLibrary(find_library("Foundation"))
|
||||
CoreServices = cdll.LoadLibrary(find_library("CoreServices"))
|
||||
|
||||
GetMacOSStatusCommentString = Foundation.GetMacOSStatusCommentString
|
||||
GetMacOSStatusCommentString.restype = c_char_p
|
||||
FSPathMakeRefWithOptions = CoreServices.FSPathMakeRefWithOptions
|
||||
FSMoveObjectToTrashSync = CoreServices.FSMoveObjectToTrashSync
|
||||
|
||||
kFSPathMakeRefDefaultOptions = 0
|
||||
kFSPathMakeRefDoNotFollowLeafSymlink = 0x01
|
||||
|
||||
kFSFileOperationDefaultOptions = 0
|
||||
kFSFileOperationOverwrite = 0x01
|
||||
kFSFileOperationSkipSourcePermissionErrors = 0x02
|
||||
kFSFileOperationDoNotMoveAcrossVolumes = 0x04
|
||||
kFSFileOperationSkipPreflight = 0x08
|
||||
|
||||
|
||||
class FSRef(Structure):
|
||||
_fields_ = [("hidden", c_char * 80)]
|
||||
|
||||
|
||||
def check_op_result(op_result):
|
||||
if op_result:
|
||||
msg = GetMacOSStatusCommentString(op_result).decode("utf-8")
|
||||
raise OSError(msg)
|
||||
|
||||
|
||||
def send2trash(paths):
|
||||
if not isinstance(paths, list):
|
||||
paths = [paths]
|
||||
paths = [
|
||||
path.encode("utf-8") if not isinstance(path, binary_type) else path
|
||||
for path in paths
|
||||
]
|
||||
for path in paths:
|
||||
fp = FSRef()
|
||||
opts = kFSPathMakeRefDoNotFollowLeafSymlink
|
||||
op_result = FSPathMakeRefWithOptions(path, opts, byref(fp), None)
|
||||
check_op_result(op_result)
|
||||
opts = kFSFileOperationDefaultOptions
|
||||
op_result = FSMoveObjectToTrashSync(byref(fp), None, opts)
|
||||
check_op_result(op_result)
|
||||
# NOTE: version of pyobjc only supports python >= 3.6 and 10.9+
|
||||
macos_ver = tuple(int(part) for part in mac_ver()[0].split("."))
|
||||
if version_info >= (3, 6) and macos_ver >= (10, 9):
|
||||
try:
|
||||
from .plat_osx_pyobjc import send2trash
|
||||
except ImportError:
|
||||
# Try to fall back to ctypes version, although likely problematic still
|
||||
from .plat_osx_ctypes import send2trash
|
||||
else:
|
||||
# Just use the old version otherwise
|
||||
from .plat_osx_ctypes import send2trash # noqa: F401
|
||||
|
||||
56
send2trash/plat_osx_ctypes.py
Normal file
56
send2trash/plat_osx_ctypes.py
Normal file
@@ -0,0 +1,56 @@
|
||||
# Copyright 2017 Virgil Dupras
|
||||
|
||||
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
|
||||
# which should be included with this package. The terms are also available at
|
||||
# http://www.hardcoded.net/licenses/bsd_license
|
||||
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from ctypes import cdll, byref, Structure, c_char, c_char_p
|
||||
from ctypes.util import find_library
|
||||
|
||||
from .compat import binary_type
|
||||
from .util import preprocess_paths
|
||||
|
||||
Foundation = cdll.LoadLibrary(find_library("Foundation"))
|
||||
CoreServices = cdll.LoadLibrary(find_library("CoreServices"))
|
||||
|
||||
GetMacOSStatusCommentString = Foundation.GetMacOSStatusCommentString
|
||||
GetMacOSStatusCommentString.restype = c_char_p
|
||||
FSPathMakeRefWithOptions = CoreServices.FSPathMakeRefWithOptions
|
||||
FSMoveObjectToTrashSync = CoreServices.FSMoveObjectToTrashSync
|
||||
|
||||
kFSPathMakeRefDefaultOptions = 0
|
||||
kFSPathMakeRefDoNotFollowLeafSymlink = 0x01
|
||||
|
||||
kFSFileOperationDefaultOptions = 0
|
||||
kFSFileOperationOverwrite = 0x01
|
||||
kFSFileOperationSkipSourcePermissionErrors = 0x02
|
||||
kFSFileOperationDoNotMoveAcrossVolumes = 0x04
|
||||
kFSFileOperationSkipPreflight = 0x08
|
||||
|
||||
|
||||
class FSRef(Structure):
|
||||
_fields_ = [("hidden", c_char * 80)]
|
||||
|
||||
|
||||
def check_op_result(op_result):
|
||||
if op_result:
|
||||
msg = GetMacOSStatusCommentString(op_result).decode("utf-8")
|
||||
raise OSError(msg)
|
||||
|
||||
|
||||
def send2trash(paths):
|
||||
paths = preprocess_paths(paths)
|
||||
paths = [
|
||||
path.encode("utf-8") if not isinstance(path, binary_type) else path
|
||||
for path in paths
|
||||
]
|
||||
for path in paths:
|
||||
fp = FSRef()
|
||||
opts = kFSPathMakeRefDoNotFollowLeafSymlink
|
||||
op_result = FSPathMakeRefWithOptions(path, opts, byref(fp), None)
|
||||
check_op_result(op_result)
|
||||
opts = kFSFileOperationDefaultOptions
|
||||
op_result = FSMoveObjectToTrashSync(byref(fp), None, opts)
|
||||
check_op_result(op_result)
|
||||
29
send2trash/plat_osx_pyobjc.py
Normal file
29
send2trash/plat_osx_pyobjc.py
Normal file
@@ -0,0 +1,29 @@
|
||||
# Copyright 2017 Virgil Dupras
|
||||
|
||||
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
|
||||
# which should be included with this package. The terms are also available at
|
||||
# http://www.hardcoded.net/licenses/bsd_license
|
||||
|
||||
from Foundation import NSFileManager, NSURL
|
||||
from .compat import text_type
|
||||
from .util import preprocess_paths
|
||||
|
||||
|
||||
def check_op_result(op_result):
|
||||
# First value will be false on failure
|
||||
if not op_result[0]:
|
||||
# Error is in third value, localized failure reason matchs ctypes version
|
||||
raise OSError(op_result[2].localizedFailureReason())
|
||||
|
||||
|
||||
def send2trash(paths):
|
||||
paths = preprocess_paths(paths)
|
||||
paths = [
|
||||
path.decode("utf-8") if not isinstance(path, text_type) else path
|
||||
for path in paths
|
||||
]
|
||||
for path in paths:
|
||||
file_url = NSURL.fileURLWithPath_(path)
|
||||
fm = NSFileManager.defaultManager()
|
||||
op_result = fm.trashItemAtURL_resultingItemURL_error_(file_url, None, None)
|
||||
check_op_result(op_result)
|
||||
@@ -30,6 +30,7 @@ except ImportError:
|
||||
from urllib import quote
|
||||
|
||||
from .compat import text_type, environb
|
||||
from .util import preprocess_paths
|
||||
from .exceptions import TrashPermissionError
|
||||
|
||||
try:
|
||||
@@ -111,10 +112,9 @@ def trash_move(src, dst, topdir=None):
|
||||
check_create(filespath)
|
||||
check_create(infopath)
|
||||
|
||||
os.rename(src, op.join(filespath, destname))
|
||||
f = open(op.join(infopath, destname + INFO_SUFFIX), "w")
|
||||
with open(op.join(infopath, destname + INFO_SUFFIX), "w") as f:
|
||||
f.write(info_for(src, topdir))
|
||||
f.close()
|
||||
os.rename(src, op.join(filespath, destname))
|
||||
|
||||
|
||||
def find_mount_point(path):
|
||||
@@ -173,8 +173,7 @@ def get_dev(path):
|
||||
|
||||
|
||||
def send2trash(paths):
|
||||
if not isinstance(paths, list):
|
||||
paths = [paths]
|
||||
paths = preprocess_paths(paths)
|
||||
for path in paths:
|
||||
if isinstance(path, text_type):
|
||||
path_b = fsencode(path)
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
from __future__ import unicode_literals
|
||||
import os.path as op
|
||||
from .compat import text_type
|
||||
from .util import preprocess_paths
|
||||
|
||||
from ctypes import (
|
||||
windll,
|
||||
Structure,
|
||||
@@ -51,23 +53,57 @@ FOF_ALLOWUNDO = 64
|
||||
FOF_NOERRORUI = 1024
|
||||
|
||||
|
||||
def prefix_and_path(path):
|
||||
r"""Guess the long-path prefix based on the kind of *path*.
|
||||
Local paths (C:\folder\file.ext) and UNC names (\\server\folder\file.ext)
|
||||
are handled.
|
||||
|
||||
Return a tuple of the long-path prefix and the prefixed path.
|
||||
"""
|
||||
prefix, long_path = "\\\\?\\", path
|
||||
|
||||
if not path.startswith(prefix):
|
||||
if path.startswith("\\\\"):
|
||||
# Likely a UNC name
|
||||
prefix = "\\\\?\\UNC"
|
||||
long_path = prefix + path[1:]
|
||||
else:
|
||||
# Likely a local path
|
||||
long_path = prefix + path
|
||||
elif path.startswith(prefix + "UNC\\"):
|
||||
# UNC name with long-path prefix
|
||||
prefix = "\\\\?\\UNC"
|
||||
|
||||
return prefix, long_path
|
||||
|
||||
|
||||
def get_awaited_path_from_prefix(prefix, path):
|
||||
"""Guess the correct path to pass to the SHFileOperationW() call.
|
||||
The long-path prefix must be removed, so we should take care of
|
||||
different long-path prefixes.
|
||||
"""
|
||||
if prefix == "\\\\?\\UNC":
|
||||
# We need to prepend a backslash for UNC names, as it was removed
|
||||
# in prefix_and_path().
|
||||
return "\\" + path[len(prefix) :]
|
||||
return path[len(prefix) :]
|
||||
|
||||
|
||||
def get_short_path_name(long_name):
|
||||
if not long_name.startswith("\\\\?\\"):
|
||||
long_name = "\\\\?\\" + long_name
|
||||
buf_size = GetShortPathNameW(long_name, None, 0)
|
||||
prefix, long_path = prefix_and_path(long_name)
|
||||
buf_size = GetShortPathNameW(long_path, None, 0)
|
||||
# FIX: https://github.com/hsoft/send2trash/issues/31
|
||||
# If buffer size is zero, an error has occurred.
|
||||
if not buf_size:
|
||||
err_no = GetLastError()
|
||||
raise WindowsError(err_no, FormatError(err_no), long_name[4:])
|
||||
raise WindowsError(err_no, FormatError(err_no), long_path)
|
||||
output = create_unicode_buffer(buf_size)
|
||||
GetShortPathNameW(long_name, output, buf_size)
|
||||
return output.value[4:] # Remove '\\?\' for SHFileOperationW
|
||||
GetShortPathNameW(long_path, output, buf_size)
|
||||
return get_awaited_path_from_prefix(prefix, output.value)
|
||||
|
||||
|
||||
def send2trash(paths):
|
||||
if not isinstance(paths, list):
|
||||
paths = [paths]
|
||||
paths = preprocess_paths(paths)
|
||||
# convert data type
|
||||
paths = [
|
||||
text_type(path, "mbcs") if not isinstance(path, text_type) else path
|
||||
@@ -77,8 +113,6 @@ def send2trash(paths):
|
||||
paths = [op.abspath(path) if not op.isabs(path) else path for path in paths]
|
||||
# get short path to handle path length issues
|
||||
paths = [get_short_path_name(path) for path in paths]
|
||||
# convert to a single string of null terminated paths
|
||||
paths = "\0".join(paths)
|
||||
fileop = SHFILEOPSTRUCTW()
|
||||
fileop.hwnd = 0
|
||||
fileop.wFunc = FO_DELETE
|
||||
@@ -93,7 +127,15 @@ def send2trash(paths):
|
||||
# NOTE: based on how python allocates memory for these types they should
|
||||
# always be zero, if this is ever not true we can go back to explicitly
|
||||
# setting the last two characters to null using buffer[index] = '\0'.
|
||||
buffer = create_unicode_buffer(paths, len(paths) + 2)
|
||||
# Additional note on another issue here, unicode_buffer expects length in
|
||||
# bytes essentially, so having multi-byte characters causes issues if just
|
||||
# passing pythons string length. Instead of dealing with this difference we
|
||||
# just create a buffer then a new one with an extra null. Since the non-length
|
||||
# specified version apparently stops after the first null, join with a space first.
|
||||
buffer = create_unicode_buffer(" ".join(paths))
|
||||
# convert to a single string of null terminated paths
|
||||
path_string = "\0".join(paths)
|
||||
buffer = create_unicode_buffer(path_string, len(buffer) + 1)
|
||||
fileop.pFrom = LPCWSTR(addressof(buffer))
|
||||
fileop.pTo = None
|
||||
fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
|
||||
|
||||
@@ -7,15 +7,16 @@
|
||||
from __future__ import unicode_literals
|
||||
import os.path as op
|
||||
from .compat import text_type
|
||||
from .util import preprocess_paths
|
||||
from platform import version
|
||||
import pythoncom
|
||||
import pywintypes
|
||||
from win32com.shell import shell, shellcon
|
||||
from .IFileOperationProgressSink import CreateSink
|
||||
|
||||
|
||||
def send2trash(paths):
|
||||
if not isinstance(paths, list):
|
||||
paths = [paths]
|
||||
paths = preprocess_paths(paths)
|
||||
# convert data type
|
||||
paths = [
|
||||
text_type(path, "mbcs") if not isinstance(path, text_type) else path
|
||||
@@ -25,6 +26,8 @@ def send2trash(paths):
|
||||
paths = [op.abspath(path) if not op.isabs(path) else path for path in paths]
|
||||
# remove the leading \\?\ if present
|
||||
paths = [path[4:] if path.startswith("\\\\?\\") else path for path in paths]
|
||||
# Need to initialize the com before using
|
||||
pythoncom.CoInitialize()
|
||||
# create instance of file operation object
|
||||
fileop = pythoncom.CoCreateInstance(
|
||||
shell.CLSID_FileOperation, None, pythoncom.CLSCTX_ALL, shell.IID_IFileOperation,
|
||||
@@ -50,10 +53,11 @@ def send2trash(paths):
|
||||
# actually try to perform the operation, this section may throw a
|
||||
# pywintypes.com_error which does not seem to create as nice of an
|
||||
# error as OSError so wrapping with try to convert
|
||||
sink = CreateSink()
|
||||
try:
|
||||
for path in paths:
|
||||
item = shell.SHCreateItemFromParsingName(path, None, shell.IID_IShellItem)
|
||||
fileop.DeleteItem(item)
|
||||
fileop.DeleteItem(item, sink)
|
||||
result = fileop.PerformOperations()
|
||||
aborted = fileop.GetAnyOperationsAborted()
|
||||
# if non-zero result or aborted throw an exception
|
||||
@@ -63,3 +67,6 @@ def send2trash(paths):
|
||||
# convert to standard OS error, allows other code to get a
|
||||
# normal errno
|
||||
raise OSError(None, error.strerror, path, error.hresult)
|
||||
finally:
|
||||
# Need to make sure we call this once fore every init
|
||||
pythoncom.CoUninitialize()
|
||||
|
||||
16
send2trash/util.py
Normal file
16
send2trash/util.py
Normal file
@@ -0,0 +1,16 @@
|
||||
# encoding: utf-8
|
||||
# Copyright 2017 Virgil Dupras
|
||||
|
||||
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
|
||||
# which should be included with this package. The terms are also available at
|
||||
# http://www.hardcoded.net/licenses/bsd_license
|
||||
|
||||
|
||||
def preprocess_paths(paths):
|
||||
if not isinstance(paths, list):
|
||||
paths = [paths]
|
||||
# Convert items such as pathlib paths to strings
|
||||
paths = [
|
||||
path.__fspath__() if hasattr(path, "__fspath__") else path for path in paths
|
||||
]
|
||||
return paths
|
||||
20
setup.py
20
setup.py
@@ -14,16 +14,17 @@ CLASSIFIERS = [
|
||||
"Programming Language :: Python :: 3.6",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Topic :: Desktop Environment :: File Managers",
|
||||
]
|
||||
|
||||
LONG_DESCRIPTION = (
|
||||
open("README.rst", "rt").read() + "\n\n" + open("CHANGES.rst", "rt").read()
|
||||
)
|
||||
with open("README.rst", "rt") as f1, open("CHANGES.rst", "rt") as f2:
|
||||
LONG_DESCRIPTION = f1.read() + "\n\n" + f2.read()
|
||||
|
||||
setup(
|
||||
name="Send2Trash",
|
||||
version="1.6.0b1",
|
||||
version="1.8.0",
|
||||
author="Andrew Senetar",
|
||||
author_email="arsenetar@voltaicideas.net",
|
||||
packages=["send2trash"],
|
||||
@@ -33,7 +34,16 @@ setup(
|
||||
license="BSD License",
|
||||
description="Send file to trash natively under Mac OS X, Windows and Linux.",
|
||||
long_description=LONG_DESCRIPTION,
|
||||
long_description_content_type="text/x-rst",
|
||||
classifiers=CLASSIFIERS,
|
||||
extras_require={"win32": ["pywin32"]},
|
||||
extras_require={
|
||||
"win32": ['pywin32; sys_platform == "win32"'],
|
||||
"objc": ['pyobjc-framework-Cocoa; sys_platform == "darwin"'],
|
||||
"nativeLib": [
|
||||
'pywin32; sys_platform == "win32"',
|
||||
'pyobjc-framework-Cocoa; sys_platform == "darwin"',
|
||||
],
|
||||
},
|
||||
project_urls={"Bug Reports": "https://github.com/arsenetar/send2trash/issues"},
|
||||
entry_points={"console_scripts": ["send2trash=send2trash.__main__:main"]},
|
||||
)
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
def TestSuite():
|
||||
suite = unittest.TestSuite()
|
||||
loader = unittest.TestLoader()
|
||||
if sys.platform == "win32":
|
||||
from . import test_plat_win
|
||||
|
||||
suite.addTests(loader.loadTestsFromModule(test_plat_win))
|
||||
else:
|
||||
from . import test_script_main
|
||||
from . import test_plat_other
|
||||
|
||||
suite.addTests(loader.loadTestsFromModule(test_script_main))
|
||||
suite.addTests(loader.loadTestsFromModule(test_plat_other))
|
||||
return suite
|
||||
|
||||
@@ -1,51 +1,53 @@
|
||||
# encoding: utf-8
|
||||
import pytest
|
||||
import codecs
|
||||
import unittest
|
||||
import os
|
||||
import sys
|
||||
from os import path as op
|
||||
import send2trash.plat_other
|
||||
from send2trash.plat_other import send2trash as s2t
|
||||
from send2trash.compat import PY3
|
||||
from send2trash import TrashPermissionError
|
||||
|
||||
try:
|
||||
from configparser import ConfigParser
|
||||
except ImportError:
|
||||
# py2
|
||||
from ConfigParser import ConfigParser
|
||||
from ConfigParser import ConfigParser # noqa: F401
|
||||
|
||||
from tempfile import mkdtemp, NamedTemporaryFile, mktemp
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
|
||||
# Could still use cleaning up. But no longer relies on ramfs.
|
||||
if sys.platform != "win32":
|
||||
import send2trash.plat_other
|
||||
from send2trash.plat_other import send2trash as s2t
|
||||
|
||||
HOMETRASH = send2trash.plat_other.HOMETRASH
|
||||
else:
|
||||
pytest.skip("Skipping non-windows tests", allow_module_level=True)
|
||||
|
||||
|
||||
def touch(path):
|
||||
with open(path, "a"):
|
||||
os.utime(path, None)
|
||||
|
||||
|
||||
class TestHomeTrash(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.file = NamedTemporaryFile(
|
||||
@pytest.fixture
|
||||
def testfile():
|
||||
file = NamedTemporaryFile(
|
||||
dir=op.expanduser("~"), prefix="send2trash_test", delete=False
|
||||
)
|
||||
|
||||
def test_trash(self):
|
||||
s2t(self.file.name)
|
||||
self.assertFalse(op.exists(self.file.name))
|
||||
|
||||
def tearDown(self):
|
||||
name = op.basename(self.file.name)
|
||||
file.close()
|
||||
assert op.exists(file.name) is True
|
||||
yield file
|
||||
# Cleanup trash files on supported platforms
|
||||
if sys.platform != "win32":
|
||||
name = op.basename(file.name)
|
||||
# Remove trash files if they exist
|
||||
if op.exists(op.join(HOMETRASH, "files", name)):
|
||||
os.remove(op.join(HOMETRASH, "files", name))
|
||||
os.remove(op.join(HOMETRASH, "info", name + ".trashinfo"))
|
||||
if op.exists(file.name):
|
||||
os.remove(file.name)
|
||||
|
||||
|
||||
class TestHomeMultiTrash(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.files = list(
|
||||
@pytest.fixture
|
||||
def testfiles():
|
||||
files = list(
|
||||
map(
|
||||
lambda index: NamedTemporaryFile(
|
||||
dir=op.expanduser("~"),
|
||||
@@ -55,14 +57,10 @@ class TestHomeMultiTrash(unittest.TestCase):
|
||||
range(10),
|
||||
)
|
||||
)
|
||||
|
||||
def test_multitrash(self):
|
||||
filenames = [file.name for file in self.files]
|
||||
s2t(filenames)
|
||||
self.assertFalse(any([op.exists(filename) for filename in filenames]))
|
||||
|
||||
def tearDown(self):
|
||||
filenames = [op.basename(file.name) for file in self.files]
|
||||
[file.close() for file in files]
|
||||
assert all([op.exists(file.name) for file in files]) is True
|
||||
yield files
|
||||
filenames = [op.basename(file.name) for file in files]
|
||||
[os.remove(op.join(HOMETRASH, "files", filename)) for filename in filenames]
|
||||
[
|
||||
os.remove(op.join(HOMETRASH, "info", filename + ".trashinfo"))
|
||||
@@ -70,57 +68,64 @@ class TestHomeMultiTrash(unittest.TestCase):
|
||||
]
|
||||
|
||||
|
||||
def test_trash(testfile):
|
||||
s2t(testfile.name)
|
||||
assert op.exists(testfile.name) is False
|
||||
|
||||
|
||||
def test_multitrash(testfiles):
|
||||
filenames = [file.name for file in testfiles]
|
||||
s2t(filenames)
|
||||
assert any([op.exists(filename) for filename in filenames]) is False
|
||||
|
||||
|
||||
def touch(path):
|
||||
with open(path, "a"):
|
||||
os.utime(path, None)
|
||||
|
||||
|
||||
def _filesys_enc():
|
||||
enc = sys.getfilesystemencoding()
|
||||
# Get canonical name of codec
|
||||
return codecs.lookup(enc).name
|
||||
|
||||
|
||||
@unittest.skipIf(_filesys_enc() == "ascii", "ASCII filesystem")
|
||||
class TestUnicodeTrash(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.name = u"send2trash_tést1"
|
||||
self.file = op.join(op.expanduser(b"~"), self.name.encode("utf-8"))
|
||||
touch(self.file)
|
||||
|
||||
def test_trash_bytes(self):
|
||||
s2t(self.file)
|
||||
assert not op.exists(self.file)
|
||||
|
||||
def test_trash_unicode(self):
|
||||
s2t(self.file.decode(sys.getfilesystemencoding()))
|
||||
assert not op.exists(self.file)
|
||||
|
||||
def tearDown(self):
|
||||
if op.exists(self.file):
|
||||
os.remove(self.file)
|
||||
|
||||
trash_file = op.join(HOMETRASH, "files", self.name)
|
||||
if op.exists(trash_file):
|
||||
os.remove(trash_file)
|
||||
os.remove(op.join(HOMETRASH, "info", self.name + ".trashinfo"))
|
||||
@pytest.fixture
|
||||
def testUnicodefile():
|
||||
name = u"send2trash_tést1"
|
||||
file = op.join(op.expanduser(b"~"), name.encode("utf-8"))
|
||||
touch(file)
|
||||
assert op.exists(file) is True
|
||||
yield file
|
||||
# Cleanup trash files on supported platforms
|
||||
if sys.platform != "win32":
|
||||
# Remove trash files if they exist
|
||||
if op.exists(op.join(HOMETRASH, "files", name)):
|
||||
os.remove(op.join(HOMETRASH, "files", name))
|
||||
os.remove(op.join(HOMETRASH, "info", name + ".trashinfo"))
|
||||
if op.exists(file):
|
||||
os.remove(file)
|
||||
|
||||
|
||||
#
|
||||
# Tests for files on some other volume than the user's home directory.
|
||||
#
|
||||
# What we need to stub:
|
||||
# * plat_other.get_dev (to make sure the file will not be on the home dir dev)
|
||||
# * os.path.ismount (to make our topdir look like a top dir)
|
||||
#
|
||||
class TestExtVol(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.trashTopdir = mkdtemp(prefix="s2t")
|
||||
@pytest.mark.skipif(_filesys_enc() == "ascii", reason="Requires Unicode filesystem")
|
||||
def test_trash_bytes(testUnicodefile):
|
||||
s2t(testUnicodefile)
|
||||
assert not op.exists(testUnicodefile)
|
||||
|
||||
|
||||
@pytest.mark.skipif(_filesys_enc() == "ascii", reason="Requires Unicode filesystem")
|
||||
def test_trash_unicode(testUnicodefile):
|
||||
s2t(testUnicodefile.decode(sys.getfilesystemencoding()))
|
||||
assert not op.exists(testUnicodefile)
|
||||
|
||||
|
||||
class ExtVol:
|
||||
def __init__(self, path):
|
||||
self.trashTopdir = path
|
||||
if PY3:
|
||||
trashTopdir_b = os.fsencode(self.trashTopdir)
|
||||
self.trashTopdir_b = os.fsencode(self.trashTopdir)
|
||||
else:
|
||||
trashTopdir_b = self.trashTopdir
|
||||
self.fileName = "test.txt"
|
||||
self.filePath = op.join(self.trashTopdir, self.fileName)
|
||||
touch(self.filePath)
|
||||
|
||||
self.old_ismount = old_ismount = op.ismount
|
||||
self.old_getdev = send2trash.plat_other.get_dev
|
||||
self.trashTopdir_b = self.trashTopdir
|
||||
|
||||
def s_getdev(path):
|
||||
from send2trash.plat_other import is_parent
|
||||
@@ -133,120 +138,98 @@ class TestExtVol(unittest.TestCase):
|
||||
def s_ismount(path):
|
||||
if op.realpath(path) in (
|
||||
op.realpath(self.trashTopdir),
|
||||
op.realpath(trashTopdir_b),
|
||||
op.realpath(self.trashTopdir_b),
|
||||
):
|
||||
return True
|
||||
return old_ismount(path)
|
||||
|
||||
self.old_ismount = old_ismount = op.ismount
|
||||
self.old_getdev = send2trash.plat_other.get_dev
|
||||
send2trash.plat_other.os.path.ismount = s_ismount
|
||||
send2trash.plat_other.get_dev = s_getdev
|
||||
|
||||
def tearDown(self):
|
||||
def cleanup(self):
|
||||
send2trash.plat_other.get_dev = self.old_getdev
|
||||
send2trash.plat_other.os.path.ismount = self.old_ismount
|
||||
shutil.rmtree(self.trashTopdir)
|
||||
|
||||
|
||||
class TestTopdirTrash(TestExtVol):
|
||||
def setUp(self):
|
||||
TestExtVol.setUp(self)
|
||||
# Create a .Trash dir w/ a sticky bit
|
||||
self.trashDir = op.join(self.trashTopdir, ".Trash")
|
||||
os.mkdir(self.trashDir, 0o777 | stat.S_ISVTX)
|
||||
@pytest.fixture
|
||||
def testExtVol():
|
||||
trashTopdir = mkdtemp(prefix="s2t")
|
||||
volume = ExtVol(trashTopdir)
|
||||
fileName = "test.txt"
|
||||
filePath = op.join(volume.trashTopdir, fileName)
|
||||
touch(filePath)
|
||||
assert op.exists(filePath) is True
|
||||
yield volume, fileName, filePath
|
||||
volume.cleanup()
|
||||
|
||||
def test_trash(self):
|
||||
s2t(self.filePath)
|
||||
self.assertFalse(op.exists(self.filePath))
|
||||
self.assertTrue(
|
||||
op.exists(op.join(self.trashDir, str(os.getuid()), "files", self.fileName))
|
||||
|
||||
def test_trash_topdir(testExtVol):
|
||||
trashDir = op.join(testExtVol[0].trashTopdir, ".Trash")
|
||||
os.mkdir(trashDir, 0o777 | stat.S_ISVTX)
|
||||
|
||||
s2t(testExtVol[2])
|
||||
assert op.exists(testExtVol[2]) is False
|
||||
assert (
|
||||
op.exists(op.join(trashDir, str(os.getuid()), "files", testExtVol[1])) is True
|
||||
)
|
||||
self.assertTrue(
|
||||
assert (
|
||||
op.exists(
|
||||
op.join(
|
||||
self.trashDir,
|
||||
str(os.getuid()),
|
||||
"info",
|
||||
self.fileName + ".trashinfo",
|
||||
)
|
||||
op.join(trashDir, str(os.getuid()), "info", testExtVol[1] + ".trashinfo",)
|
||||
)
|
||||
is True
|
||||
)
|
||||
# info relative path (if another test is added, with the same fileName/Path,
|
||||
# then it gets renamed etc.)
|
||||
cfg = ConfigParser()
|
||||
cfg.read(
|
||||
op.join(
|
||||
self.trashDir, str(os.getuid()), "info", self.fileName + ".trashinfo"
|
||||
)
|
||||
)
|
||||
self.assertEqual(self.fileName, cfg.get("Trash Info", "Path", raw=True))
|
||||
cfg.read(op.join(trashDir, str(os.getuid()), "info", testExtVol[1] + ".trashinfo"))
|
||||
assert (testExtVol[1] == cfg.get("Trash Info", "Path", raw=True)) is True
|
||||
|
||||
|
||||
# Test .Trash-UID
|
||||
class TestTopdirTrashFallback(TestExtVol):
|
||||
def test_trash(self):
|
||||
touch(self.filePath)
|
||||
s2t(self.filePath)
|
||||
self.assertFalse(op.exists(self.filePath))
|
||||
self.assertTrue(
|
||||
def test_trash_topdir_fallback(testExtVol):
|
||||
s2t(testExtVol[2])
|
||||
assert op.exists(testExtVol[2]) is False
|
||||
assert (
|
||||
op.exists(
|
||||
op.join(
|
||||
self.trashTopdir,
|
||||
testExtVol[0].trashTopdir,
|
||||
".Trash-" + str(os.getuid()),
|
||||
"files",
|
||||
self.fileName,
|
||||
testExtVol[1],
|
||||
)
|
||||
)
|
||||
is True
|
||||
)
|
||||
|
||||
|
||||
# Test failure
|
||||
class TestTopdirFailure(TestExtVol):
|
||||
def setUp(self):
|
||||
TestExtVol.setUp(self)
|
||||
os.chmod(self.trashTopdir, 0o500) # not writable to induce the exception
|
||||
|
||||
def test_trash(self):
|
||||
with self.assertRaises(OSError):
|
||||
s2t(self.filePath)
|
||||
self.assertTrue(op.exists(self.filePath))
|
||||
|
||||
def tearDown(self):
|
||||
os.chmod(self.trashTopdir, 0o700) # writable to allow deletion
|
||||
TestExtVol.tearDown(self)
|
||||
def test_trash_topdir_failure(testExtVol):
|
||||
os.chmod(testExtVol[0].trashTopdir, 0o500) # not writable to induce the exception
|
||||
pytest.raises(TrashPermissionError, s2t, [testExtVol[2]])
|
||||
os.chmod(testExtVol[0].trashTopdir, 0o700) # writable to allow deletion
|
||||
|
||||
|
||||
# Make sure it will find the mount point properly for a file in a symlinked path
|
||||
class TestSymlink(TestExtVol):
|
||||
def setUp(self):
|
||||
TestExtVol.setUp(self)
|
||||
def test_trash_symlink(testExtVol):
|
||||
# Use mktemp (race conditioney but no symlink equivalent)
|
||||
# Since is_parent uses realpath(), and our getdev uses is_parent,
|
||||
# this should work
|
||||
self.slDir = mktemp(prefix="s2t", dir=op.expanduser("~"))
|
||||
|
||||
os.mkdir(op.join(self.trashTopdir, "subdir"), 0o700)
|
||||
self.filePath = op.join(self.trashTopdir, "subdir", self.fileName)
|
||||
touch(self.filePath)
|
||||
os.symlink(op.join(self.trashTopdir, "subdir"), self.slDir)
|
||||
|
||||
def test_trash(self):
|
||||
s2t(op.join(self.slDir, self.fileName))
|
||||
self.assertFalse(op.exists(self.filePath))
|
||||
self.assertTrue(
|
||||
slDir = mktemp(prefix="s2t", dir=op.expanduser("~"))
|
||||
os.mkdir(op.join(testExtVol[0].trashTopdir, "subdir"), 0o700)
|
||||
filePath = op.join(testExtVol[0].trashTopdir, "subdir", testExtVol[1])
|
||||
touch(filePath)
|
||||
os.symlink(op.join(testExtVol[0].trashTopdir, "subdir"), slDir)
|
||||
s2t(op.join(slDir, testExtVol[1]))
|
||||
assert op.exists(filePath) is False
|
||||
assert (
|
||||
op.exists(
|
||||
op.join(
|
||||
self.trashTopdir,
|
||||
testExtVol[0].trashTopdir,
|
||||
".Trash-" + str(os.getuid()),
|
||||
"files",
|
||||
self.fileName,
|
||||
testExtVol[1],
|
||||
)
|
||||
)
|
||||
is True
|
||||
)
|
||||
|
||||
def tearDown(self):
|
||||
os.remove(self.slDir)
|
||||
TestExtVol.tearDown(self)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
os.remove(slDir)
|
||||
|
||||
@@ -1,154 +1,203 @@
|
||||
# coding: utf-8
|
||||
# encoding: utf-8
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import unittest
|
||||
import pytest
|
||||
from os import path as op
|
||||
from tempfile import gettempdir
|
||||
|
||||
from send2trash import send2trash as s2t
|
||||
|
||||
# import the two versions as well as the "automatic" version
|
||||
if sys.platform == "win32":
|
||||
from send2trash.plat_win_modern import send2trash as s2t_modern
|
||||
from send2trash.plat_win_legacy import send2trash as s2t_legacy
|
||||
else:
|
||||
pytest.skip("Skipping windows-only tests", allow_module_level=True)
|
||||
|
||||
|
||||
@unittest.skipIf(sys.platform != "win32", "Windows only")
|
||||
class TestNormal(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dirname = "\\\\?\\" + op.join(gettempdir(), "python.send2trash")
|
||||
self.file = op.join(self.dirname, "testfile.txt")
|
||||
self._create_tree(self.file)
|
||||
self.files = [
|
||||
op.join(self.dirname, "testfile{}.txt".format(index)) for index in range(10)
|
||||
]
|
||||
[self._create_tree(file) for file in self.files]
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.dirname, ignore_errors=True)
|
||||
|
||||
def _create_tree(self, path):
|
||||
def _create_tree(path):
|
||||
dirname = op.dirname(path)
|
||||
if not op.isdir(dirname):
|
||||
os.makedirs(dirname)
|
||||
with open(path, "w") as writer:
|
||||
writer.write("send2trash test")
|
||||
|
||||
def _trash_file(self, fcn):
|
||||
fcn(self.file)
|
||||
self.assertFalse(op.exists(self.file))
|
||||
|
||||
def _trash_multifile(self, fcn):
|
||||
fcn(self.files)
|
||||
self.assertFalse(any([op.exists(file) for file in self.files]))
|
||||
|
||||
def _file_not_found(self, fcn):
|
||||
file = op.join(self.dirname, "otherfile.txt")
|
||||
self.assertRaises(WindowsError, fcn, file)
|
||||
|
||||
def test_trash_file(self):
|
||||
self._trash_file(s2t)
|
||||
|
||||
def test_trash_multifile(self):
|
||||
self._trash_multifile(s2t)
|
||||
|
||||
def test_file_not_found(self):
|
||||
self._file_not_found(s2t)
|
||||
|
||||
def test_trash_file_modern(self):
|
||||
self._trash_file(s2t_modern)
|
||||
|
||||
def test_trash_multifile_modern(self):
|
||||
self._trash_multifile(s2t_modern)
|
||||
|
||||
def test_file_not_found_modern(self):
|
||||
self._file_not_found(s2t_modern)
|
||||
|
||||
def test_trash_file_legacy(self):
|
||||
self._trash_file(s2t_legacy)
|
||||
|
||||
def test_trash_multifile_legacy(self):
|
||||
self._trash_multifile(s2t_legacy)
|
||||
|
||||
def test_file_not_found_legacy(self):
|
||||
self._file_not_found(s2t_legacy)
|
||||
@pytest.fixture
|
||||
def testdir(tmp_path):
|
||||
dirname = "\\\\?\\" + str(tmp_path)
|
||||
assert op.exists(dirname) is True
|
||||
yield dirname
|
||||
shutil.rmtree(dirname, ignore_errors=True)
|
||||
|
||||
|
||||
@unittest.skipIf(sys.platform != "win32", "Windows only")
|
||||
class TestLongPath(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.functions = {s2t: "auto", s2t_legacy: "legacy", s2t_modern: "modern"}
|
||||
filename = "A" * 100
|
||||
self.dirname = "\\\\?\\" + op.join(gettempdir(), filename)
|
||||
path = op.join(
|
||||
self.dirname,
|
||||
filename,
|
||||
filename, # From there, the path is not trashable from Explorer
|
||||
filename,
|
||||
filename + "{}.txt",
|
||||
)
|
||||
self.file = path.format("")
|
||||
self._create_tree(self.file)
|
||||
self.files = [path.format(index) for index in range(10)]
|
||||
[self._create_tree(file) for file in self.files]
|
||||
@pytest.fixture
|
||||
def testfile(testdir):
|
||||
file = op.join(testdir, "testfile.txt")
|
||||
_create_tree(file)
|
||||
assert op.exists(file) is True
|
||||
yield file
|
||||
# Note dir will cleanup the file
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.dirname, ignore_errors=True)
|
||||
|
||||
def _create_tree(self, path):
|
||||
dirname = op.dirname(path)
|
||||
if not op.isdir(dirname):
|
||||
os.makedirs(dirname)
|
||||
with open(path, "w") as writer:
|
||||
writer.write("Looong filename!")
|
||||
@pytest.fixture
|
||||
def testfiles(testdir):
|
||||
files = [op.join(testdir, "testfile{}.txt".format(index)) for index in range(10)]
|
||||
[_create_tree(file) for file in files]
|
||||
assert all([op.exists(file) for file in files]) is True
|
||||
yield files
|
||||
# Note dir will cleanup the files
|
||||
|
||||
def _trash_file(self, fcn):
|
||||
fcn(self.file)
|
||||
self.assertFalse(op.exists(self.file))
|
||||
|
||||
def _trash_multifile(self, fcn):
|
||||
fcn(self.files)
|
||||
self.assertFalse(any([op.exists(file) for file in self.files]))
|
||||
def _trash_folder(dir, fcn):
|
||||
fcn(dir)
|
||||
assert op.exists(dir) is False
|
||||
|
||||
def _trash_folder(self, fcn):
|
||||
fcn(self.dirname)
|
||||
self.assertFalse(op.exists(self.dirname))
|
||||
|
||||
def test_trash_file(self):
|
||||
self._trash_file(s2t)
|
||||
def _trash_file(file, fcn):
|
||||
fcn(file)
|
||||
assert op.exists(file) is False
|
||||
|
||||
def test_trash_multifile(self):
|
||||
self._trash_multifile(s2t)
|
||||
|
||||
@unittest.skipIf(
|
||||
op.splitdrive(os.getcwd())[0] != op.splitdrive(gettempdir())[0],
|
||||
"Cannot trash long path from other drive",
|
||||
)
|
||||
def test_trash_folder(self):
|
||||
self._trash_folder(s2t)
|
||||
def _trash_multifile(files, fcn):
|
||||
fcn(files)
|
||||
assert any([op.exists(file) for file in files]) is False
|
||||
|
||||
def test_trash_file_modern(self):
|
||||
self._trash_file(s2t_modern)
|
||||
|
||||
def test_trash_multifile_modern(self):
|
||||
self._trash_multifile(s2t_modern)
|
||||
def _file_not_found(dir, fcn):
|
||||
file = op.join(dir, "otherfile.txt")
|
||||
pytest.raises(OSError, fcn, file)
|
||||
|
||||
@unittest.skipIf(
|
||||
op.splitdrive(os.getcwd())[0] != op.splitdrive(gettempdir())[0],
|
||||
"Cannot trash long path from other drive",
|
||||
)
|
||||
def test_trash_folder_modern(self):
|
||||
self._trash_folder(s2t_modern)
|
||||
|
||||
def test_trash_file_legacy(self):
|
||||
self._trash_file(s2t_legacy)
|
||||
def _multi_byte_unicode(dir, fcn):
|
||||
single_file = op.join(dir, "😇.txt")
|
||||
_create_tree(single_file)
|
||||
assert op.exists(single_file) is True
|
||||
fcn(single_file)
|
||||
assert op.exists(single_file) is False
|
||||
files = [op.join(dir, "😇{}.txt".format(index)) for index in range(10)]
|
||||
[_create_tree(file) for file in files]
|
||||
assert all([op.exists(file) for file in files]) is True
|
||||
fcn(files)
|
||||
assert any([op.exists(file) for file in files]) is False
|
||||
|
||||
def test_trash_multifile_legacy(self):
|
||||
self._trash_multifile(s2t_legacy)
|
||||
|
||||
@unittest.skipIf(
|
||||
op.splitdrive(os.getcwd())[0] != op.splitdrive(gettempdir())[0],
|
||||
"Cannot trash long path from other drive",
|
||||
)
|
||||
def test_trash_folder_legacy(self):
|
||||
self._trash_folder(s2t_legacy)
|
||||
def test_trash_folder(testdir):
|
||||
_trash_folder(testdir, s2t)
|
||||
|
||||
|
||||
def test_trash_file(testfile):
|
||||
_trash_file(testfile, s2t)
|
||||
|
||||
|
||||
def test_trash_multifile(testfiles):
|
||||
_trash_multifile(testfiles, s2t)
|
||||
|
||||
|
||||
def test_file_not_found(testdir):
|
||||
_file_not_found(testdir, s2t)
|
||||
|
||||
|
||||
def test_trash_folder_modern(testdir):
|
||||
_trash_folder(testdir, s2t_modern)
|
||||
|
||||
|
||||
def test_trash_file_modern(testfile):
|
||||
_trash_file(testfile, s2t_modern)
|
||||
|
||||
|
||||
def test_trash_multifile_modern(testfiles):
|
||||
_trash_multifile(testfiles, s2t_modern)
|
||||
|
||||
|
||||
def test_file_not_found_modern(testdir):
|
||||
_file_not_found(testdir, s2t_modern)
|
||||
|
||||
|
||||
def test_multi_byte_unicode_modern(testdir):
|
||||
_multi_byte_unicode(testdir, s2t_modern)
|
||||
|
||||
|
||||
def test_trash_folder_legacy(testdir):
|
||||
_trash_folder(testdir, s2t_legacy)
|
||||
|
||||
|
||||
def test_trash_file_legacy(testfile):
|
||||
_trash_file(testfile, s2t_legacy)
|
||||
|
||||
|
||||
def test_trash_multifile_legacy(testfiles):
|
||||
_trash_multifile(testfiles, s2t_legacy)
|
||||
|
||||
|
||||
def test_file_not_found_legacy(testdir):
|
||||
_file_not_found(testdir, s2t_legacy)
|
||||
|
||||
|
||||
def test_multi_byte_unicode_legacy(testdir):
|
||||
_multi_byte_unicode(testdir, s2t_legacy)
|
||||
|
||||
|
||||
# Long path tests
|
||||
@pytest.fixture
|
||||
def longdir(tmp_path):
|
||||
dirname = "\\\\?\\" + str(tmp_path)
|
||||
name = "A" * 100
|
||||
yield op.join(dirname, name, name, name)
|
||||
shutil.rmtree(dirname, ignore_errors=True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def longfile(longdir):
|
||||
name = "A" * 100
|
||||
path = op.join(longdir, name + "{}.txt")
|
||||
file = path.format("")
|
||||
_create_tree(file)
|
||||
assert op.exists(file) is True
|
||||
yield file
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def longfiles(longdir):
|
||||
name = "A" * 100
|
||||
path = op.join(longdir, name + "{}.txt")
|
||||
files = [path.format(index) for index in range(10)]
|
||||
[_create_tree(file) for file in files]
|
||||
assert all([op.exists(file) for file in files]) is True
|
||||
yield files
|
||||
|
||||
|
||||
# NOTE: both legacy and modern test "pass" on windows, however sometimes with the same path
|
||||
# they do not actually recycle files but delete them. Noticed this when testing with the
|
||||
# recycle bin open, noticed later tests actually worked, modern version can actually detect
|
||||
# when this happens but not stop it at this moment, and we need a way to verify it when testing.
|
||||
def test_trash_long_file_modern(longfile):
|
||||
_trash_file(longfile, s2t_modern)
|
||||
|
||||
|
||||
def test_trash_long_multifile_modern(longfiles):
|
||||
_trash_multifile(longfiles, s2t_modern)
|
||||
|
||||
|
||||
# @pytest.skipif(
|
||||
# op.splitdrive(os.getcwd())[0] != op.splitdrive(gettempdir())[0],
|
||||
# "Cannot trash long path from other drive",
|
||||
# )
|
||||
# def test_trash_long_folder_modern(self):
|
||||
# self._trash_folder(s2t_modern)
|
||||
|
||||
|
||||
def test_trash_long_file_legacy(longfile):
|
||||
_trash_file(longfile, s2t_legacy)
|
||||
|
||||
|
||||
def test_trash_long_multifile_legacy(longfiles):
|
||||
_trash_multifile(longfiles, s2t_legacy)
|
||||
|
||||
|
||||
# @pytest.skipif(
|
||||
# op.splitdrive(os.getcwd())[0] != op.splitdrive(gettempdir())[0],
|
||||
# "Cannot trash long path from other drive",
|
||||
# )
|
||||
# def test_trash_long_folder_legacy(self):
|
||||
# self._trash_folder(s2t_legacy)
|
||||
|
||||
@@ -1,32 +1,43 @@
|
||||
# encoding: utf-8
|
||||
import os
|
||||
import unittest
|
||||
import sys
|
||||
import pytest
|
||||
from tempfile import NamedTemporaryFile
|
||||
from os import path as op
|
||||
|
||||
from send2trash.__main__ import main as trash_main
|
||||
from tests.test_plat_other import HOMETRASH
|
||||
|
||||
# Only import HOMETRASH on supported platforms
|
||||
if sys.platform != "win32":
|
||||
from send2trash.plat_other import HOMETRASH
|
||||
|
||||
|
||||
class TestMainTrash(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.file = NamedTemporaryFile(dir=op.expanduser('~'), prefix='send2trash_test', delete=False)
|
||||
|
||||
def test_trash(self):
|
||||
trash_main(['-v', self.file.name])
|
||||
self.assertFalse(op.exists(self.file.name))
|
||||
|
||||
def test_no_args(self):
|
||||
self.assertRaises(SystemExit, trash_main, [])
|
||||
self.assertRaises(SystemExit, trash_main, ['-v'])
|
||||
self.assertTrue(op.exists(self.file.name))
|
||||
trash_main([self.file.name]) # Trash the file so tearDown runs properly
|
||||
|
||||
def tearDown(self):
|
||||
name = op.basename(self.file.name)
|
||||
os.remove(op.join(HOMETRASH, 'files', name))
|
||||
os.remove(op.join(HOMETRASH, 'info', name + '.trashinfo'))
|
||||
@pytest.fixture
|
||||
def file():
|
||||
file = NamedTemporaryFile(
|
||||
dir=op.expanduser("~"), prefix="send2trash_test", delete=False
|
||||
)
|
||||
file.close()
|
||||
# Verify file was actually created
|
||||
assert op.exists(file.name) is True
|
||||
yield file.name
|
||||
# Cleanup trash files on supported platforms
|
||||
if sys.platform != "win32":
|
||||
name = op.basename(file.name)
|
||||
# Remove trash files if they exist
|
||||
if op.exists(op.join(HOMETRASH, "files", name)):
|
||||
os.remove(op.join(HOMETRASH, "files", name))
|
||||
os.remove(op.join(HOMETRASH, "info", name + ".trashinfo"))
|
||||
if op.exists(file.name):
|
||||
os.remove(file.name)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
def test_trash(file):
|
||||
trash_main(["-v", file])
|
||||
assert op.exists(file) is False
|
||||
|
||||
|
||||
def test_no_args(file):
|
||||
pytest.raises(SystemExit, trash_main, [])
|
||||
pytest.raises(SystemExit, trash_main, ["-v"])
|
||||
assert op.exists(file) is True
|
||||
|
||||
18
tox.ini
18
tox.ini
@@ -1,21 +1,21 @@
|
||||
[tox]
|
||||
envlist = py27,py34,py35,py36,py3-win
|
||||
envlist = py{27,34,35,36,37,38,39,310}
|
||||
skip_missing_interpreters = True
|
||||
|
||||
[testenv]
|
||||
platform = linux
|
||||
deps =
|
||||
flake8
|
||||
pytest
|
||||
pywin32; sys_platform == 'win32'
|
||||
pyobjc-framework-Cocoa; sys_platform == 'darwin'
|
||||
commands =
|
||||
python setup.py test --test-suite tests.TestSuite
|
||||
|
||||
[testenv:py3-win]
|
||||
platform = win
|
||||
commands =
|
||||
python -m pip install pywin32
|
||||
python setup.py test --test-suite tests.TestSuite
|
||||
flake8
|
||||
pytest
|
||||
|
||||
[testenv:py27]
|
||||
deps =
|
||||
configparser
|
||||
{[testenv]deps}
|
||||
|
||||
[flake8]
|
||||
exclude = .tox,env,build
|
||||
|
||||
Reference in New Issue
Block a user