objects.py 19 KB

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