objects.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. @property
  142. def id(self):
  143. return self.sha().hexdigest()
  144. def __eq__(self, other):
  145. """Return true id the sha of the two objects match.
  146. The __le__ etc methods aren't overriden as they make no sense,
  147. certainly at this level.
  148. """
  149. return self.sha().digest() == other.sha().digest()
  150. class Blob(ShaFile):
  151. """A Git Blob object."""
  152. _type = blob_id
  153. @property
  154. def data(self):
  155. """The text contained within the blob object."""
  156. return self._text
  157. @classmethod
  158. def from_file(cls, filename):
  159. blob = ShaFile.from_file(filename)
  160. if blob._type != cls._type:
  161. raise NotBlobError(filename)
  162. return blob
  163. @classmethod
  164. def from_string(cls, string):
  165. """Create a blob from a string."""
  166. shafile = cls()
  167. shafile._text = string
  168. return shafile
  169. class Tag(ShaFile):
  170. """A Git Tag object."""
  171. _type = tag_id
  172. @classmethod
  173. def from_file(cls, filename):
  174. blob = ShaFile.from_file(filename)
  175. if blob._type != cls._type:
  176. raise NotBlobError(filename)
  177. return blob
  178. @classmethod
  179. def from_string(cls, string):
  180. """Create a blob from a string."""
  181. shafile = cls()
  182. shafile._text = string
  183. return shafile
  184. class Tree(ShaFile):
  185. """A Git tree object"""
  186. _type = tree_id
  187. @classmethod
  188. def from_file(cls, filename):
  189. tree = ShaFile.from_file(filename)
  190. if tree._type != cls._type:
  191. raise NotTreeError(filename)
  192. return tree
  193. def entries(self):
  194. """Return a list of tuples describing the tree entries"""
  195. return self._entries
  196. def _parse_text(self):
  197. """Grab the entries in the tree"""
  198. self._entries = []
  199. count = 0
  200. while count < len(self._text):
  201. mode = 0
  202. chr = self._text[count]
  203. while chr != ' ':
  204. assert chr >= '0' and chr <= '7', "%s is not a valid mode char" % chr
  205. mode = (mode << 3) + (ord(chr) - ord('0'))
  206. count += 1
  207. chr = self._text[count]
  208. count += 1
  209. chr = self._text[count]
  210. name = ''
  211. while chr != '\0':
  212. name += chr
  213. count += 1
  214. chr = self._text[count]
  215. count += 1
  216. chr = self._text[count]
  217. sha = self._text[count:count+20]
  218. hexsha = sha_to_hex(sha)
  219. self._entries.append((mode, name, hexsha))
  220. count = count + 20
  221. class Commit(ShaFile):
  222. """A git commit object"""
  223. _type = commit_id
  224. @classmethod
  225. def from_file(cls, filename):
  226. commit = ShaFile.from_file(filename)
  227. if commit._type != cls._type:
  228. raise NotCommitError(filename)
  229. return commit
  230. def _parse_text(self):
  231. text = self._text
  232. count = 0
  233. assert text.startswith(tree_id), "Invalid commit object, " \
  234. "must start with %s" % tree_id
  235. count += len(tree_id)
  236. assert text[count] == ' ', "Invalid commit object, " \
  237. "%s must be followed by space not %s" % (tree_id, text[count])
  238. count += 1
  239. self._tree = text[count:count+40]
  240. count = count + 40
  241. assert text[count] == "\n", "Invalid commit object, " \
  242. "tree sha must be followed by newline"
  243. count += 1
  244. self._parents = []
  245. while text[count:].startswith(parent_id):
  246. count += len(parent_id)
  247. assert text[count] == ' ', "Invalid commit object, " \
  248. "%s must be followed by space not %s" % (parent_id, text[count])
  249. count += 1
  250. self._parents.append(text[count:count+40])
  251. count += 40
  252. assert text[count] == "\n", "Invalid commit object, " \
  253. "parent sha must be followed by newline"
  254. count += 1
  255. self._author = None
  256. if text[count:].startswith(author_id):
  257. count += len(author_id)
  258. assert text[count] == ' ', "Invalid commit object, " \
  259. "%s must be followed by space not %s" % (author_id, text[count])
  260. count += 1
  261. self._author = ''
  262. while text[count] != '>':
  263. assert text[count] != '\n', "Malformed author information"
  264. self._author += text[count]
  265. count += 1
  266. self._author += text[count]
  267. count += 1
  268. while text[count] != '\n':
  269. count += 1
  270. count += 1
  271. self._committer = None
  272. if text[count:].startswith(committer_id):
  273. count += len(committer_id)
  274. assert text[count] == ' ', "Invalid commit object, " \
  275. "%s must be followed by space not %s" % (committer_id, text[count])
  276. count += 1
  277. self._committer = ''
  278. while text[count] != '>':
  279. assert text[count] != '\n', "Malformed committer information"
  280. self._committer += text[count]
  281. count += 1
  282. self._committer += text[count]
  283. count += 1
  284. assert text[count] == ' ', "Invalid commit object, " \
  285. "commiter information must be followed by space not %s" % text[count]
  286. count += 1
  287. self._commit_time = int(text[count:count+10])
  288. while text[count] != '\n':
  289. count += 1
  290. count += 1
  291. assert text[count] == '\n', "There must be a new line after the headers"
  292. count += 1
  293. # XXX: There can be an encoding field.
  294. self._message = text[count:]
  295. @property
  296. def tree(self):
  297. """Returns the tree that is the state of this commit"""
  298. return self._tree
  299. @property
  300. def parents(self):
  301. """Return a list of parents of this commit."""
  302. return self._parents
  303. @property
  304. def author(self):
  305. """Returns the name of the author of the commit"""
  306. return self._author
  307. @property
  308. def committer(self):
  309. """Returns the name of the committer of the commit"""
  310. return self._committer
  311. @property
  312. def message(self):
  313. """Returns the commit message"""
  314. return self._message
  315. @property
  316. def commit_time(self):
  317. """Returns the timestamp of the commit.
  318. Returns it as the number of seconds since the epoch.
  319. """
  320. return self._commit_time
  321. type_map = {
  322. blob_id : Blob,
  323. tree_id : Tree,
  324. commit_id : Commit,
  325. tag_id: Tag,
  326. }
  327. num_type_map = {
  328. 0: None,
  329. 1: Commit,
  330. 2: Tree,
  331. 3: Blob,
  332. 4: Tag,
  333. # 5 Is reserved for further expansion
  334. }