objects.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. class ShaFile(object):
  50. """A git SHA file."""
  51. @classmethod
  52. def _parse_legacy_object(cls, map):
  53. """Parse a legacy object, creating it and setting object._text"""
  54. text = _decompress(map)
  55. object = None
  56. for posstype in type_map.keys():
  57. if text.startswith(posstype):
  58. object = type_map[posstype]()
  59. text = text[len(posstype):]
  60. break
  61. assert object is not None, "%s is not a known object type" % text[:9]
  62. assert text[0] == ' ', "%s is not a space" % text[0]
  63. text = text[1:]
  64. size = 0
  65. i = 0
  66. while text[0] >= '0' and text[0] <= '9':
  67. if i > 0 and size == 0:
  68. assert False, "Size is not in canonical format"
  69. size = (size * 10) + int(text[0])
  70. text = text[1:]
  71. i += 1
  72. object._size = size
  73. assert text[0] == "\0", "Size not followed by null"
  74. text = text[1:]
  75. object._text = text
  76. return object
  77. def as_raw_string(self):
  78. return self._num_type, self._text
  79. @classmethod
  80. def _parse_object(cls, map):
  81. """Parse a new style object , creating it and setting object._text"""
  82. used = 0
  83. byte = ord(map[used])
  84. used += 1
  85. num_type = (byte >> 4) & 7
  86. try:
  87. object = num_type_map[num_type]()
  88. except KeyError:
  89. assert False, "Not a known type: %d" % num_type
  90. while((byte & 0x80) != 0):
  91. byte = ord(map[used])
  92. used += 1
  93. raw = map[used:]
  94. object._text = _decompress(raw)
  95. return object
  96. @classmethod
  97. def _parse_file(cls, map):
  98. word = (ord(map[0]) << 8) + ord(map[1])
  99. if ord(map[0]) == 0x78 and (word % 31) == 0:
  100. return cls._parse_legacy_object(map)
  101. else:
  102. return cls._parse_object(map)
  103. def __init__(self):
  104. """Don't call this directly"""
  105. def _parse_text(self):
  106. """For subclasses to do initialistion time parsing"""
  107. @classmethod
  108. def from_file(cls, filename):
  109. """Get the contents of a SHA file on disk"""
  110. size = os.path.getsize(filename)
  111. f = open(filename, 'rb')
  112. try:
  113. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  114. shafile = cls._parse_file(map)
  115. shafile._parse_text()
  116. return shafile
  117. finally:
  118. f.close()
  119. @classmethod
  120. def from_raw_string(cls, type, string):
  121. """Creates an object of the indicated type from the raw string given.
  122. Type is the numeric type of an object. String is the raw uncompressed
  123. contents.
  124. """
  125. real_class = num_type_map[type]
  126. obj = real_class()
  127. obj._num_type = type
  128. obj._text = string
  129. obj._parse_text()
  130. return obj
  131. def _header(self):
  132. return "%s %lu\0" % (self._type, len(self._text))
  133. def crc32(self):
  134. return zlib.crc32(self._text)
  135. def sha(self):
  136. """The SHA1 object that is the name of this object."""
  137. ressha = sha.new()
  138. ressha.update(self._header())
  139. ressha.update(self._text)
  140. return ressha
  141. def __eq__(self, other):
  142. """Return true id the sha of the two objects match.
  143. The __le__ etc methods aren't overriden as they make no sense,
  144. certainly at this level.
  145. """
  146. return self.sha().digest() == other.sha().digest()
  147. class Blob(ShaFile):
  148. """A Git Blob object."""
  149. _type = blob_id
  150. def text(self):
  151. """The text contained within the blob object."""
  152. return self._text
  153. @classmethod
  154. def from_file(cls, filename):
  155. blob = ShaFile.from_file(filename)
  156. if blob._type != cls._type:
  157. raise NotBlobError(filename)
  158. return blob
  159. @classmethod
  160. def from_string(cls, string):
  161. """Create a blob from a string."""
  162. shafile = cls()
  163. shafile._text = string
  164. return shafile
  165. class Tag(ShaFile):
  166. """A Git Tag object."""
  167. _type = tag_id
  168. @classmethod
  169. def from_file(cls, filename):
  170. blob = ShaFile.from_file(filename)
  171. if blob._type != cls._type:
  172. raise NotBlobError(filename)
  173. return blob
  174. @classmethod
  175. def from_string(cls, string):
  176. """Create a blob from a string."""
  177. shafile = cls()
  178. shafile._text = string
  179. return shafile
  180. class Tree(ShaFile):
  181. """A Git tree object"""
  182. _type = tree_id
  183. @classmethod
  184. def from_file(cls, filename):
  185. tree = ShaFile.from_file(filename)
  186. if tree._type != cls._type:
  187. raise NotTreeError(filename)
  188. return tree
  189. def entries(self):
  190. """Return a list of tuples describing the tree entries"""
  191. return self._entries
  192. def _parse_text(self):
  193. """Grab the entries in the tree"""
  194. self._entries = []
  195. count = 0
  196. while count < len(self._text):
  197. mode = 0
  198. chr = self._text[count]
  199. while chr != ' ':
  200. assert chr >= '0' and chr <= '7', "%s is not a valid mode char" % chr
  201. mode = (mode << 3) + (ord(chr) - ord('0'))
  202. count += 1
  203. chr = self._text[count]
  204. count += 1
  205. chr = self._text[count]
  206. name = ''
  207. while chr != '\0':
  208. name += chr
  209. count += 1
  210. chr = self._text[count]
  211. count += 1
  212. chr = self._text[count]
  213. sha = self._text[count:count+20]
  214. hexsha = sha_to_hex(sha)
  215. self._entries.append((mode, name, hexsha))
  216. count = count + 20
  217. class Commit(ShaFile):
  218. """A git commit object"""
  219. _type = commit_id
  220. @classmethod
  221. def from_file(cls, filename):
  222. commit = ShaFile.from_file(filename)
  223. if commit._type != cls._type:
  224. raise NotCommitError(filename)
  225. return commit
  226. def _parse_text(self):
  227. text = self._text
  228. count = 0
  229. assert text.startswith(tree_id), "Invalid commit object, " \
  230. "must start with %s" % tree_id
  231. count += len(tree_id)
  232. assert text[count] == ' ', "Invalid commit object, " \
  233. "%s must be followed by space not %s" % (tree_id, text[count])
  234. count += 1
  235. self._tree = text[count:count+40]
  236. count = count + 40
  237. assert text[count] == "\n", "Invalid commit object, " \
  238. "tree sha must be followed by newline"
  239. count += 1
  240. self._parents = []
  241. while text[count:].startswith(parent_id):
  242. count += len(parent_id)
  243. assert text[count] == ' ', "Invalid commit object, " \
  244. "%s must be followed by space not %s" % (parent_id, text[count])
  245. count += 1
  246. self._parents.append(text[count:count+40])
  247. count += 40
  248. assert text[count] == "\n", "Invalid commit object, " \
  249. "parent sha must be followed by newline"
  250. count += 1
  251. self._author = None
  252. if text[count:].startswith(author_id):
  253. count += len(author_id)
  254. assert text[count] == ' ', "Invalid commit object, " \
  255. "%s must be followed by space not %s" % (author_id, text[count])
  256. count += 1
  257. self._author = ''
  258. while text[count] != '>':
  259. assert text[count] != '\n', "Malformed author information"
  260. self._author += text[count]
  261. count += 1
  262. self._author += text[count]
  263. count += 1
  264. while text[count] != '\n':
  265. count += 1
  266. count += 1
  267. self._committer = None
  268. if text[count:].startswith(committer_id):
  269. count += len(committer_id)
  270. assert text[count] == ' ', "Invalid commit object, " \
  271. "%s must be followed by space not %s" % (committer_id, text[count])
  272. count += 1
  273. self._committer = ''
  274. while text[count] != '>':
  275. assert text[count] != '\n', "Malformed committer information"
  276. self._committer += text[count]
  277. count += 1
  278. self._committer += text[count]
  279. count += 1
  280. assert text[count] == ' ', "Invalid commit object, " \
  281. "commiter information must be followed by space not %s" % text[count]
  282. count += 1
  283. self._commit_time = int(text[count:count+10])
  284. while text[count] != '\n':
  285. count += 1
  286. count += 1
  287. assert text[count] == '\n', "There must be a new line after the headers"
  288. count += 1
  289. # XXX: There can be an encoding field.
  290. self._message = text[count:]
  291. @property
  292. def tree(self):
  293. """Returns the tree that is the state of this commit"""
  294. return self._tree
  295. @property
  296. def parents(self):
  297. """Return a list of parents of this commit."""
  298. return self._parents
  299. @property
  300. def author(self):
  301. """Returns the name of the author of the commit"""
  302. return self._author
  303. @property
  304. def committer(self):
  305. """Returns the name of the committer of the commit"""
  306. return self._committer
  307. @property
  308. def message(self):
  309. """Returns the commit message"""
  310. return self._message
  311. @property
  312. def commit_time(self):
  313. """Returns the timestamp of the commit.
  314. Returns it as the number of seconds since the epoch.
  315. """
  316. return self._commit_time
  317. @property
  318. def id(self):
  319. return self.sha().hexdigest()
  320. type_map = {
  321. blob_id : Blob,
  322. tree_id : Tree,
  323. commit_id : Commit,
  324. tag_id: Tag,
  325. }
  326. num_type_map = {
  327. 0: None,
  328. 1: Commit,
  329. 2: Tree,
  330. 3: Blob,
  331. 4: Tag,
  332. # 5 Is reserved for further expansion
  333. }