objects.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. OBJECT_ID = "object"
  37. TYPE_ID = "type"
  38. TAGGER_ID = "tagger"
  39. def _decompress(string):
  40. dcomp = zlib.decompressobj()
  41. dcomped = dcomp.decompress(string)
  42. dcomped += dcomp.flush()
  43. return dcomped
  44. def sha_to_hex(sha):
  45. """Takes a string and returns the hex of the sha within"""
  46. hexsha = ''
  47. for c in sha:
  48. hexsha += "%02x" % ord(c)
  49. assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % \
  50. len(hexsha)
  51. return hexsha
  52. class ShaFile(object):
  53. """A git SHA file."""
  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. return object
  80. def as_raw_string(self):
  81. return self._num_type, self._text
  82. @classmethod
  83. def _parse_object(cls, map):
  84. """Parse a new style object , creating it and setting object._text"""
  85. used = 0
  86. byte = ord(map[used])
  87. used += 1
  88. num_type = (byte >> 4) & 7
  89. try:
  90. object = num_type_map[num_type]()
  91. except KeyError:
  92. assert False, "Not a known type: %d" % num_type
  93. while((byte & 0x80) != 0):
  94. byte = ord(map[used])
  95. used += 1
  96. raw = map[used:]
  97. object._text = _decompress(raw)
  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 initialisation 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._num_type = type
  131. obj._text = string
  132. obj._parse_text()
  133. return obj
  134. def _header(self):
  135. return "%s %lu\0" % (self._type, len(self._text))
  136. def crc32(self):
  137. return zlib.crc32(self._text)
  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. @property
  145. def id(self):
  146. return self.sha().hexdigest()
  147. def __repr__(self):
  148. return "<%s %s>" % (self.__class__.__name__, self.id)
  149. def __eq__(self, other):
  150. """Return true id the sha of the two objects match.
  151. The __le__ etc methods aren't overriden as they make no sense,
  152. certainly at this level.
  153. """
  154. return self.sha().digest() == other.sha().digest()
  155. class Blob(ShaFile):
  156. """A Git Blob object."""
  157. _type = BLOB_ID
  158. @property
  159. def data(self):
  160. """The text contained within the blob object."""
  161. return self._text
  162. @classmethod
  163. def from_file(cls, filename):
  164. blob = ShaFile.from_file(filename)
  165. if blob._type != cls._type:
  166. raise NotBlobError(filename)
  167. return blob
  168. @classmethod
  169. def from_string(cls, string):
  170. """Create a blob from a string."""
  171. shafile = cls()
  172. shafile._text = string
  173. return shafile
  174. class Tag(ShaFile):
  175. """A Git Tag object."""
  176. _type = TAG_ID
  177. @classmethod
  178. def from_file(cls, filename):
  179. blob = ShaFile.from_file(filename)
  180. if blob._type != cls._type:
  181. raise NotBlobError(filename)
  182. return blob
  183. @classmethod
  184. def from_string(cls, string):
  185. """Create a blob from a string."""
  186. shafile = cls()
  187. shafile._text = string
  188. return shafile
  189. def _parse_text(self):
  190. """Grab the metadata attached to the tag"""
  191. text = self._text
  192. count = 0
  193. assert text.startswith(OBJECT_ID), "Invalid tag object, " \
  194. "must start with %s" % OBJECT_ID
  195. count += len(OBJECT_ID)
  196. assert text[count] == ' ', "Invalid tag object, " \
  197. "%s must be followed by space not %s" % (OBJECT_ID, text[count])
  198. count += 1
  199. self._object_sha = text[count:count+40]
  200. count += 40
  201. assert text[count] == '\n', "Invalid tag object, " \
  202. "%s sha must be followed by newline" % OBJECT_ID
  203. count += 1
  204. assert text[count:].startswith(TYPE_ID), "Invalid tag object, " \
  205. "%s sha must be followed by %s" % (OBJECT_ID, TYPE_ID)
  206. count += len(TYPE_ID)
  207. assert text[count] == ' ', "Invalid tag object, " \
  208. "%s must be followed by space not %s" % (TAG_ID, text[count])
  209. count += 1
  210. self._object_type = ""
  211. while text[count] != '\n':
  212. self._object_type += text[count]
  213. count += 1
  214. count += 1
  215. assert self._object_type in (COMMIT_ID, BLOB_ID, TREE_ID, TAG_ID), "Invalid tag object, " \
  216. "unexpected object type %s" % self._object_type
  217. self._object_type = type_map[self._object_type]
  218. assert text[count:].startswith(TAG_ID), "Invalid tag object, " \
  219. "object type must be followed by %s" % (TAG_ID)
  220. count += len(TAG_ID)
  221. assert text[count] == ' ', "Invalid tag object, " \
  222. "%s must be followed by space not %s" % (TAG_ID, text[count])
  223. count += 1
  224. self._name = ""
  225. while text[count] != '\n':
  226. self._name += text[count]
  227. count += 1
  228. count += 1
  229. assert text[count:].startswith(TAGGER_ID), "Invalid tag object, " \
  230. "%s must be followed by %s" % (TAG_ID, TAGGER_ID)
  231. count += len(TAGGER_ID)
  232. assert text[count] == ' ', "Invalid tag object, " \
  233. "%s must be followed by space not %s" % (TAGGER_ID, text[count])
  234. count += 1
  235. self._tagger = ""
  236. while text[count] != '>':
  237. assert text[count] != '\n', "Malformed tagger information"
  238. self._tagger += text[count]
  239. count += 1
  240. self._tagger += text[count]
  241. count += 1
  242. assert text[count] == ' ', "Invalid tag object, " \
  243. "tagger information must be followed by space not %s" % text[count]
  244. count += 1
  245. self._tag_time = int(text[count:count+10])
  246. while text[count] != '\n':
  247. count += 1
  248. count += 1
  249. assert text[count] == '\n', "There must be a new line after the headers"
  250. count += 1
  251. self._message = text[count:]
  252. @property
  253. def object(self):
  254. """Returns the object pointed by this tag, represented as a tuple(type, sha)"""
  255. return (self._object_type, self._object_sha)
  256. @property
  257. def name(self):
  258. """Returns the name of this tag"""
  259. return self._name
  260. @property
  261. def tagger(self):
  262. """Returns the name of the person who created this tag"""
  263. return self._tagger
  264. @property
  265. def tag_time(self):
  266. """Returns the creation timestamp of the tag.
  267. Returns it as the number of seconds since the epoch"""
  268. return self._tag_time
  269. @property
  270. def message(self):
  271. """Returns the message attached to this tag"""
  272. return self._message
  273. class Tree(ShaFile):
  274. """A Git tree object"""
  275. _type = TREE_ID
  276. @classmethod
  277. def from_file(cls, filename):
  278. tree = ShaFile.from_file(filename)
  279. if tree._type != cls._type:
  280. raise NotTreeError(filename)
  281. return tree
  282. def entries(self):
  283. """Return a list of tuples describing the tree entries"""
  284. return self._entries
  285. def _parse_text(self):
  286. """Grab the entries in the tree"""
  287. self._entries = []
  288. count = 0
  289. while count < len(self._text):
  290. mode = 0
  291. chr = self._text[count]
  292. while chr != ' ':
  293. assert chr >= '0' and chr <= '7', "%s is not a valid mode char" % chr
  294. mode = (mode << 3) + (ord(chr) - ord('0'))
  295. count += 1
  296. chr = self._text[count]
  297. count += 1
  298. chr = self._text[count]
  299. name = ''
  300. while chr != '\0':
  301. name += chr
  302. count += 1
  303. chr = self._text[count]
  304. count += 1
  305. chr = self._text[count]
  306. sha = self._text[count:count+20]
  307. hexsha = sha_to_hex(sha)
  308. self._entries.append((mode, name, hexsha))
  309. count = count + 20
  310. class Commit(ShaFile):
  311. """A git commit object"""
  312. _type = COMMIT_ID
  313. @classmethod
  314. def from_file(cls, filename):
  315. commit = ShaFile.from_file(filename)
  316. if commit._type != cls._type:
  317. raise NotCommitError(filename)
  318. return commit
  319. def _parse_text(self):
  320. text = self._text
  321. count = 0
  322. assert text.startswith(TREE_ID), "Invalid commit object, " \
  323. "must start with %s" % TREE_ID
  324. count += len(TREE_ID)
  325. assert text[count] == ' ', "Invalid commit object, " \
  326. "%s must be followed by space not %s" % (TREE_ID, text[count])
  327. count += 1
  328. self._tree = text[count:count+40]
  329. count = count + 40
  330. assert text[count] == "\n", "Invalid commit object, " \
  331. "tree sha must be followed by newline"
  332. count += 1
  333. self._parents = []
  334. while text[count:].startswith(PARENT_ID):
  335. count += len(PARENT_ID)
  336. assert text[count] == ' ', "Invalid commit object, " \
  337. "%s must be followed by space not %s" % (PARENT_ID, text[count])
  338. count += 1
  339. self._parents.append(text[count:count+40])
  340. count += 40
  341. assert text[count] == "\n", "Invalid commit object, " \
  342. "parent sha must be followed by newline"
  343. count += 1
  344. self._author = None
  345. if text[count:].startswith(AUTHOR_ID):
  346. count += len(AUTHOR_ID)
  347. assert text[count] == ' ', "Invalid commit object, " \
  348. "%s must be followed by space not %s" % (AUTHOR_ID, text[count])
  349. count += 1
  350. self._author = ''
  351. while text[count] != '>':
  352. assert text[count] != '\n', "Malformed author information"
  353. self._author += text[count]
  354. count += 1
  355. self._author += text[count]
  356. count += 1
  357. while text[count] != '\n':
  358. count += 1
  359. count += 1
  360. self._committer = None
  361. if text[count:].startswith(COMMITTER_ID):
  362. count += len(COMMITTER_ID)
  363. assert text[count] == ' ', "Invalid commit object, " \
  364. "%s must be followed by space not %s" % (COMMITTER_ID, text[count])
  365. count += 1
  366. self._committer = ''
  367. while text[count] != '>':
  368. assert text[count] != '\n', "Malformed committer information"
  369. self._committer += text[count]
  370. count += 1
  371. self._committer += text[count]
  372. count += 1
  373. assert text[count] == ' ', "Invalid commit object, " \
  374. "commiter information must be followed by space not %s" % text[count]
  375. count += 1
  376. self._commit_time = int(text[count:count+10])
  377. while text[count] != '\n':
  378. count += 1
  379. count += 1
  380. assert text[count] == '\n', "There must be a new line after the headers"
  381. count += 1
  382. # XXX: There can be an encoding field.
  383. self._message = text[count:]
  384. @property
  385. def tree(self):
  386. """Returns the tree that is the state of this commit"""
  387. return self._tree
  388. @property
  389. def parents(self):
  390. """Return a list of parents of this commit."""
  391. return self._parents
  392. @property
  393. def author(self):
  394. """Returns the name of the author of the commit"""
  395. return self._author
  396. @property
  397. def committer(self):
  398. """Returns the name of the committer of the commit"""
  399. return self._committer
  400. @property
  401. def message(self):
  402. """Returns the commit message"""
  403. return self._message
  404. @property
  405. def commit_time(self):
  406. """Returns the timestamp of the commit.
  407. Returns it as the number of seconds since the epoch.
  408. """
  409. return self._commit_time
  410. type_map = {
  411. BLOB_ID : Blob,
  412. TREE_ID : Tree,
  413. COMMIT_ID : Commit,
  414. TAG_ID: Tag,
  415. }
  416. num_type_map = {
  417. 0: None,
  418. 1: Commit,
  419. 2: Tree,
  420. 3: Blob,
  421. 4: Tag,
  422. # 5 Is reserved for further expansion
  423. }