objects.py 10 KB

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