objects.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. # objects.py -- Acces to base git objects
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
  4. # The header parsing code is based on that from git itself, which is
  5. # Copyright (C) 2005 Linus Torvalds
  6. # and licensed under v2 of the GPL.
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; version 2
  11. # of the License or (at your option) a later version of the License.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  21. # MA 02110-1301, USA.
  22. import mmap
  23. import os
  24. import sha
  25. import zlib
  26. from dulwich.errors import (
  27. NotBlobError,
  28. NotCommitError,
  29. NotTreeError,
  30. )
  31. BLOB_ID = "blob"
  32. TAG_ID = "tag"
  33. TREE_ID = "tree"
  34. COMMIT_ID = "commit"
  35. PARENT_ID = "parent"
  36. AUTHOR_ID = "author"
  37. COMMITTER_ID = "committer"
  38. OBJECT_ID = "object"
  39. TYPE_ID = "type"
  40. TAGGER_ID = "tagger"
  41. def _decompress(string):
  42. dcomp = zlib.decompressobj()
  43. dcomped = dcomp.decompress(string)
  44. dcomped += dcomp.flush()
  45. return dcomped
  46. def sha_to_hex(sha):
  47. """Takes a string and returns the hex of the sha within"""
  48. hexsha = ''
  49. for c in sha:
  50. hexsha += "%02x" % ord(c)
  51. assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % \
  52. len(hexsha)
  53. return hexsha
  54. def hex_to_sha(hex):
  55. """Takes a hex sha and returns a binary sha"""
  56. sha = ''
  57. for i in range(0, len(hex), 2):
  58. sha += chr(int(hex[i:i+2], 16))
  59. assert len(sha) == 20, "Incorrent length of sha1: %d" % len(sha)
  60. return sha
  61. class ShaFile(object):
  62. """A git SHA file."""
  63. @classmethod
  64. def _parse_legacy_object(cls, map):
  65. """Parse a legacy object, creating it and setting object._text"""
  66. text = _decompress(map)
  67. object = None
  68. for posstype in type_map.keys():
  69. if text.startswith(posstype):
  70. object = type_map[posstype]()
  71. text = text[len(posstype):]
  72. break
  73. assert object is not None, "%s is not a known object type" % text[:9]
  74. assert text[0] == ' ', "%s is not a space" % text[0]
  75. text = text[1:]
  76. size = 0
  77. i = 0
  78. while text[0] >= '0' and text[0] <= '9':
  79. if i > 0 and size == 0:
  80. assert False, "Size is not in canonical format"
  81. size = (size * 10) + int(text[0])
  82. text = text[1:]
  83. i += 1
  84. object._size = size
  85. assert text[0] == "\0", "Size not followed by null"
  86. text = text[1:]
  87. object._text = text
  88. return object
  89. def as_raw_string(self):
  90. return self._num_type, self._text
  91. @classmethod
  92. def _parse_object(cls, map):
  93. """Parse a new style object , creating it and setting object._text"""
  94. used = 0
  95. byte = ord(map[used])
  96. used += 1
  97. num_type = (byte >> 4) & 7
  98. try:
  99. object = num_type_map[num_type]()
  100. except KeyError:
  101. assert False, "Not a known type: %d" % num_type
  102. while((byte & 0x80) != 0):
  103. byte = ord(map[used])
  104. used += 1
  105. raw = map[used:]
  106. object._text = _decompress(raw)
  107. return object
  108. @classmethod
  109. def _parse_file(cls, map):
  110. word = (ord(map[0]) << 8) + ord(map[1])
  111. if ord(map[0]) == 0x78 and (word % 31) == 0:
  112. return cls._parse_legacy_object(map)
  113. else:
  114. return cls._parse_object(map)
  115. def __init__(self):
  116. """Don't call this directly"""
  117. def _parse_text(self):
  118. """For subclasses to do initialisation time parsing"""
  119. @classmethod
  120. def from_file(cls, filename):
  121. """Get the contents of a SHA file on disk"""
  122. size = os.path.getsize(filename)
  123. f = open(filename, 'rb')
  124. try:
  125. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  126. shafile = cls._parse_file(map)
  127. shafile._parse_text()
  128. return shafile
  129. finally:
  130. f.close()
  131. @classmethod
  132. def from_raw_string(cls, type, string):
  133. """Creates an object of the indicated type from the raw string given.
  134. Type is the numeric type of an object. String is the raw uncompressed
  135. contents.
  136. """
  137. real_class = num_type_map[type]
  138. obj = real_class()
  139. obj._num_type = type
  140. obj._text = string
  141. obj._parse_text()
  142. return obj
  143. def _header(self):
  144. return "%s %lu\0" % (self._type, len(self._text))
  145. def sha(self):
  146. """The SHA1 object that is the name of this object."""
  147. ressha = sha.new()
  148. ressha.update(self._header())
  149. ressha.update(self._text)
  150. return ressha
  151. @property
  152. def id(self):
  153. return self.sha().hexdigest()
  154. @property
  155. def type(self):
  156. return self._num_type
  157. def __repr__(self):
  158. return "<%s %s>" % (self.__class__.__name__, self.id)
  159. def __eq__(self, other):
  160. """Return true id the sha of the two objects match.
  161. The __le__ etc methods aren't overriden as they make no sense,
  162. certainly at this level.
  163. """
  164. return self.sha().digest() == other.sha().digest()
  165. class Blob(ShaFile):
  166. """A Git Blob object."""
  167. _type = BLOB_ID
  168. _num_type = 3
  169. @property
  170. def data(self):
  171. """The text contained within the blob object."""
  172. return self._text
  173. @classmethod
  174. def from_file(cls, filename):
  175. blob = ShaFile.from_file(filename)
  176. if blob._type != cls._type:
  177. raise NotBlobError(filename)
  178. return blob
  179. @classmethod
  180. def from_string(cls, string):
  181. """Create a blob from a string."""
  182. shafile = cls()
  183. shafile._text = string
  184. return shafile
  185. class Tag(ShaFile):
  186. """A Git Tag object."""
  187. _type = TAG_ID
  188. @classmethod
  189. def from_file(cls, filename):
  190. blob = ShaFile.from_file(filename)
  191. if blob._type != cls._type:
  192. raise NotBlobError(filename)
  193. return blob
  194. @classmethod
  195. def from_string(cls, string):
  196. """Create a blob from a string."""
  197. shafile = cls()
  198. shafile._text = string
  199. return shafile
  200. def _parse_text(self):
  201. """Grab the metadata attached to the tag"""
  202. text = self._text
  203. count = 0
  204. assert text.startswith(OBJECT_ID), "Invalid tag object, " \
  205. "must start with %s" % OBJECT_ID
  206. count += len(OBJECT_ID)
  207. assert text[count] == ' ', "Invalid tag object, " \
  208. "%s must be followed by space not %s" % (OBJECT_ID, text[count])
  209. count += 1
  210. self._object_sha = text[count:count+40]
  211. count += 40
  212. assert text[count] == '\n', "Invalid tag object, " \
  213. "%s sha must be followed by newline" % OBJECT_ID
  214. count += 1
  215. assert text[count:].startswith(TYPE_ID), "Invalid tag object, " \
  216. "%s sha must be followed by %s" % (OBJECT_ID, TYPE_ID)
  217. count += len(TYPE_ID)
  218. assert text[count] == ' ', "Invalid tag object, " \
  219. "%s must be followed by space not %s" % (TAG_ID, text[count])
  220. count += 1
  221. self._object_type = ""
  222. while text[count] != '\n':
  223. self._object_type += text[count]
  224. count += 1
  225. count += 1
  226. assert self._object_type in (COMMIT_ID, BLOB_ID, TREE_ID, TAG_ID), "Invalid tag object, " \
  227. "unexpected object type %s" % self._object_type
  228. self._object_type = type_map[self._object_type]
  229. assert text[count:].startswith(TAG_ID), "Invalid tag object, " \
  230. "object type must be followed by %s" % (TAG_ID)
  231. count += len(TAG_ID)
  232. assert text[count] == ' ', "Invalid tag object, " \
  233. "%s must be followed by space not %s" % (TAG_ID, text[count])
  234. count += 1
  235. self._name = ""
  236. while text[count] != '\n':
  237. self._name += text[count]
  238. count += 1
  239. count += 1
  240. assert text[count:].startswith(TAGGER_ID), "Invalid tag object, " \
  241. "%s must be followed by %s" % (TAG_ID, TAGGER_ID)
  242. count += len(TAGGER_ID)
  243. assert text[count] == ' ', "Invalid tag object, " \
  244. "%s must be followed by space not %s" % (TAGGER_ID, text[count])
  245. count += 1
  246. self._tagger = ""
  247. while text[count] != '>':
  248. assert text[count] != '\n', "Malformed tagger information"
  249. self._tagger += text[count]
  250. count += 1
  251. self._tagger += text[count]
  252. count += 1
  253. assert text[count] == ' ', "Invalid tag object, " \
  254. "tagger information must be followed by space not %s" % text[count]
  255. count += 1
  256. self._tag_time = int(text[count:count+10])
  257. while text[count] != '\n':
  258. count += 1
  259. count += 1
  260. assert text[count] == '\n', "There must be a new line after the headers"
  261. count += 1
  262. self._message = text[count:]
  263. @property
  264. def object(self):
  265. """Returns the object pointed by this tag, represented as a tuple(type, sha)"""
  266. return (self._object_type, self._object_sha)
  267. @property
  268. def name(self):
  269. """Returns the name of this tag"""
  270. return self._name
  271. @property
  272. def tagger(self):
  273. """Returns the name of the person who created this tag"""
  274. return self._tagger
  275. @property
  276. def tag_time(self):
  277. """Returns the creation timestamp of the tag.
  278. Returns it as the number of seconds since the epoch"""
  279. return self._tag_time
  280. @property
  281. def message(self):
  282. """Returns the message attached to this tag"""
  283. return self._message
  284. class Tree(ShaFile):
  285. """A Git tree object"""
  286. _type = TREE_ID
  287. _num_type = 2
  288. def __init__(self):
  289. self._entries = []
  290. @classmethod
  291. def from_file(cls, filename):
  292. tree = ShaFile.from_file(filename)
  293. if tree._type != cls._type:
  294. raise NotTreeError(filename)
  295. return tree
  296. def add(self, mode, name, hexsha):
  297. self._entries.append((mode, name, hexsha))
  298. def entries(self):
  299. """Return a list of tuples describing the tree entries"""
  300. return self._entries
  301. def _parse_text(self):
  302. """Grab the entries in the tree"""
  303. count = 0
  304. while count < len(self._text):
  305. mode = 0
  306. chr = self._text[count]
  307. while chr != ' ':
  308. assert chr >= '0' and chr <= '7', "%s is not a valid mode char" % chr
  309. mode = (mode << 3) + (ord(chr) - ord('0'))
  310. count += 1
  311. chr = self._text[count]
  312. count += 1
  313. chr = self._text[count]
  314. name = ''
  315. while chr != '\0':
  316. name += chr
  317. count += 1
  318. chr = self._text[count]
  319. count += 1
  320. chr = self._text[count]
  321. sha = self._text[count:count+20]
  322. hexsha = sha_to_hex(sha)
  323. self.add(mode, name, hexsha)
  324. count = count + 20
  325. def serialize(self):
  326. self._text = ""
  327. for mode, name, hexsha in self._entries:
  328. self._text += "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
  329. class Commit(ShaFile):
  330. """A git commit object"""
  331. _type = COMMIT_ID
  332. _num_type = 1
  333. def __init__(self):
  334. self._parents = []
  335. @classmethod
  336. def from_file(cls, filename):
  337. commit = ShaFile.from_file(filename)
  338. if commit._type != cls._type:
  339. raise NotCommitError(filename)
  340. return commit
  341. def _parse_text(self):
  342. text = self._text
  343. count = 0
  344. assert text.startswith(TREE_ID), "Invalid commit object, " \
  345. "must start with %s" % TREE_ID
  346. count += len(TREE_ID)
  347. assert text[count] == ' ', "Invalid commit object, " \
  348. "%s must be followed by space not %s" % (TREE_ID, text[count])
  349. count += 1
  350. self._tree = text[count:count+40]
  351. count = count + 40
  352. assert text[count] == "\n", "Invalid commit object, " \
  353. "tree sha must be followed by newline"
  354. count += 1
  355. self._parents = []
  356. while text[count:].startswith(PARENT_ID):
  357. count += len(PARENT_ID)
  358. assert text[count] == ' ', "Invalid commit object, " \
  359. "%s must be followed by space not %s" % (PARENT_ID, text[count])
  360. count += 1
  361. self._parents.append(text[count:count+40])
  362. count += 40
  363. assert text[count] == "\n", "Invalid commit object, " \
  364. "parent sha must be followed by newline"
  365. count += 1
  366. self._author = None
  367. if text[count:].startswith(AUTHOR_ID):
  368. count += len(AUTHOR_ID)
  369. assert text[count] == ' ', "Invalid commit object, " \
  370. "%s must be followed by space not %s" % (AUTHOR_ID, text[count])
  371. count += 1
  372. self._author = ''
  373. while text[count] != '>':
  374. assert text[count] != '\n', "Malformed author information"
  375. self._author += text[count]
  376. count += 1
  377. self._author += text[count]
  378. count += 1
  379. while text[count] != '\n':
  380. count += 1
  381. count += 1
  382. self._committer = None
  383. if text[count:].startswith(COMMITTER_ID):
  384. count += len(COMMITTER_ID)
  385. assert text[count] == ' ', "Invalid commit object, " \
  386. "%s must be followed by space not %s" % (COMMITTER_ID, text[count])
  387. count += 1
  388. self._committer = ''
  389. while text[count] != '>':
  390. assert text[count] != '\n', "Malformed committer information"
  391. self._committer += text[count]
  392. count += 1
  393. self._committer += text[count]
  394. count += 1
  395. assert text[count] == ' ', "Invalid commit object, " \
  396. "commiter information must be followed by space not %s" % text[count]
  397. count += 1
  398. self._commit_time = int(text[count:count+10])
  399. while text[count] != '\n':
  400. count += 1
  401. count += 1
  402. assert text[count] == '\n', "There must be a new line after the headers"
  403. count += 1
  404. # XXX: There can be an encoding field.
  405. self._message = text[count:]
  406. def serialize(self):
  407. self._text = ""
  408. self._text += "%s %s\n" % (TREE_ID, self._tree)
  409. for p in self._parents:
  410. self._text += "%s %s\n" % (PARENT_ID, p)
  411. self._text += "%s %s %s +0000\n" % (AUTHOR_ID, self._author, str(self._commit_time))
  412. self._text += "%s %s %s +0000\n" % (COMMITTER_ID, self._committer, str(self._commit_time))
  413. self._text += "\n" # There must be a new line after the headers
  414. self._text += self._message
  415. @property
  416. def tree(self):
  417. """Returns the tree that is the state of this commit"""
  418. return self._tree
  419. @property
  420. def parents(self):
  421. """Return a list of parents of this commit."""
  422. return self._parents
  423. @property
  424. def author(self):
  425. """Returns the name of the author of the commit"""
  426. return self._author
  427. @property
  428. def committer(self):
  429. """Returns the name of the committer of the commit"""
  430. return self._committer
  431. @property
  432. def message(self):
  433. """Returns the commit message"""
  434. return self._message
  435. @property
  436. def commit_time(self):
  437. """Returns the timestamp of the commit.
  438. Returns it as the number of seconds since the epoch.
  439. """
  440. return self._commit_time
  441. type_map = {
  442. BLOB_ID : Blob,
  443. TREE_ID : Tree,
  444. COMMIT_ID : Commit,
  445. TAG_ID: Tag,
  446. }
  447. num_type_map = {
  448. 0: None,
  449. 1: Commit,
  450. 2: Tree,
  451. 3: Blob,
  452. 4: Tag,
  453. # 5 Is reserved for further expansion
  454. }