objects.py 10 KB

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