2
0

objects.py 19 KB

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