- Notifications
You must be signed in to change notification settings - Fork68
Expand file tree
/
Copy pathloose.py
More file actions
268 lines (231 loc) · 8.52 KB
/
loose.py
File metadata and controls
268 lines (231 loc) · 8.52 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
# 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: https://opensource.org/license/bsd-3-clause/
fromcontextlibimportsuppress
fromgitdb.db.baseimport (
FileDBBase,
ObjectDBR,
ObjectDBW
)
fromgitdb.excimport (
BadObject,
AmbiguousObjectName
)
fromgitdb.streamimport (
DecompressMemMapReader,
FDCompressedSha1Writer,
FDStream,
Sha1Writer
)
fromgitdb.baseimport (
OStream,
OInfo
)
fromgitdb.utilimport (
file_contents_ro_filepath,
ENOENT,
hex_to_bin,
bin_to_hex,
exists,
chmod,
isfile,
remove,
rename,
dirname,
basename,
join
)
fromgitdb.funimport (
chunk_size,
loose_object_header_info,
write_object,
stream_copy
)
fromgitdb.utils.encodingimportforce_bytes
importtempfile
importos
importsys
importtime
__all__= ('LooseObjectDB', )
classLooseObjectDB(FileDBBase,ObjectDBR,ObjectDBW):
"""A database which operates on loose object files"""
# CONFIGURATION
# chunks in which data will be copied between streams
stream_chunk_size=chunk_size
# On windows we need to keep it writable, otherwise it cannot be removed
# either
new_objects_mode=int("444",8)
ifos.name=='nt':
new_objects_mode=int("644",8)
def__init__(self,root_path):
super().__init__(root_path)
self._hexsha_to_file=dict()
# Additional Flags - might be set to 0 after the first failure
# Depending on the root, this might work for some mounts, for others not, which
# is why it is per instance
self._fd_open_flags=getattr(os,'O_NOATIME',0)
#{ Interface
defobject_path(self,hexsha):
"""
:return: path at which the object with the given hexsha would be stored,
relative to the database root"""
returnjoin(hexsha[:2],hexsha[2:])
defreadable_db_object_path(self,hexsha):
"""
:return: readable object path to the object identified by hexsha
:raise BadObject: If the object file does not exist"""
withsuppress(KeyError):
returnself._hexsha_to_file[hexsha]
# END ignore cache misses
# try filesystem
path=self.db_path(self.object_path(hexsha))
ifexists(path):
self._hexsha_to_file[hexsha]=path
returnpath
# END handle cache
raiseBadObject(hexsha)
defpartial_to_complete_sha_hex(self,partial_hexsha):
""":return: 20 byte binary sha1 string which matches the given name uniquely
:param name: hexadecimal partial name (bytes or ascii string)
:raise AmbiguousObjectName:
:raise BadObject: """
candidate=None
forbinshainself.sha_iter():
ifbin_to_hex(binsha).startswith(force_bytes(partial_hexsha)):
# it can't ever find the same object twice
ifcandidateisnotNone:
raiseAmbiguousObjectName(partial_hexsha)
candidate=binsha
# END for each object
ifcandidateisNone:
raiseBadObject(partial_hexsha)
returncandidate
#} END interface
def_map_loose_object(self,sha):
"""
:return: memory map of that file to allow random read access
:raise BadObject: if object could not be located"""
db_path=self.db_path(self.object_path(bin_to_hex(sha)))
try:
returnfile_contents_ro_filepath(db_path,flags=self._fd_open_flags)
exceptOSErrorase:
ife.errno!=ENOENT:
# try again without noatime
try:
returnfile_contents_ro_filepath(db_path)
exceptOSErrorasnew_e:
raiseBadObject(sha)fromnew_e
# didn't work because of our flag, don't try it again
self._fd_open_flags=0
else:
raiseBadObject(sha)frome
# END handle error
# END exception handling
defset_ostream(self,stream):
""":raise TypeError: if the stream does not support the Sha1Writer interface"""
ifstreamisnotNoneandnotisinstance(stream,Sha1Writer):
raiseTypeError("Output stream musst support the %s interface"%Sha1Writer.__name__)
returnsuper().set_ostream(stream)
definfo(self,sha):
m=self._map_loose_object(sha)
try:
typ,size=loose_object_header_info(m)
returnOInfo(sha,typ,size)
finally:
ifhasattr(m,'close'):
m.close()
# END assure release of system resources
defstream(self,sha):
m=self._map_loose_object(sha)
type,size,stream=DecompressMemMapReader.new(m,close_on_deletion=True)
returnOStream(sha,type,size,stream)
defhas_object(self,sha):
try:
self.readable_db_object_path(bin_to_hex(sha))
returnTrue
exceptBadObject:
returnFalse
# END check existence
defstore(self,istream):
"""note: The sha we produce will be hex by nature"""
tmp_path=None
writer=self.ostream()
ifwriterisNone:
# open a tmp file to write the data to
fd,tmp_path=tempfile.mkstemp(prefix='obj',dir=self._root_path)
ifistream.binshaisNone:
writer=FDCompressedSha1Writer(fd)
else:
writer=FDStream(fd)
# END handle direct stream copies
# END handle custom writer
try:
try:
ifistream.binshaisnotNone:
# copy as much as possible, the actual uncompressed item size might
# be smaller than the compressed version
stream_copy(istream.read,writer.write,sys.maxsize,self.stream_chunk_size)
else:
# write object with header, we have to make a new one
write_object(istream.type,istream.size,istream.read,writer.write,
chunk_size=self.stream_chunk_size)
# END handle direct stream copies
finally:
iftmp_path:
writer.close()
# END assure target stream is closed
except:
iftmp_path:
remove(tmp_path)
raise
# END assure tmpfile removal on error
hexsha=None
ifistream.binsha:
hexsha=istream.hexsha
else:
hexsha=writer.sha(as_hex=True)
# END handle sha
iftmp_path:
obj_path=self.db_path(self.object_path(hexsha))
obj_dir=dirname(obj_path)
os.makedirs(obj_dir,exist_ok=True)
# END handle destination directory
# rename onto existing doesn't work on NTFS
ifisfile(obj_path):
remove(tmp_path)
else:
rename(tmp_path,obj_path)
# end rename only if needed
# Ensure rename is actually done and file is stable
# Retry up to 14 times - quadratic wait & retry in ms.
# The total maximum wait time is 1000ms, which should be vastly enough for the
# OS to return and commit the file to disk.
forbackoff_msin [1,4,9,16,25,36,49,64,81,100,121,144,169,181]:
withsuppress(PermissionError):
# make sure its readable for all ! It started out as rw-- tmp file
# but needs to be rwrr
chmod(obj_path,self.new_objects_mode)
break
time.sleep(backoff_ms/1000.0)
else:
raisePermissionError(
"Impossible to apply `chmod` to file {}".format(obj_path)
)
# END handle dry_run
istream.binsha=hex_to_bin(hexsha)
returnistream
defsha_iter(self):
# find all files which look like an object, extract sha from there
forroot,dirs,filesinos.walk(self.root_path()):
root_base=basename(root)
iflen(root_base)!=2:
continue
forfinfiles:
iflen(f)!=38:
continue
yieldhex_to_bin(root_base+f)
# END for each file
# END for each walk iteration
defsize(self):
returnlen(tuple(self.sha_iter()))