objects.py 19 KB

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