eric6/ThirdParty/Send2Trash/send2trash/plat_other.py

changeset 8258
82b608e352ec
parent 8257
28146736bbfc
child 8259
2bbec88047dd
equal deleted inserted replaced
8257:28146736bbfc 8258:82b608e352ec
1 # Copyright 2017 Virgil Dupras
2
3 # This software is licensed under the "BSD" License as described in the "LICENSE" file,
4 # which should be included with this package. The terms are also available at
5 # http://www.hardcoded.net/licenses/bsd_license
6
7 # This is a reimplementation of plat_other.py with reference to the
8 # freedesktop.org trash specification:
9 # [1] http://www.freedesktop.org/wiki/Specifications/trash-spec
10 # [2] http://www.ramendik.ru/docs/trashspec.html
11 # See also:
12 # [3] http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
13 #
14 # For external volumes this implementation will raise an exception if it can't
15 # find or create the user's trash directory.
16
17 from __future__ import unicode_literals
18
19 import errno
20 import sys
21 import os
22 import os.path as op
23 from datetime import datetime
24 import stat
25 try:
26 from urllib.parse import quote
27 except ImportError:
28 # Python 2
29 from urllib import quote
30
31 from .compat import text_type, environb
32 from .exceptions import TrashPermissionError
33
34 try:
35 fsencode = os.fsencode # Python 3
36 fsdecode = os.fsdecode
37 except AttributeError:
38 def fsencode(u): # Python 2
39 return u.encode(sys.getfilesystemencoding())
40 def fsdecode(b):
41 return b.decode(sys.getfilesystemencoding())
42 # The Python 3 versions are a bit smarter, handling surrogate escapes,
43 # but these should work in most cases.
44
45 FILES_DIR = b'files'
46 INFO_DIR = b'info'
47 INFO_SUFFIX = b'.trashinfo'
48
49 # Default of ~/.local/share [3]
50 XDG_DATA_HOME = op.expanduser(environb.get(b'XDG_DATA_HOME', b'~/.local/share'))
51 HOMETRASH_B = op.join(XDG_DATA_HOME, b'Trash')
52 HOMETRASH = fsdecode(HOMETRASH_B)
53
54 uid = os.getuid()
55 TOPDIR_TRASH = b'.Trash'
56 TOPDIR_FALLBACK = b'.Trash-' + text_type(uid).encode('ascii')
57
58 def is_parent(parent, path):
59 path = op.realpath(path) # In case it's a symlink
60 if isinstance(path, text_type):
61 path = fsencode(path)
62 parent = op.realpath(parent)
63 if isinstance(parent, text_type):
64 parent = fsencode(parent)
65 return path.startswith(parent)
66
67 def format_date(date):
68 return date.strftime("%Y-%m-%dT%H:%M:%S")
69
70 def info_for(src, topdir):
71 # ...it MUST not include a ".." directory, and for files not "under" that
72 # directory, absolute pathnames must be used. [2]
73 if topdir is None or not is_parent(topdir, src):
74 src = op.abspath(src)
75 else:
76 src = op.relpath(src, topdir)
77
78 info = "[Trash Info]\n"
79 info += "Path=" + quote(src) + "\n"
80 info += "DeletionDate=" + format_date(datetime.now()) + "\n"
81 return info
82
83 def check_create(dir):
84 # use 0700 for paths [3]
85 if not op.exists(dir):
86 os.makedirs(dir, 0o700)
87
88 def trash_move(src, dst, topdir=None):
89 filename = op.basename(src)
90 filespath = op.join(dst, FILES_DIR)
91 infopath = op.join(dst, INFO_DIR)
92 base_name, ext = op.splitext(filename)
93
94 counter = 0
95 destname = filename
96 while op.exists(op.join(filespath, destname)) or op.exists(op.join(infopath, destname + INFO_SUFFIX)):
97 counter += 1
98 destname = base_name + b' ' + text_type(counter).encode('ascii') + ext
99
100 check_create(filespath)
101 check_create(infopath)
102
103 os.rename(src, op.join(filespath, destname))
104 f = open(op.join(infopath, destname + INFO_SUFFIX), 'w')
105 f.write(info_for(src, topdir))
106 f.close()
107
108 def find_mount_point(path):
109 # Even if something's wrong, "/" is a mount point, so the loop will exit.
110 # Use realpath in case it's a symlink
111 path = op.realpath(path) # Required to avoid infinite loop
112 while not op.ismount(path):
113 path = op.split(path)[0]
114 return path
115
116 def find_ext_volume_global_trash(volume_root):
117 # from [2] Trash directories (1) check for a .Trash dir with the right
118 # permissions set.
119 trash_dir = op.join(volume_root, TOPDIR_TRASH)
120 if not op.exists(trash_dir):
121 return None
122
123 mode = os.lstat(trash_dir).st_mode
124 # vol/.Trash must be a directory, cannot be a symlink, and must have the
125 # sticky bit set.
126 if not op.isdir(trash_dir) or op.islink(trash_dir) or not (mode & stat.S_ISVTX):
127 return None
128
129 trash_dir = op.join(trash_dir, text_type(uid).encode('ascii'))
130 try:
131 check_create(trash_dir)
132 except OSError:
133 return None
134 return trash_dir
135
136 def find_ext_volume_fallback_trash(volume_root):
137 # from [2] Trash directories (1) create a .Trash-$uid dir.
138 trash_dir = op.join(volume_root, TOPDIR_FALLBACK)
139 # Try to make the directory, if we lack permission, raise TrashPermissionError
140 try:
141 check_create(trash_dir)
142 except OSError as e:
143 if e.errno == errno.EACCES:
144 raise TrashPermissionError(e.filename)
145 raise
146 return trash_dir
147
148 def find_ext_volume_trash(volume_root):
149 trash_dir = find_ext_volume_global_trash(volume_root)
150 if trash_dir is None:
151 trash_dir = find_ext_volume_fallback_trash(volume_root)
152 return trash_dir
153
154 # Pull this out so it's easy to stub (to avoid stubbing lstat itself)
155 def get_dev(path):
156 return os.lstat(path).st_dev
157
158 def send2trash(path):
159 if isinstance(path, text_type):
160 path_b = fsencode(path)
161 elif isinstance(path, bytes):
162 path_b = path
163 elif hasattr(path, '__fspath__'):
164 # Python 3.6 PathLike protocol
165 return send2trash(path.__fspath__())
166 else:
167 raise TypeError('str, bytes or PathLike expected, not %r' % type(path))
168
169 if not op.exists(path_b):
170 raise OSError("File not found: %s" % path)
171 # ...should check whether the user has the necessary permissions to delete
172 # it, before starting the trashing operation itself. [2]
173 if not os.access(path_b, os.W_OK):
174 raise OSError("Permission denied: %s" % path)
175 # if the file to be trashed is on the same device as HOMETRASH we
176 # want to move it there.
177 path_dev = get_dev(path_b)
178
179 # If XDG_DATA_HOME or HOMETRASH do not yet exist we need to stat the
180 # home directory, and these paths will be created further on if needed.
181 trash_dev = get_dev(op.expanduser(b'~'))
182
183 if path_dev == trash_dev:
184 topdir = XDG_DATA_HOME
185 dest_trash = HOMETRASH_B
186 else:
187 topdir = find_mount_point(path_b)
188 trash_dev = get_dev(topdir)
189 if trash_dev != path_dev:
190 raise OSError("Couldn't find mount point for %s" % path)
191 dest_trash = find_ext_volume_trash(topdir)
192 trash_move(path_b, dest_trash, topdir)

eric ide

mercurial