objects.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. # objects.py -- Acces to base git objects
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # The header parsing code is based on that from git itself, which is
  4. # Copyright (C) 2005 Linus Torvalds
  5. # and licensed under v2 of the GPL.
  6. #
  7. # This program is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU General Public License
  9. # as published by the Free Software Foundation; version 2
  10. # of the License.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  20. # MA 02110-1301, USA.
  21. import mmap
  22. import os
  23. import sha
  24. import zlib
  25. from errors import (NotCommitError,
  26. NotTreeError,
  27. NotBlobError,
  28. )
  29. BLOB_ID = "blob"
  30. TAG_ID = "tag"
  31. TREE_ID = "tree"
  32. COMMIT_ID = "commit"
  33. PARENT_ID = "parent"
  34. AUTHOR_ID = "author"
  35. COMMITTER_ID = "committer"
  36. def _decompress(string):
  37. dcomp = zlib.decompressobj()
  38. dcomped = dcomp.decompress(string)
  39. dcomped += dcomp.flush()
  40. return dcomped
  41. def sha_to_hex(sha):
  42. """Takes a string and returns the hex of the sha within"""
  43. hexsha = ''
  44. for c in sha:
  45. hexsha += "%02x" % ord(c)
  46. assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % \
  47. len(hexsha)
  48. return hexsha
  49. def hex_to_sha(hex):
  50. """Takes a hex sha and returns a binary sha"""
  51. sha = ''
  52. for i in range(0,20):
  53. sha += chr(int(hex[i*2:i*2+2], 16))
  54. assert len(sha) == 20, "Incorrent length of sha1: %d" % len(sha)
  55. return sha
  56. class ShaFile(object):
  57. """A git SHA file."""
  58. @classmethod
  59. def _parse_legacy_object(cls, map):
  60. """Parse a legacy object, creating it and setting object._text"""
  61. text = _decompress(map)
  62. object = None
  63. for posstype in type_map.keys():
  64. if text.startswith(posstype):
  65. object = type_map[posstype]()
  66. text = text[len(posstype):]
  67. break
  68. assert object is not None, "%s is not a known object type" % text[:9]
  69. assert text[0] == ' ', "%s is not a space" % text[0]
  70. text = text[1:]
  71. size = 0
  72. i = 0
  73. while text[0] >= '0' and text[0] <= '9':
  74. if i > 0 and size == 0:
  75. assert False, "Size is not in canonical format"
  76. size = (size * 10) + int(text[0])
  77. text = text[1:]
  78. i += 1
  79. object._size = size
  80. assert text[0] == "\0", "Size not followed by null"
  81. text = text[1:]
  82. object._text = text
  83. return object
  84. def as_raw_string(self):
  85. return self._num_type, self._text
  86. @classmethod
  87. def _parse_object(cls, map):
  88. """Parse a new style object , creating it and setting object._text"""
  89. used = 0
  90. byte = ord(map[used])
  91. used += 1
  92. num_type = (byte >> 4) & 7
  93. try:
  94. object = num_type_map[num_type]()
  95. except KeyError:
  96. assert False, "Not a known type: %d" % num_type
  97. while((byte & 0x80) != 0):
  98. byte = ord(map[used])
  99. used += 1
  100. raw = map[used:]
  101. object._text = _decompress(raw)
  102. return object
  103. @classmethod
  104. def _parse_file(cls, map):
  105. word = (ord(map[0]) << 8) + ord(map[1])
  106. if ord(map[0]) == 0x78 and (word % 31) == 0:
  107. return cls._parse_legacy_object(map)
  108. else:
  109. return cls._parse_object(map)
  110. def __init__(self):
  111. """Don't call this directly"""
  112. def _parse_text(self):
  113. """For subclasses to do initialisation time parsing"""
  114. @classmethod
  115. def from_file(cls, filename):
  116. """Get the contents of a SHA file on disk"""
  117. size = os.path.getsize(filename)
  118. f = open(filename, 'rb')
  119. try:
  120. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  121. shafile = cls._parse_file(map)
  122. shafile._parse_text()
  123. return shafile
  124. finally:
  125. f.close()
  126. @classmethod
  127. def from_raw_string(cls, type, string):
  128. """Creates an object of the indicated type from the raw string given.
  129. Type is the numeric type of an object. String is the raw uncompressed
  130. contents.
  131. """
  132. real_class = num_type_map[type]
  133. obj = real_class()
  134. obj._num_type = type
  135. obj._text = string
  136. obj._parse_text()
  137. return obj
  138. def _header(self):
  139. return "%s %lu\0" % (self._type, len(self._text))
  140. def crc32(self):
  141. return zlib.crc32(self._text)
  142. def sha(self):
  143. """The SHA1 object that is the name of this object."""
  144. ressha = sha.new()
  145. ressha.update(self._header())
  146. ressha.update(self._text)
  147. return ressha
  148. @property
  149. def id(self):
  150. return self.sha().hexdigest()
  151. def __repr__(self):
  152. return "<%s %s>" % (self.__class__.__name__, self.id)
  153. def __eq__(self, other):
  154. """Return true id the sha of the two objects match.
  155. The __le__ etc methods aren't overriden as they make no sense,
  156. certainly at this level.
  157. """
  158. return self.sha().digest() == other.sha().digest()
  159. class Blob(ShaFile):
  160. """A Git Blob object."""
  161. _type = BLOB_ID
  162. _num_type = 3
  163. @property
  164. def data(self):
  165. """The text contained within the blob object."""
  166. return self._text
  167. @classmethod
  168. def from_file(cls, filename):
  169. blob = ShaFile.from_file(filename)
  170. if blob._type != cls._type:
  171. raise NotBlobError(filename)
  172. return blob
  173. @classmethod
  174. def from_string(cls, string):
  175. """Create a blob from a string."""
  176. shafile = cls()
  177. shafile._text = string
  178. return shafile
  179. class Tag(ShaFile):
  180. """A Git Tag object."""
  181. _type = TAG_ID
  182. @classmethod
  183. def from_file(cls, filename):
  184. blob = ShaFile.from_file(filename)
  185. if blob._type != cls._type:
  186. raise NotBlobError(filename)
  187. return blob
  188. @classmethod
  189. def from_string(cls, string):
  190. """Create a blob from a string."""
  191. shafile = cls()
  192. shafile._text = string
  193. return shafile
  194. class Tree(ShaFile):
  195. """A Git tree object"""
  196. _type = TREE_ID
  197. _num_type = 2
  198. def __init__(self):
  199. self._entries = []
  200. @classmethod
  201. def from_file(cls, filename):
  202. tree = ShaFile.from_file(filename)
  203. if tree._type != cls._type:
  204. raise NotTreeError(filename)
  205. return tree
  206. def add(self, mode, name, hexsha):
  207. self._entries.append((mode, name, hexsha))
  208. def entries(self):
  209. """Return a list of tuples describing the tree entries"""
  210. return self._entries
  211. def _parse_text(self):
  212. """Grab the entries in the tree"""
  213. count = 0
  214. while count < len(self._text):
  215. mode = 0
  216. chr = self._text[count]
  217. while chr != ' ':
  218. assert chr >= '0' and chr <= '7', "%s is not a valid mode char" % chr
  219. mode = (mode << 3) + (ord(chr) - ord('0'))
  220. count += 1
  221. chr = self._text[count]
  222. count += 1
  223. chr = self._text[count]
  224. name = ''
  225. while chr != '\0':
  226. name += chr
  227. count += 1
  228. chr = self._text[count]
  229. count += 1
  230. chr = self._text[count]
  231. sha = self._text[count:count+20]
  232. hexsha = sha_to_hex(sha)
  233. self.add(mode, name, hexsha)
  234. count = count + 20
  235. def serialize(self):
  236. self._text = ""
  237. for mode, name, hexsha in self._entries:
  238. self._text += "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
  239. class Commit(ShaFile):
  240. """A git commit object"""
  241. _type = COMMIT_ID
  242. _num_type = 1
  243. def __init__(self):
  244. self._parents = []
  245. @classmethod
  246. def from_file(cls, filename):
  247. commit = ShaFile.from_file(filename)
  248. if commit._type != cls._type:
  249. raise NotCommitError(filename)
  250. return commit
  251. def _parse_text(self):
  252. text = self._text
  253. count = 0
  254. assert text.startswith(TREE_ID), "Invalid commit object, " \
  255. "must start with %s" % TREE_ID
  256. count += len(TREE_ID)
  257. assert text[count] == ' ', "Invalid commit object, " \
  258. "%s must be followed by space not %s" % (TREE_ID, text[count])
  259. count += 1
  260. self._tree = text[count:count+40]
  261. count = count + 40
  262. assert text[count] == "\n", "Invalid commit object, " \
  263. "tree sha must be followed by newline"
  264. count += 1
  265. self._parents = []
  266. while text[count:].startswith(PARENT_ID):
  267. count += len(PARENT_ID)
  268. assert text[count] == ' ', "Invalid commit object, " \
  269. "%s must be followed by space not %s" % (PARENT_ID, text[count])
  270. count += 1
  271. self._parents.append(text[count:count+40])
  272. count += 40
  273. assert text[count] == "\n", "Invalid commit object, " \
  274. "parent sha must be followed by newline"
  275. count += 1
  276. self._author = None
  277. if text[count:].startswith(AUTHOR_ID):
  278. count += len(AUTHOR_ID)
  279. assert text[count] == ' ', "Invalid commit object, " \
  280. "%s must be followed by space not %s" % (AUTHOR_ID, text[count])
  281. count += 1
  282. self._author = ''
  283. while text[count] != '>':
  284. assert text[count] != '\n', "Malformed author information"
  285. self._author += text[count]
  286. count += 1
  287. self._author += text[count]
  288. count += 1
  289. while text[count] != '\n':
  290. count += 1
  291. count += 1
  292. self._committer = None
  293. if text[count:].startswith(COMMITTER_ID):
  294. count += len(COMMITTER_ID)
  295. assert text[count] == ' ', "Invalid commit object, " \
  296. "%s must be followed by space not %s" % (COMMITTER_ID, text[count])
  297. count += 1
  298. self._committer = ''
  299. while text[count] != '>':
  300. assert text[count] != '\n', "Malformed committer information"
  301. self._committer += text[count]
  302. count += 1
  303. self._committer += text[count]
  304. count += 1
  305. assert text[count] == ' ', "Invalid commit object, " \
  306. "commiter information must be followed by space not %s" % text[count]
  307. count += 1
  308. self._commit_time = int(text[count:count+10])
  309. while text[count] != '\n':
  310. count += 1
  311. count += 1
  312. assert text[count] == '\n', "There must be a new line after the headers"
  313. count += 1
  314. # XXX: There can be an encoding field.
  315. self._message = text[count:]
  316. def serialize(self):
  317. self._text = ""
  318. self._text += "%s %s\n" % (TREE_ID, self._tree)
  319. for p in self._parents:
  320. self._text += "%s %s\n" % (PARENT_ID, p)
  321. self._text += "%s %s %s +0000\n" % (AUTHOR_ID, self._author, str(self._commit_time))
  322. self._text += "%s %s %s +0000\n" % (COMMITTER_ID, self._committer, str(self._commit_time))
  323. self._text += self._message
  324. @property
  325. def tree(self):
  326. """Returns the tree that is the state of this commit"""
  327. return self._tree
  328. @property
  329. def parents(self):
  330. """Return a list of parents of this commit."""
  331. return self._parents
  332. @property
  333. def author(self):
  334. """Returns the name of the author of the commit"""
  335. return self._author
  336. @property
  337. def committer(self):
  338. """Returns the name of the committer of the commit"""
  339. return self._committer
  340. @property
  341. def message(self):
  342. """Returns the commit message"""
  343. return self._message
  344. @property
  345. def commit_time(self):
  346. """Returns the timestamp of the commit.
  347. Returns it as the number of seconds since the epoch.
  348. """
  349. return self._commit_time
  350. type_map = {
  351. BLOB_ID : Blob,
  352. TREE_ID : Tree,
  353. COMMIT_ID : Commit,
  354. TAG_ID: Tag,
  355. }
  356. num_type_map = {
  357. 0: None,
  358. 1: Commit,
  359. 2: Tree,
  360. 3: Blob,
  361. 4: Tag,
  362. # 5 Is reserved for further expansion
  363. }