/
fsobject.py
350 lines (293 loc) · 11 KB
/
fsobject.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# This file is part of ranger, the console file manager.
# License: GNU GPL version 3, see the file "AUTHORS" for details.
from __future__ import (absolute_import, print_function)
import re
from grp import getgrgid
from os import lstat, stat
from os.path import abspath, basename, dirname, realpath, splitext, extsep, relpath
from pwd import getpwuid
from ranger.core.linemode import (
DEFAULT_LINEMODE, DefaultLinemode, TitleLinemode,
PermissionsLinemode, FileInfoLinemode, MtimeLinemode, SizeMtimeLinemode,
)
from ranger.core.shared import FileManagerAware, SettingsAware
from ranger.ext.shell_escape import shell_escape
from ranger.ext import spawn
from ranger.ext.lazy_property import lazy_property
from ranger.ext.human_readable import human_readable
if hasattr(str, 'maketrans'):
maketrans = str.maketrans # pylint: disable=invalid-name,no-member
else:
from string import maketrans # pylint: disable=no-name-in-module
CONTAINER_EXTENSIONS = ('7z', 'ace', 'ar', 'arc', 'bz', 'bz2', 'cab', 'cpio',
'cpt', 'deb', 'dgc', 'dmg', 'gz', 'iso', 'jar', 'msi', 'pkg', 'rar',
'shar', 'tar', 'tbz', 'tgz', 'xar', 'xpi', 'xz', 'zip')
DOCUMENT_EXTENSIONS = ('cfg', 'css', 'cvs', 'djvu', 'doc', 'docx', 'gnm',
'gnumeric', 'htm', 'html', 'md', 'odf', 'odg', 'odp', 'ods', 'odt', 'pdf',
'pod', 'ps', 'rtf', 'sxc', 'txt', 'xls', 'xlw', 'xml', 'xslx')
DOCUMENT_BASENAMES = ('bugs', 'bugs', 'changelog', 'copying', 'credits',
'hacking', 'help', 'install', 'license', 'readme', 'todo')
BAD_INFO = '?'
# pylint: disable=invalid-name
_unsafe_chars = '\n' + ''.join(map(chr, range(32))) + ''.join(map(chr, range(128, 256)))
_safe_string_table = maketrans(_unsafe_chars, '?' * len(_unsafe_chars))
_extract_number_re = re.compile(r'(\d+|\D)')
_integers = set("0123456789")
# pylint: enable=invalid-name
def safe_path(path):
return path.translate(_safe_string_table)
class FileSystemObject( # pylint: disable=too-many-instance-attributes
FileManagerAware, SettingsAware):
(basename,
relative_path,
relative_path_lower,
dirname,
extension,
infostring,
path,
permissions,
stat) = (None,) * 9
(content_loaded,
force_load,
is_device,
is_directory,
is_file,
is_fifo,
is_link,
is_socket,
accessible,
exists, # "exists" currently means "link_target_exists"
loaded,
marked,
runnable,
stopped,
tagged,
audio,
container,
document,
image,
media,
video) = (False,) * 21
size = 0
vcsstatus = None
vcsremotestatus = None
_linemode = DEFAULT_LINEMODE
linemode_dict = dict(
(linemode.name, linemode()) for linemode in
[DefaultLinemode, TitleLinemode, PermissionsLinemode, FileInfoLinemode,
MtimeLinemode, SizeMtimeLinemode]
)
def __init__(self, path, preload=None, path_is_abs=False, basename_is_rel_to=None):
if not path_is_abs:
path = abspath(path)
self.path = path
self.basename = basename(path)
if basename_is_rel_to is None:
self.relative_path = self.basename
else:
self.relative_path = relpath(path, basename_is_rel_to)
self.relative_path_lower = self.relative_path.lower()
self.extension = splitext(self.basename)[1].lstrip(extsep) or None
self.dirname = dirname(path)
self.preload = preload
self.display_data = {}
try:
lastdot = self.basename.rindex('.') + 1
self.extension = self.basename[lastdot:].lower()
except ValueError:
self.extension = None
# Set the line mode from fm.default_linemodes
for method, argument, linemode in self.fm.default_linemodes:
if linemode in self.linemode_dict:
if method == "always":
self._linemode = linemode
break
if method == "path" and argument.search(path):
self._linemode = linemode
break
if method == "tag" and self.realpath in self.fm.tags and \
self.fm.tags.marker(self.realpath) in argument:
self._linemode = linemode
break
def __repr__(self):
return "<{0} {1}>".format(self.__class__.__name__, self.path)
@lazy_property
def shell_escaped_basename(self):
return shell_escape(self.basename)
@lazy_property
def filetype(self):
try:
return spawn.check_output(["file", '-Lb', '--mime-type', self.path])
except OSError:
return ""
@lazy_property
def basename_natural(self):
return [('0', int(s)) if s in _integers else (s, 0)
for s in _extract_number_re.split(self.relative_path)]
@lazy_property
def basename_natural_lower(self):
return [('0', int(s)) if s in _integers else (s, 0)
for s in _extract_number_re.split(self.relative_path_lower)]
@lazy_property
def safe_basename(self):
return self.basename.translate(_safe_string_table)
@lazy_property
def user(self):
try:
return getpwuid(self.stat.st_uid)[0]
except Exception:
return str(self.stat.st_uid)
@lazy_property
def group(self):
try:
return getgrgid(self.stat.st_gid)[0]
except Exception:
return str(self.stat.st_gid)
for attr in ('video', 'audio', 'image', 'media', 'document', 'container'):
exec( # pylint: disable=exec-used
"%s = lazy_property(lambda self: self.set_mimetype() or self.%s)" % (attr, attr))
def __str__(self):
"""returns a string containing the absolute path"""
return str(self.path)
def use(self):
"""Used in garbage-collecting. Override in Directory"""
def look_up_cumulative_size(self):
pass # normal files have no cumulative size
def set_mimetype(self):
"""assign attributes such as self.video according to the mimetype"""
bname = self.basename
if self.extension == 'part':
bname = bname[0:-5]
self._mimetype = self.fm.mimetypes.guess_type(bname, False)[0]
if self._mimetype is None:
self._mimetype = ''
self.video = self._mimetype.startswith('video')
self.image = self._mimetype.startswith('image')
self.audio = self._mimetype.startswith('audio')
self.media = self.video or self.image or self.audio
self.document = self._mimetype.startswith('text') \
or self.extension in DOCUMENT_EXTENSIONS \
or self.basename.lower() in DOCUMENT_BASENAMES
self.container = self.extension in CONTAINER_EXTENSIONS
keys = ('video', 'audio', 'image', 'media', 'document', 'container')
self._mimetype_tuple = tuple(key for key in keys if getattr(self, key))
if self._mimetype == '':
self._mimetype = None
@property
def mimetype(self):
try:
return self._mimetype
except Exception:
self.set_mimetype()
return self._mimetype
@property
def mimetype_tuple(self):
try:
return self._mimetype_tuple
except Exception:
self.set_mimetype()
return self._mimetype_tuple
def mark(self, _):
directory = self.fm.get_directory(self.dirname)
directory.mark_item(self)
def _mark(self, boolean):
"""Called by directory.mark_item() and similar functions"""
self.marked = bool(boolean)
@lazy_property
def realpath(self):
if self.is_link:
try:
return realpath(self.path)
except Exception:
return None # it is impossible to get the link destination
return self.path
def load(self):
"""Loads information about the directory itself.
reads useful information about the filesystem-object from the
filesystem and caches it for later use
"""
self.display_data = {}
self.fm.update_preview(self.path)
self.loaded = True
# Get the stat object, either from preload or from [l]stat
self.permissions = None
new_stat = None
path = self.path
self.is_link = False
if self.preload:
new_stat = self.preload[1]
self.is_link = new_stat.st_mode & 0o170000 == 0o120000
if self.is_link:
new_stat = self.preload[0]
self.preload = None
self.exists = True if new_stat else False
else:
try:
new_stat = lstat(path)
self.is_link = new_stat.st_mode & 0o170000 == 0o120000
if self.is_link:
new_stat = stat(path)
self.exists = True
except Exception:
self.exists = False
# Set some attributes
self.accessible = True if new_stat else False
mode = new_stat.st_mode if new_stat else 0
fmt = mode & 0o170000
if fmt == 0o020000 or fmt == 0o060000: # stat.S_IFCHR/BLK
self.is_device = True
self.size = 0
self.infostring = 'dev'
elif fmt == 0o010000: # stat.S_IFIFO
self.is_fifo = True
self.size = 0
self.infostring = 'fifo'
elif fmt == 0o140000: # stat.S_IFSOCK
self.is_socket = True
self.size = 0
self.infostring = 'sock'
elif self.is_file:
if new_stat:
self.size = new_stat.st_size
self.infostring = ' ' + human_readable(self.size)
else:
self.size = 0
self.infostring = '?'
if self.is_link and not self.is_directory:
self.infostring = '->' + self.infostring
self.stat = new_stat
def get_permission_string(self):
if self.permissions is not None:
return self.permissions
if self.is_directory:
perms = ['d']
elif self.is_link:
perms = ['l']
else:
perms = ['-']
mode = self.stat.st_mode
test = 0o0400
while test: # will run 3 times because 0o400 >> 9 = 0
for what in "rwx":
if mode & test:
perms.append(what)
else:
perms.append('-')
test >>= 1
self.permissions = ''.join(perms)
return self.permissions
def load_if_outdated(self):
"""Calls load() if the currently cached information is outdated"""
if not self.loaded:
self.load()
return True
try:
real_ctime = lstat(self.path).st_ctime
except OSError:
real_ctime = None
if not self.stat or self.stat.st_ctime != real_ctime:
self.load()
return True
return False
def _set_linemode(self, mode):
self._linemode = mode