Skip to content

Instantly share code, notes, and snippets.

@ptrcnull
Created September 16, 2024 01:46
Show Gist options
  • Save ptrcnull/78ca152428d8bc42c425bfea109412ad to your computer and use it in GitHub Desktop.
Save ptrcnull/78ca152428d8bc42c425bfea109412ad to your computer and use it in GitHub Desktop.
simple Git wire protocol parser/serializer in Python
MAGIC_DELIMITER = 69420
def serialize_git_pack(args):
git_list = args[0]
for extra in args[1:]:
git_list.append(MAGIC_DELIMITER)
git_list.extend(extra)
res = ''
for arg in git_list:
if arg is MAGIC_DELIMITER:
res += '0001'
else:
res += (hex(len(arg) + 4)[2:]).zfill(4) + arg
res += '0000'
return res
def deserialize_git_pack(data):
git_list = []
while len(data):
size = int(data[0:4], 16)
if size == 0:
# flush-pkt
break
elif size == 1:
# delim-pkt
res.append(MAGIC_DELIMITER)
continue
elif size == 2:
# response-end-pkt
break
size -= 4
data = data[4:]
content = data[:size]
git_list.append(content)
data = data[size:]
res = [[]]
for param in git_list:
if param is MAGIC_DELIMITER:
res.append([])
continue
res[-1].append(param)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment