Debian Codegraph @

hgext/remotefilelog/shallowutil.py

raw
1 # shallowutil.py -- remotefilelog utilities
2 #
3 # Copyright 2014 Facebook, Inc.
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 from __future__ import annotations
9
10 import collections
11 import os
12 import stat
13 import struct
14 import tempfile
15
16 from mercurial.i18n import _
17 from mercurial.node import hex
18 from mercurial import (
19 error,
20 pycompat,
21 revlog,
22 util,
23 )
24 from mercurial.utils import (
25 hashutil,
26 storageutil,
27 stringutil,
28 )
29 from . import constants
30
31 if not pycompat.iswindows:
32 import grp
33
34
35 def isenabled(repo):
36 """returns whether the repository is remotefilelog enabled or not"""
37 return constants.SHALLOWREPO_REQUIREMENT in repo.requirements
38
39
40 def getcachekey(reponame, file, id):
41 pathhash = hex(hashutil.sha1(file).digest())
42 return os.path.join(reponame, pathhash[:2], pathhash[2:], id)
43
44
45 def getlocalkey(file, id):
46 pathhash = hex(hashutil.sha1(file).digest())
47 return os.path.join(pathhash, id)
48
49
50 def getcachepath(ui, allowempty=False):
51 cachepath = ui.config(b"remotefilelog", b"cachepath")
52 if not cachepath:
53 if allowempty:
54 return None
55 else:
56 raise error.Abort(
57 _(b"could not find config option remotefilelog.cachepath")
58 )
59 return util.expandpath(cachepath)
60
61
62 def getcachepackpath(repo, category):
63 cachepath = getcachepath(repo.ui)
64 if category != constants.FILEPACK_CATEGORY:
65 return os.path.join(cachepath, repo.name, b'packs', category)
66 else:
67 return os.path.join(cachepath, repo.name, b'packs')
68
69
70 def getlocalpackpath(base, category):
71 return os.path.join(base, b'packs', category)
72
73
74 def createrevlogtext(text, copyfrom=None, copyrev=None):
75 """returns a string that matches the revlog contents in a
76 traditional revlog
77 """
78 meta = {}
79 if copyfrom or text.startswith(b'\1\n'):
80 if copyfrom:
81 meta[b'copy'] = copyfrom
82 meta[b'copyrev'] = copyrev
83 text = storageutil.packmeta(meta, text)
84
85 return text
86
87
88 def parsemeta(text):
89 """parse mercurial filelog metadata"""
90 meta, size = storageutil.parsemeta(text)
91 if text.startswith(b'\1\n'):
92 s = text.index(b'\1\n', 2)
93 text = text[s + 2 :]
94 return meta or {}, text
95
96
97 def sumdicts(*dicts):
98 """Adds all the values of *dicts together into one dictionary. This assumes
99 the values in *dicts are all summable.
100
101 e.g. [{'a': 4', 'b': 2}, {'b': 3, 'c': 1}] -> {'a': 4, 'b': 5, 'c': 1}
102 """
103 result = collections.defaultdict(int)
104 for dict in dicts:
105 for k, v in dict.items():
106 result[k] += v
107 return result
108
109
110 def prefixkeys(dict, prefix):
111 """Returns ``dict`` with ``prefix`` prepended to all its keys."""
112 result = {}
113 for k, v in dict.items():
114 result[prefix + k] = v
115 return result
116
117
118 def reportpackmetrics(ui, prefix, *stores):
119 dicts = [s.getmetrics() for s in stores]
120 dict = prefixkeys(sumdicts(*dicts), prefix + b'_')
121 ui.log(prefix + b"_packsizes", b"\n", **pycompat.strkwargs(dict))
122
123
124 def _parsepackmeta(metabuf):
125 """parse datapack meta, bytes (<metadata-list>) -> dict
126
127 The dict contains raw content - both keys and values are strings.
128 Upper-level business may want to convert some of them to other types like
129 integers, on their own.
130
131 raise ValueError if the data is corrupted
132 """
133 metadict = {}
134 offset = 0
135 buflen = len(metabuf)
136 while buflen - offset >= 3:
137 key = metabuf[offset : offset + 1]
138 offset += 1
139 metalen = struct.unpack_from(b'!H', metabuf, offset)[0]
140 offset += 2
141 if offset + metalen > buflen:
142 raise ValueError(b'corrupted metadata: incomplete buffer')
143 value = metabuf[offset : offset + metalen]
144 metadict[key] = value
145 offset += metalen
146 if offset != buflen:
147 raise ValueError(b'corrupted metadata: redundant data')
148 return metadict
149
150
151 def _buildpackmeta(metadict):
152 """reverse of _parsepackmeta, dict -> bytes (<metadata-list>)
153
154 The dict contains raw content - both keys and values are strings.
155 Upper-level business may want to serialize some of other types (like
156 integers) to strings before calling this function.
157
158 raise ProgrammingError when metadata key is illegal, or ValueError if
159 length limit is exceeded
160 """
161 metabuf = b''
162 for k, v in sorted((metadict or {}).items()):
163 if len(k) != 1:
164 raise error.ProgrammingError(b'packmeta: illegal key: %s' % k)
165 if len(v) > 0xFFFE:
166 raise ValueError(
167 b'metadata value is too long: 0x%x > 0xfffe' % len(v)
168 )
169 metabuf += k
170 metabuf += struct.pack(b'!H', len(v))
171 metabuf += v
172 # len(metabuf) is guaranteed representable in 4 bytes, because there are
173 # only 256 keys, and for each value, len(value) <= 0xfffe.
174 return metabuf
175
176
177 _metaitemtypes = {
178 constants.METAKEYFLAG: (int, int),
179 constants.METAKEYSIZE: (int, int),
180 }
181
182
183 def buildpackmeta(metadict):
184 """like _buildpackmeta, but typechecks metadict and normalize it.
185
186 This means, METAKEYSIZE and METAKEYSIZE should have integers as values,
187 and METAKEYFLAG will be dropped if its value is 0.
188 """
189 newmeta = {}
190 for k, v in (metadict or {}).items():
191 expectedtype = _metaitemtypes.get(k, (bytes,))
192 if not isinstance(v, expectedtype):
193 raise error.ProgrammingError(b'packmeta: wrong type of key %s' % k)
194 # normalize int to binary buffer
195 if int in expectedtype:
196 # optimization: remove flag if it's 0 to save space
197 if k == constants.METAKEYFLAG and v == 0:
198 continue
199 v = int2bin(v)
200 newmeta[k] = v
201 return _buildpackmeta(newmeta)
202
203
204 def parsepackmeta(metabuf):
205 """like _parsepackmeta, but convert fields to desired types automatically.
206
207 This means, METAKEYFLAG and METAKEYSIZE fields will be converted to
208 integers.
209 """
210 metadict = _parsepackmeta(metabuf)
211 for k, v in metadict.items():
212 if k in _metaitemtypes and int in _metaitemtypes[k]:
213 metadict[k] = bin2int(v)
214 return metadict
215
216
217 def int2bin(n):
218 """convert a non-negative integer to raw binary buffer"""
219 buf = bytearray()
220 while n > 0:
221 buf.insert(0, n & 0xFF)
222 n >>= 8
223 return bytes(buf)
224
225
226 def bin2int(buf):
227 """the reverse of int2bin, convert a binary buffer to an integer"""
228 x = 0
229 for b in bytearray(buf):
230 x <<= 8
231 x |= b
232 return x
233
234
235 class BadRemotefilelogHeader(error.StorageError):
236 """Exception raised when parsing a remotefilelog blob header fails."""
237
238
239 def parsesizeflags(raw):
240 """given a remotefilelog blob, return (headersize, rawtextsize, flags)
241
242 see remotefilelogserver.createfileblob for the format.
243 raise RuntimeError if the content is illformed.
244 """
245 flags = revlog.REVIDX_DEFAULT_FLAGS
246 size = None
247 try:
248 index = raw.index(b'\0')
249 except ValueError:
250 raise BadRemotefilelogHeader(
251 b"unexpected remotefilelog header: illegal format"
252 )
253 header = raw[:index]
254 if header.startswith(b'v'):
255 # v1 and above, header starts with 'v'
256 if header.startswith(b'v1\n'):
257 for s in header.split(b'\n'):
258 if s.startswith(constants.METAKEYSIZE):
259 size = int(s[len(constants.METAKEYSIZE) :])
260 elif s.startswith(constants.METAKEYFLAG):
261 flags = int(s[len(constants.METAKEYFLAG) :])
262 else:
263 raise BadRemotefilelogHeader(
264 b'unsupported remotefilelog header: %s' % header
265 )
266 else:
267 # v0, str(int(size)) is the header
268 size = int(header)
269 if size is None:
270 raise BadRemotefilelogHeader(
271 b"unexpected remotefilelog header: no size found"
272 )
273 return index + 1, size, flags
274
275
276 def buildfileblobheader(size, flags, version=None):
277 """return the header of a remotefilelog blob.
278
279 see remotefilelogserver.createfileblob for the format.
280 approximately the reverse of parsesizeflags.
281
282 version could be 0 or 1, or None (auto decide).
283 """
284 # choose v0 if flags is empty, otherwise v1
285 if version is None:
286 version = int(bool(flags))
287 if version == 1:
288 header = b'v1\n%s%d\n%s%d' % (
289 constants.METAKEYSIZE,
290 size,
291 constants.METAKEYFLAG,
292 flags,
293 )
294 elif version == 0:
295 if flags:
296 raise error.ProgrammingError(b'fileblob v0 does not support flag')
297 header = b'%d' % size
298 else:
299 raise error.ProgrammingError(b'unknown fileblob version %d' % version)
300 return header
301
302
303 def ancestormap(raw):
304 offset, size, flags = parsesizeflags(raw)
305 start = offset + size
306
307 mapping = {}
308 while start < len(raw):
309 divider = raw.index(b'\0', start + 80)
310
311 currentnode = raw[start : (start + 20)]
312 p1 = raw[(start + 20) : (start + 40)]
313 p2 = raw[(start + 40) : (start + 60)]
314 linknode = raw[(start + 60) : (start + 80)]
315 copyfrom = raw[(start + 80) : divider]
316
317 mapping[currentnode] = (p1, p2, linknode, copyfrom)
318 start = divider + 1
319
320 return mapping
321
322
323 def readfile(path):
324 result = util.readfile(path)
325
326 # we should never have empty files
327 if not result:
328 os.remove(path)
329 raise OSError(b"empty file: %s" % path)
330
331 return result
332
333
334 def unlinkfile(filepath):
335 if pycompat.iswindows:
336 # On Windows, os.unlink cannnot delete readonly files
337 os.chmod(filepath, stat.S_IWUSR)
338 os.unlink(filepath)
339
340
341 def renamefile(source, destination):
342 if pycompat.iswindows:
343 # On Windows, os.rename cannot rename readonly files
344 # and cannot overwrite destination if it exists
345 os.chmod(source, stat.S_IWUSR)
346 if os.path.isfile(destination):
347 os.chmod(destination, stat.S_IWUSR)
348 os.unlink(destination)
349
350 os.rename(source, destination)
351
352
353 def writefile(path, content, readonly=False):
354 dirname, filename = os.path.split(path)
355 if not os.path.exists(dirname):
356 try:
357 os.makedirs(dirname)
358 except FileExistsError:
359 pass
360
361 fd, temp = tempfile.mkstemp(prefix=b'.%s-' % filename, dir=dirname)
362 os.close(fd)
363
364 try:
365 f = util.posixfile(temp, b'wb')
366 f.write(content)
367 f.close()
368
369 if readonly:
370 mode = 0o444
371 else:
372 # tempfiles are created with 0o600, so we need to manually set the
373 # mode.
374 oldumask = os.umask(0)
375 # there's no way to get the umask without modifying it, so set it
376 # back
377 os.umask(oldumask)
378 mode = ~oldumask
379
380 renamefile(temp, path)
381 os.chmod(path, mode)
382 except Exception:
383 try:
384 unlinkfile(temp)
385 except OSError:
386 pass
387 raise
388
389
390 def sortnodes(nodes, parentfunc):
391 """Topologically sorts the nodes, using the parentfunc to find
392 the parents of nodes."""
393 nodes = set(nodes)
394 childmap = {}
395 parentmap = {}
396 roots = []
397
398 # Build a child and parent map
399 for n in nodes:
400 parents = [p for p in parentfunc(n) if p in nodes]
401 parentmap[n] = set(parents)
402 for p in parents:
403 childmap.setdefault(p, set()).add(n)
404 if not parents:
405 roots.append(n)
406
407 roots.sort()
408 # Process roots, adding children to the queue as they become roots
409 results = []
410 while roots:
411 n = roots.pop(0)
412 results.append(n)
413 if n in childmap:
414 children = childmap[n]
415 for c in children:
416 childparents = parentmap[c]
417 childparents.remove(n)
418 if len(childparents) == 0:
419 # insert at the beginning, that way child nodes
420 # are likely to be output immediately after their
421 # parents. This gives better compression results.
422 roots.insert(0, c)
423
424 return results
425
426
427 def readexactly(stream, n):
428 '''read n bytes from stream.read and abort if less was available'''
429 s = stream.read(n)
430 if len(s) < n:
431 raise error.Abort(
432 _(b"stream ended unexpectedly (got %d bytes, expected %d)")
433 % (len(s), n)
434 )
435 return s
436
437
438 def readunpack(stream, fmt):
439 data = readexactly(stream, struct.calcsize(fmt))
440 return struct.unpack(fmt, data)
441
442
443 def readpath(stream):
444 rawlen = readexactly(stream, constants.FILENAMESIZE)
445 pathlen = struct.unpack(constants.FILENAMESTRUCT, rawlen)[0]
446 return readexactly(stream, pathlen)
447
448
449 def readnodelist(stream):
450 rawlen = readexactly(stream, constants.NODECOUNTSIZE)
451 nodecount = struct.unpack(constants.NODECOUNTSTRUCT, rawlen)[0]
452 for i in range(nodecount):
453 yield readexactly(stream, constants.NODESIZE)
454
455
456 def readpathlist(stream):
457 rawlen = readexactly(stream, constants.PATHCOUNTSIZE)
458 pathcount = struct.unpack(constants.PATHCOUNTSTRUCT, rawlen)[0]
459 for i in range(pathcount):
460 yield readpath(stream)
461
462
463 def getgid(groupname):
464 try:
465 gid = grp.getgrnam(pycompat.fsdecode(groupname)).gr_gid
466 return gid
467 except KeyError:
468 return None
469
470
471 def setstickygroupdir(path, gid, warn=None):
472 if gid is None:
473 return
474 try:
475 os.chown(path, -1, gid)
476 os.chmod(path, 0o2775)
477 except OSError as ex:
478 if warn:
479 warn(_(b'unable to chown/chmod on %s: %s\n') % (path, ex))
480
481
482 def mkstickygroupdir(ui, path):
483 """Creates the given directory (if it doesn't exist) and give it a
484 particular group with setgid enabled."""
485 gid = None
486 groupname = ui.config(b"remotefilelog", b"cachegroup")
487 if groupname:
488 gid = getgid(groupname)
489 if gid is None:
490 ui.warn(_(b'unable to resolve group name: %s\n') % groupname)
491
492 # we use a single stat syscall to test the existence and mode / group bit
493 st = None
494 try:
495 st = os.stat(path)
496 except OSError:
497 pass
498
499 if st:
500 # exists
501 if (st.st_mode & 0o2775) != 0o2775 or st.st_gid != gid:
502 # permission needs to be fixed
503 setstickygroupdir(path, gid, ui.warn)
504 return
505
506 oldumask = os.umask(0o002)
507 try:
508 missingdirs = [path]
509 path = os.path.dirname(path)
510 while path and not os.path.exists(path):
511 missingdirs.append(path)
512 path = os.path.dirname(path)
513
514 for path in reversed(missingdirs):
515 try:
516 os.mkdir(path)
517 except FileExistsError:
518 pass
519
520 for path in missingdirs:
521 setstickygroupdir(path, gid, ui.warn)
522 finally:
523 os.umask(oldumask)
524
525
526 def getusername(ui):
527 try:
528 return stringutil.shortuser(ui.username())
529 except Exception:
530 return b'unknown'
531
532
533 def getreponame(ui):
534 reponame = ui.config(b'paths', b'default')
535 if reponame:
536 return os.path.basename(reponame)
537 return b"unknown"