Skip to content

Instantly share code, notes, and snippets.

@Caleb-T-Owens
Created July 1, 2024 23:37
Show Gist options
  • Save Caleb-T-Owens/e8630f2b600e99acc3c3e317efb42a61 to your computer and use it in GitHub Desktop.
Save Caleb-T-Owens/e8630f2b600e99acc3c3e317efb42a61 to your computer and use it in GitHub Desktop.
Parsing a git tree
require 'zlib'
file = File.read(".git/objects/f2/e2c063fb85137b4fc3bef895ed9d6eed03df42")
# f2e2c063fb85137b4fc3bef895ed9d6eed03df42
buf = Zlib::Inflate.inflate(file)
header, body = buf.split("\0", 2)
puts header
headers = []
SPACE_BYTE = 32
NULL_BYTE = 0
OID_LENGTH = 20
found_space = false
found_null = false
oid = []
name = []
permissions = []
body.bytes.each do |byte|
if !found_space
if byte == SPACE_BYTE
found_space = true
next
end
permissions << byte
elsif !found_null
if byte == NULL_BYTE
found_null = true
next
end
name << byte
else
if oid.length == OID_LENGTH
headers << {
oid:,
name:,
permissions:
}
found_space = false
found_null = false
oid = []
name = []
permissions = []
permissions << byte
else
oid << byte
end
end
end
formatted_headers = headers.map do |header|
{
permissions: header[:permissions].pack("c*"),
name: header[:name].pack("c*"),
oid: header[:oid].pack("c*").unpack("H*").first
}
end
pp formatted_headers
# [0, 32], [46, 32], [32, 34]
# 00 2E 20
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment