Repository navigation
Expand file tree
/
Copy pathgitobj.py
More file actions
490 lines (422 loc) · 16.4 KB
/
Copy pathgitobj.py
File metadata and controls
490 lines (422 loc) · 16.4 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
"""Git object model, packfiles and the pkt-line wire format.
Pure standard library. No git binary, no subprocess. Written from the git
pack and protocol specifications as exercised by the conformance suite:
objects are content-addressed by SHA-1, packs carry full objects only
(no deltas on write; deltas are resolved on read), and the smart-HTTP
exchange is pkt-line framed with sideband band 1 carrying pack data.
"""
import hashlib
import struct
import zlib
ZERO_OID = "0" * 40
TYPE_CODE = {"commit": 1, "tree": 2, "blob": 3, "tag": 4}
CODE_TYPE = {1: "commit", 2: "tree", 3: "blob", 4: "tag", 6: "ofs-delta", 7: "ref-delta"}
def hash_object(obj_type, data):
"""SHA-1 id of a git object: "<type> <len>\\0<data>"."""
header = ("%s %d\0" % (obj_type, len(data))).encode("ascii")
return hashlib.sha1(header + data).hexdigest()
def object_header(obj_type, size):
return ("%s %d\0" % (obj_type, size)).encode("ascii")
# ---------------------------------------------------------------------------
# pkt-line framing
# ---------------------------------------------------------------------------
def pkt_line(payload):
"""Encode one pkt-line. payload is bytes (without the 4-byte length)."""
if isinstance(payload, str):
payload = payload.encode("utf-8")
total = len(payload) + 4
return ("%04x" % total).encode("ascii") + payload
def pkt_flush():
return b"0000"
def pkt_delim():
return b"0001"
def pkt_lines(items):
"""Encode a list of str/bytes/'flush'/'delim' into one byte string."""
out = bytearray()
for item in items:
if item == "flush":
out += pkt_flush()
elif item == "delim":
out += pkt_delim()
else:
out += pkt_line(item)
return bytes(out)
class PktLineError(Exception):
pass
def decode_pkt_lines(data, allow_trailing=False):
"""Decode a whole buffer into a list of packets.
Each packet is ('data', bytes), ('flush', None) or ('delim', None).
"""
packets = []
pos = 0
n = len(data)
while pos < n:
if pos + 4 > n:
raise PktLineError("truncated pkt-line length")
length_hex = data[pos:pos + 4]
try:
length = int(length_hex.decode("ascii"), 16)
except ValueError:
raise PktLineError("bad pkt-line length %r" % length_hex)
if length == 0:
packets.append(("flush", None))
pos += 4
elif length == 1:
packets.append(("delim", None))
pos += 4
elif length == 2:
packets.append(("response-end", None))
pos += 4
elif length == 3:
raise PktLineError("pkt-line length 3 is invalid")
else:
if pos + length > n:
if allow_trailing:
break
raise PktLineError("truncated pkt-line payload")
packets.append(("data", data[pos + 4:pos + length]))
pos += length
return packets
def sideband_pack(pack_bytes, chunk=60000):
"""Wrap pack bytes in sideband band-1 pkt-lines."""
out = bytearray()
for i in range(0, len(pack_bytes), chunk):
out += pkt_line(b"\x01" + pack_bytes[i:i + chunk])
return bytes(out)
def sideband_text(text, band=2):
"""Wrap a progress/error line in a sideband pkt-line."""
if isinstance(text, str):
text = text.encode("utf-8")
return pkt_line(bytes([band]) + text)
# ---------------------------------------------------------------------------
# Trees and commits
# ---------------------------------------------------------------------------
def build_tree(entries):
"""Build a tree object from [(mode, name, oid)].
Entries are sorted the way git sorts them: by name, with a directory
compared as if its name ended with '/'.
"""
def sort_key(entry):
mode, name, _oid = entry
if mode == "40000":
return name + "/"
return name
ordered = sorted(entries, key=sort_key)
out = bytearray()
for mode, name, oid in ordered:
out += ("%s %s\0" % (mode, name)).encode("utf-8")
out += bytes.fromhex(oid)
return bytes(out)
def parse_tree(data):
"""Parse a tree object into [(mode, name, oid)]."""
entries = []
pos = 0
n = len(data)
while pos < n:
sp = data.index(b" ", pos)
mode = data[pos:sp].decode("ascii")
nul = data.index(b"\0", sp)
name = data[sp + 1:nul].decode("utf-8", "surrogateescape")
oid = data[nul + 1:nul + 21].hex()
entries.append((mode, name, oid))
pos = nul + 21
return entries
def build_commit(tree_oid, parents, message, author, committer, timestamp):
"""Build a commit object. Timestamp is an integer epoch; the timezone is
fixed at +0000 so the bytes are deterministic."""
lines = []
lines.append("tree %s\n" % tree_oid)
for parent in parents:
lines.append("parent %s\n" % parent)
ident = "%s %d +0000" % (author, timestamp)
lines.append("author %s\n" % ident)
lines.append("committer %s\n" % ident)
lines.append("\n")
body = "".join(lines).encode("utf-8")
msg = message if message.endswith("\n") else message + "\n"
return body + msg.encode("utf-8")
def parse_commit(data):
"""Parse a commit into a dict with tree, parents, author, committer, message."""
header, _, message = data.partition(b"\n\n")
result = {"tree": None, "parents": [], "author": "", "committer": "", "message": message.decode("utf-8", "surrogateescape")}
for line in header.decode("utf-8", "surrogateescape").split("\n"):
if line.startswith("tree "):
result["tree"] = line[5:].strip()
elif line.startswith("parent "):
result["parents"].append(line[7:].strip())
elif line.startswith("author "):
result["author"] = line[7:]
elif line.startswith("committer "):
result["committer"] = line[10:]
return result
def build_tag(obj_oid, obj_type, tag_name, message, tagger, timestamp):
lines = []
lines.append("object %s\n" % obj_oid)
lines.append("type %s\n" % obj_type)
lines.append("tag %s\n" % tag_name)
lines.append("tagger %s %d +0000\n" % (tagger, timestamp))
lines.append("\n")
body = "".join(lines).encode("utf-8")
msg = message if message.endswith("\n") else message + "\n"
return body + msg.encode("utf-8")
# ---------------------------------------------------------------------------
# Packfiles
# ---------------------------------------------------------------------------
def _pack_object_header(obj_type, size):
code = TYPE_CODE[obj_type]
out = bytearray()
first = (code << 4) | (size & 0x0F)
size >>= 4
while size:
out.append(first | 0x80)
first = size & 0x7F
size >>= 7
out.append(first)
return bytes(out)
def write_pack(objects):
"""Build a packfile from [(type, data)] with no deltas.
Returns bytes: "PACK" + version 2 + count, then each object as a
type/size header plus its zlib stream, then the SHA-1 trailer.
"""
objs = list(objects)
parts = [b"PACK" + struct.pack(">II", 2, len(objs))]
for obj_type, data in objs:
parts.append(_pack_object_header(obj_type, len(data)))
parts.append(zlib.compress(data))
body = b"".join(parts)
return body + hashlib.sha1(body).digest()
def verify_pack_checksum(pack):
if len(pack) < 20:
return False
return hashlib.sha1(pack[:-20]).digest() == pack[-20:]
class PackError(Exception):
pass
def _read_varint_size(buf, start):
if start >= len(buf):
raise PackError("pack entry has no size header")
byte = buf[start]
first = byte
size = byte & 0x0F
shift = 4
pos = start + 1
while byte & 0x80:
if pos >= len(buf):
raise PackError("pack entry size varint is truncated")
byte = buf[pos]
pos += 1
size += (byte & 0x7F) << shift
shift += 7
if shift > 63:
raise PackError("pack entry size varint is too long")
return size, pos, first
def _read_ofs_delta_base(buf, start):
if start >= len(buf):
raise PackError("ofs-delta has no base offset")
byte = buf[start]
pos = start + 1
value = byte & 0x7F
while byte & 0x80:
if pos >= len(buf):
raise PackError("ofs-delta base offset is truncated")
byte = buf[pos]
pos += 1
value = ((value + 1) << 7) + (byte & 0x7F)
return value, pos
def _inflate_at(buf, offset, end):
"""Inflate one zlib stream starting at offset. Returns (data, next_offset)."""
decomp = zlib.decompressobj()
chunk = buf[offset:end]
data = decomp.decompress(chunk)
data += decomp.flush()
consumed = len(chunk) - len(decomp.unused_data)
if consumed <= 0:
raise PackError("zlib stream at offset %d consumed no bytes" % offset)
return data, offset + consumed
def apply_delta(base, delta):
"""Apply a git delta instruction stream to base bytes."""
pos = 0
n = len(delta)
def read_size():
nonlocal pos
value = 0
shift = 0
while True:
if pos >= n:
raise PackError("delta size varint is truncated")
byte = delta[pos]
pos += 1
value += (byte & 0x7F) << shift
shift += 7
if not (byte & 0x80):
break
if shift > 63:
raise PackError("delta size varint is too long")
return value
source_size = read_size()
target_size = read_size()
if source_size != len(base):
raise PackError("delta expects a %d-byte base, got %d" % (source_size, len(base)))
out = bytearray()
while pos < n:
op = delta[pos]
pos += 1
if op & 0x80:
copy_offset = 0
copy_size = 0
shift = 0
for bit in range(4):
if op & (1 << bit):
if pos >= n:
raise PackError("delta copy offset is truncated")
copy_offset |= delta[pos] << shift
pos += 1
shift += 8
shift = 0
for bit in range(4, 7):
if op & (1 << bit):
if pos >= n:
raise PackError("delta copy size is truncated")
copy_size |= delta[pos] << shift
pos += 1
shift += 8
if copy_size == 0:
copy_size = 0x10000
if copy_offset + copy_size > len(base):
raise PackError("delta copy is out of the base")
out += base[copy_offset:copy_offset + copy_size]
elif op != 0:
literal = op & 0x7F
if pos + literal > n:
raise PackError("delta insert is truncated")
out += delta[pos:pos + literal]
pos += literal
else:
raise PackError("delta opcode 0 is invalid")
if len(out) != target_size:
raise PackError("delta produced %d of %d bytes" % (len(out), target_size))
return bytes(out)
def read_pack(pack, resolve_base=None):
"""Read a packfile and resolve every object, including deltas.
Returns (objects, delta_count) where objects maps oid -> (type, data).
resolve_base(oid) supplies a base object a thin pack leaves out.
"""
buf = pack
if len(buf) < 32:
raise PackError("pack is %d bytes, too short" % len(buf))
if buf[0:4] != b"PACK":
raise PackError("pack does not start with PACK")
version = struct.unpack(">I", buf[4:8])[0]
if version not in (2, 3):
raise PackError("unsupported pack version %d" % version)
declared = struct.unpack(">I", buf[8:12])[0]
trailer_start = len(buf) - 20
if hashlib.sha1(buf[:trailer_start]).digest() != buf[trailer_start:]:
raise PackError("pack trailer does not match its bytes")
raw = [] # each: dict(offset, type_code, size, data, base_offset, base_oid)
by_offset = {}
pos = 12
for _ in range(declared):
entry_offset = pos
size, pos, first = _read_varint_size(buf, pos)
type_code = (first >> 4) & 0x07
entry = {"offset": entry_offset, "type_code": type_code, "size": size,
"data": b"", "base_offset": None, "base_oid": None}
if type_code == 6:
rel, pos = _read_ofs_delta_base(buf, pos)
if rel <= 0 or rel > entry_offset:
raise PackError("ofs-delta at %d names an invalid base offset %d" % (entry_offset, rel))
entry["base_offset"] = entry_offset - rel
elif type_code == 7:
if pos + 20 > trailer_start:
raise PackError("ref-delta base id is truncated")
entry["base_oid"] = buf[pos:pos + 20].hex()
pos += 20
elif type_code not in CODE_TYPE:
raise PackError("pack entry has unknown type code %d" % type_code)
data, pos = _inflate_at(buf, pos, trailer_start)
if len(data) != size:
raise PackError("pack entry at %d declares %d bytes but inflated to %d" % (entry_offset, size, len(data)))
entry["data"] = data
raw.append(entry)
by_offset[entry_offset] = entry
if pos != trailer_start:
raise PackError("pack has %d stray bytes before its trailer" % (trailer_start - pos))
objects = {}
resolved_by_oid = {}
resolving = set()
delta_count = 0
def resolve(entry):
nonlocal delta_count
if "oid" in entry:
return entry["oid"], entry["resolved_type"], entry["resolved"]
if entry["offset"] in resolving:
raise PackError("delta cycle at pack offset %d" % entry["offset"])
resolving.add(entry["offset"])
try:
if entry["type_code"] == 6:
base_entry = by_offset.get(entry["base_offset"])
if base_entry is None:
raise PackError("ofs-delta base at offset %s is not in the pack" % entry["base_offset"])
_oid, base_type, base_data = resolve(base_entry)
obj_type = base_type
data = apply_delta(base_data, entry["data"])
elif entry["type_code"] == 7:
wanted = entry["base_oid"]
base_entry = resolved_by_oid.get(wanted)
if base_entry is not None:
_oid, base_type, base_data = resolve(base_entry)
obj_type = base_type
data = apply_delta(base_data, entry["data"])
else:
external = resolve_base(wanted) if resolve_base else None
if external is None:
raise PackError("ref-delta base %s is neither in the pack nor supplied" % wanted)
obj_type, base_data = external
data = apply_delta(base_data, entry["data"])
else:
obj_type = CODE_TYPE[entry["type_code"]]
data = entry["data"]
finally:
resolving.discard(entry["offset"])
oid = hash_object(obj_type, data)
entry["oid"] = oid
entry["resolved_type"] = obj_type
entry["resolved"] = data
resolved_by_oid[oid] = entry
return oid, obj_type, data
for entry in raw:
oid, obj_type, data = resolve(entry)
if entry["type_code"] in (6, 7):
delta_count += 1
if oid not in objects:
objects[oid] = (obj_type, data)
return objects, delta_count
def collect_reachable(tips, lookup):
"""All oids reachable from tips (commits, trees, blobs, tags).
lookup(oid) -> (type, data) or None. Raises PackError on a missing object.
"""
seen = set()
stack = list(tips)
while stack:
oid = stack.pop()
if oid in seen or oid == ZERO_OID:
continue
entry = lookup(oid)
if entry is None:
raise PackError("missing object %s" % oid)
seen.add(oid)
obj_type, data = entry
if obj_type == "commit":
commit = parse_commit(data)
if commit["tree"]:
stack.append(commit["tree"])
stack.extend(commit["parents"])
elif obj_type == "tree":
for _mode, _name, child in parse_tree(data):
stack.append(child)
elif obj_type == "tag":
header = data.split(b"\n\n", 1)[0].decode("utf-8", "surrogateescape")
for line in header.split("\n"):
if line.startswith("object "):
stack.append(line[7:].strip())
return seen