- Notifications
You must be signed in to change notification settings - Fork68
Expand file tree
/
Copy pathutil.py
More file actions
370 lines (300 loc) · 11.6 KB
/
util.py
File metadata and controls
370 lines (300 loc) · 11.6 KB
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# Copyright (C) 2010, 2011 Sebastian Thiel (byronimo@gmail.com) and contributors
#
# This module is part of GitDB and is released under
# the New BSD License: http://www.opensource.org/licenses/bsd-license.php
importbinascii
importos
importmmap
importsys
importerrno
fromioimportStringIO
fromsmmapimport (
StaticWindowMapManager,
SlidingWindowMapManager,
SlidingWindowMapBuffer
)
# initialize our global memory manager instance
# Use it to free cached (and unused) resources.
ifsys.version_info[1]<6:
mman=StaticWindowMapManager()
else:
mman=SlidingWindowMapManager()
#END handle mman
importhashlib
try:
fromstructimportunpack_from
exceptImportError:
fromstructimportunpack,calcsize
__calcsize_cache=dict()
defunpack_from(fmt,data,offset=0):
try:
size=__calcsize_cache[fmt]
exceptKeyError:
size=calcsize(fmt)
__calcsize_cache[fmt]=size
# END exception handling
returnunpack(fmt,data[offset :offset+size])
# END own unpack_from implementation
#{ Aliases
hex_to_bin=binascii.a2b_hex
bin_to_hex=binascii.b2a_hex
# errors
ENOENT=errno.ENOENT
# os shortcuts
exists=os.path.exists
mkdir=os.mkdir
chmod=os.chmod
isdir=os.path.isdir
isfile=os.path.isfile
rename=os.rename
remove=os.remove
dirname=os.path.dirname
basename=os.path.basename
join=os.path.join
read=os.read
write=os.write
close=os.close
fsync=os.fsync
# Backwards compatibility imports
fromgitdb.constimport (
NULL_BIN_SHA,
NULL_HEX_SHA
)
#} END Aliases
#{ compatibility stuff ...
class_RandomAccessStringIO(object):
"""Wrapper to provide required functionality in case memory maps cannot or may
not be used. This is only really required in python 2.4"""
__slots__='_sio'
def__init__(self,buf=''):
self._sio=StringIO(buf)
def__getattr__(self,attr):
returngetattr(self._sio,attr)
def__len__(self):
returnlen(self.getvalue())
def__getitem__(self,i):
returnself.getvalue()[i]
def__getslice__(self,start,end):
returnself.getvalue()[start:end]
defbyte_ord(b):
"""
Return the integer representation of the byte string. This supports Python
3 byte arrays as well as standard strings.
"""
try:
returnord(b)
exceptTypeError:
returnb
#} END compatibility stuff ...
#{ Routines
defmake_sha(source=''.encode("ascii")):
"""A python2.4 workaround for the sha/hashlib module fiasco
**Note** From the dulwich project """
try:
returnhashlib.sha1(source)
exceptNameError:
importsha
sha1=sha.sha(source)
returnsha1
defallocate_memory(size):
""":return: a file-protocol accessible memory block of the given size"""
ifsize==0:
return_RandomAccessStringIO('')
# END handle empty chunks gracefully
try:
returnmmap.mmap(-1,size)# read-write by default
exceptEnvironmentError:
# setup real memory instead
# this of course may fail if the amount of memory is not available in
# one chunk - would only be the case in python 2.4, being more likely on
# 32 bit systems.
return_RandomAccessStringIO("\0"*size)
# END handle memory allocation
deffile_contents_ro(fd,stream=False,allow_mmap=True):
""":return: read-only contents of the file represented by the file descriptor fd
:param fd: file descriptor opened for reading
:param stream: if False, random access is provided, otherwise the stream interface
is provided.
:param allow_mmap: if True, its allowed to map the contents into memory, which
allows large files to be handled and accessed efficiently. The file-descriptor
will change its position if this is False"""
try:
ifallow_mmap:
# supports stream and random access
try:
returnmmap.mmap(fd,0,access=mmap.ACCESS_READ)
exceptEnvironmentError:
# python 2.4 issue, 0 wants to be the actual size
returnmmap.mmap(fd,os.fstat(fd).st_size,access=mmap.ACCESS_READ)
# END handle python 2.4
exceptOSError:
pass
# END exception handling
# read manully
contents=os.read(fd,os.fstat(fd).st_size)
ifstream:
return_RandomAccessStringIO(contents)
returncontents
deffile_contents_ro_filepath(filepath,stream=False,allow_mmap=True,flags=0):
"""Get the file contents at filepath as fast as possible
:return: random access compatible memory of the given filepath
:param stream: see ``file_contents_ro``
:param allow_mmap: see ``file_contents_ro``
:param flags: additional flags to pass to os.open
:raise OSError: If the file could not be opened
**Note** for now we don't try to use O_NOATIME directly as the right value needs to be
shared per database in fact. It only makes a real difference for loose object
databases anyway, and they use it with the help of the ``flags`` parameter"""
fd=os.open(filepath,os.O_RDONLY|getattr(os,'O_BINARY',0)|flags)
try:
returnfile_contents_ro(fd,stream,allow_mmap)
finally:
close(fd)
# END assure file is closed
defsliding_ro_buffer(filepath,flags=0):
"""
:return: a buffer compatible object which uses our mapped memory manager internally
ready to read the whole given filepath"""
returnSlidingWindowMapBuffer(mman.make_cursor(filepath),flags=flags)
defto_hex_sha(sha):
""":return: hexified version of sha"""
iflen(sha)==40:
returnsha
returnbin_to_hex(sha)
defto_bin_sha(sha):
iflen(sha)==20:
returnsha
returnhex_to_bin(sha)
#} END routines
#{ Utilities
classLazyMixin(object):
"""
Base class providing an interface to lazily retrieve attribute values upon
first access. If slots are used, memory will only be reserved once the attribute
is actually accessed and retrieved the first time. All future accesses will
return the cached value as stored in the Instance's dict or slot.
"""
__slots__=tuple()
def__getattr__(self,attr):
"""
Whenever an attribute is requested that we do not know, we allow it
to be created and set. Next time the same attribute is reqeusted, it is simply
returned from our dict/slots. """
self._set_cache_(attr)
# will raise in case the cache was not created
returnobject.__getattribute__(self,attr)
def_set_cache_(self,attr):
"""
This method should be overridden in the derived class.
It should check whether the attribute named by attr can be created
and cached. Do nothing if you do not know the attribute or call your subclass
The derived class may create as many additional attributes as it deems
necessary in case a git command returns more information than represented
in the single attribute."""
pass
classLockedFD(object):
"""
This class facilitates a safe read and write operation to a file on disk.
If we write to 'file', we obtain a lock file at 'file.lock' and write to
that instead. If we succeed, the lock file will be renamed to overwrite
the original file.
When reading, we obtain a lock file, but to prevent other writers from
succeeding while we are reading the file.
This type handles error correctly in that it will assure a consistent state
on destruction.
**note** with this setup, parallel reading is not possible"""
__slots__= ("_filepath",'_fd','_write')
def__init__(self,filepath):
"""Initialize an instance with the givne filepath"""
self._filepath=filepath
self._fd=None
self._write=None# if True, we write a file
def__del__(self):
# will do nothing if the file descriptor is already closed
ifself._fdisnotNone:
self.rollback()
def_lockfilepath(self):
return"%s.lock"%self._filepath
defopen(self,write=False,stream=False):
"""
Open the file descriptor for reading or writing, both in binary mode.
:param write: if True, the file descriptor will be opened for writing. Other
wise it will be opened read-only.
:param stream: if True, the file descriptor will be wrapped into a simple stream
object which supports only reading or writing
:return: fd to read from or write to. It is still maintained by this instance
and must not be closed directly
:raise IOError: if the lock could not be retrieved
:raise OSError: If the actual file could not be opened for reading
**note** must only be called once"""
ifself._writeisnotNone:
raiseAssertionError("Called %s multiple times"%self.open)
self._write=write
# try to open the lock file
binary=getattr(os,'O_BINARY',0)
lockmode=os.O_WRONLY|os.O_CREAT|os.O_EXCL|binary
try:
fd=os.open(self._lockfilepath(),lockmode,int("600",8))
ifnotwrite:
os.close(fd)
else:
self._fd=fd
# END handle file descriptor
exceptOSError:
raiseIOError("Lock at %r could not be obtained"%self._lockfilepath())
# END handle lock retrieval
# open actual file if required
ifself._fdisNone:
# we could specify exlusive here, as we obtained the lock anyway
try:
self._fd=os.open(self._filepath,os.O_RDONLY|binary)
except:
# assure we release our lockfile
os.remove(self._lockfilepath())
raise
# END handle lockfile
# END open descriptor for reading
ifstream:
# need delayed import
fromgitdb.streamimportFDStream
returnFDStream(self._fd)
else:
returnself._fd
# END handle stream
defcommit(self):
"""When done writing, call this function to commit your changes into the
actual file.
The file descriptor will be closed, and the lockfile handled.
**Note** can be called multiple times"""
self._end_writing(successful=True)
defrollback(self):
"""Abort your operation without any changes. The file descriptor will be
closed, and the lock released.
**Note** can be called multiple times"""
self._end_writing(successful=False)
def_end_writing(self,successful=True):
"""Handle the lock according to the write mode """
ifself._writeisNone:
raiseAssertionError("Cannot end operation if it wasn't started yet")
ifself._fdisNone:
return
os.close(self._fd)
self._fd=None
lockfile=self._lockfilepath()
ifself._writeandsuccessful:
# on windows, rename does not silently overwrite the existing one
ifsys.platform=="win32":
ifisfile(self._filepath):
os.remove(self._filepath)
# END remove if exists
# END win32 special handling
os.rename(lockfile,self._filepath)
# assure others can at least read the file - the tmpfile left it at rw--
# We may also write that file, on windows that boils down to a remove-
# protection as well
chmod(self._filepath,int("644",8))
else:
# just delete the file so far, we failed
os.remove(lockfile)
# END successful handling
#} END utilities