File: plat_osx.py

package info (click to toggle)
send2trash 1.6.0~b1%2Bgit20210122.2eb3242-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 184 kB
  • sloc: python: 737; makefile: 2
file content (56 lines) | stat: -rw-r--r-- 1,839 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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

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)