objects.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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 binascii
  21. from cStringIO import (
  22. StringIO,
  23. )
  24. import mmap
  25. import os
  26. import stat
  27. import zlib
  28. from dulwich.errors import (
  29. ChecksumMismatch,
  30. NotBlobError,
  31. NotCommitError,
  32. NotTagError,
  33. NotTreeError,
  34. ObjectFormatException,
  35. )
  36. from dulwich.file import GitFile
  37. from dulwich.misc import (
  38. make_sha,
  39. )
  40. # Header fields for commits
  41. _TREE_HEADER = "tree"
  42. _PARENT_HEADER = "parent"
  43. _AUTHOR_HEADER = "author"
  44. _COMMITTER_HEADER = "committer"
  45. _ENCODING_HEADER = "encoding"
  46. # Header fields for objects
  47. _OBJECT_HEADER = "object"
  48. _TYPE_HEADER = "type"
  49. _TAG_HEADER = "tag"
  50. _TAGGER_HEADER = "tagger"
  51. S_IFGITLINK = 0160000
  52. def S_ISGITLINK(m):
  53. return (stat.S_IFMT(m) == S_IFGITLINK)
  54. def _decompress(string):
  55. dcomp = zlib.decompressobj()
  56. dcomped = dcomp.decompress(string)
  57. dcomped += dcomp.flush()
  58. return dcomped
  59. def sha_to_hex(sha):
  60. """Takes a string and returns the hex of the sha within"""
  61. hexsha = binascii.hexlify(sha)
  62. assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha
  63. return hexsha
  64. def hex_to_sha(hex):
  65. """Takes a hex sha and returns a binary sha"""
  66. assert len(hex) == 40, "Incorrent length of hexsha: %s" % hex
  67. return binascii.unhexlify(hex)
  68. def hex_to_filename(path, hex):
  69. """Takes a hex sha and returns its filename relative to the given path."""
  70. dir = hex[:2]
  71. file = hex[2:]
  72. # Check from object dir
  73. return os.path.join(path, dir, file)
  74. def filename_to_hex(filename):
  75. """Takes an object filename and returns its corresponding hex sha."""
  76. # grab the last (up to) two path components
  77. names = filename.rsplit(os.path.sep, 2)[-2:]
  78. errmsg = "Invalid object filename: %s" % filename
  79. assert len(names) == 2, errmsg
  80. base, rest = names
  81. assert len(base) == 2 and len(rest) == 38, errmsg
  82. hex = base + rest
  83. hex_to_sha(hex)
  84. return hex
  85. def object_header(num_type, length):
  86. """Return an object header for the given numeric type and text length."""
  87. return "%s %d\0" % (object_class(num_type).type_name, length)
  88. def serializable_property(name, docstring=None):
  89. def set(obj, value):
  90. obj._ensure_parsed()
  91. setattr(obj, "_"+name, value)
  92. obj._needs_serialization = True
  93. def get(obj):
  94. obj._ensure_parsed()
  95. return getattr(obj, "_"+name)
  96. return property(get, set, doc=docstring)
  97. def object_class(type):
  98. """Get the object class corresponding to the given type.
  99. :param type: Either a type name string or a numeric type.
  100. :return: The ShaFile subclass corresponding to the given type, or None if
  101. type is not a valid type name/number.
  102. """
  103. return _TYPE_MAP.get(type, None)
  104. def check_hexsha(hex, error_msg):
  105. try:
  106. hex_to_sha(hex)
  107. except (TypeError, AssertionError):
  108. raise ObjectFormatException("%s %s" % (error_msg, hex))
  109. def check_identity(identity, error_msg):
  110. """Check if the specified identity is valid.
  111. This will raise an exception if the identity is not valid.
  112. :param identity: Identity string
  113. :param error_msg: Error message to use in exception
  114. """
  115. email_start = identity.find("<")
  116. email_end = identity.find(">")
  117. if (email_start < 0 or email_end < 0 or email_end <= email_start
  118. or identity.find("<", email_start + 1) >= 0
  119. or identity.find(">", email_end + 1) >= 0
  120. or not identity.endswith(">")):
  121. raise ObjectFormatException(error_msg)
  122. class FixedSha(object):
  123. """SHA object that behaves like hashlib's but is given a fixed value."""
  124. def __init__(self, hexsha):
  125. self._hexsha = hexsha
  126. self._sha = hex_to_sha(hexsha)
  127. def digest(self):
  128. return self._sha
  129. def hexdigest(self):
  130. return self._hexsha
  131. class ShaFile(object):
  132. """A git SHA file."""
  133. @staticmethod
  134. def _parse_legacy_object_header(magic, f):
  135. """Parse a legacy object, creating it but not reading the file."""
  136. bufsize = 1024
  137. decomp = zlib.decompressobj()
  138. header = decomp.decompress(magic)
  139. start = 0
  140. end = -1
  141. while end < 0:
  142. header += decomp.decompress(f.read(bufsize))
  143. end = header.find("\0", start)
  144. start = len(header)
  145. header = header[:end]
  146. type_name, size = header.split(" ", 1)
  147. size = int(size) # sanity check
  148. obj_class = object_class(type_name)
  149. if not obj_class:
  150. raise ObjectFormatException("Not a known type: %s" % type_name)
  151. return obj_class()
  152. def _parse_legacy_object(self, f):
  153. """Parse a legacy object, setting the raw string."""
  154. size = os.path.getsize(f.name)
  155. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  156. try:
  157. text = _decompress(map)
  158. finally:
  159. map.close()
  160. header_end = text.find('\0')
  161. if header_end < 0:
  162. raise ObjectFormatException("Invalid object header")
  163. self.set_raw_string(text[header_end+1:])
  164. def as_legacy_object_chunks(self):
  165. compobj = zlib.compressobj()
  166. yield compobj.compress(self._header())
  167. for chunk in self.as_raw_chunks():
  168. yield compobj.compress(chunk)
  169. yield compobj.flush()
  170. def as_legacy_object(self):
  171. return "".join(self.as_legacy_object_chunks())
  172. def as_raw_chunks(self):
  173. if self._needs_parsing:
  174. self._ensure_parsed()
  175. elif self._needs_serialization:
  176. self._chunked_text = self._serialize()
  177. return self._chunked_text
  178. def as_raw_string(self):
  179. return "".join(self.as_raw_chunks())
  180. def __str__(self):
  181. return self.as_raw_string()
  182. def __hash__(self):
  183. return hash(self.id)
  184. def as_pretty_string(self):
  185. return self.as_raw_string()
  186. def _ensure_parsed(self):
  187. if self._needs_parsing:
  188. if not self._chunked_text:
  189. if self._file is not None:
  190. self._parse_file(self._file)
  191. elif self._path is not None:
  192. self._parse_path()
  193. else:
  194. raise AssertionError(
  195. "ShaFile needs either text or filename")
  196. self._deserialize(self._chunked_text)
  197. self._needs_parsing = False
  198. def set_raw_string(self, text):
  199. if type(text) != str:
  200. raise TypeError(text)
  201. self.set_raw_chunks([text])
  202. def set_raw_chunks(self, chunks):
  203. self._chunked_text = chunks
  204. self._deserialize(chunks)
  205. self._sha = None
  206. self._needs_parsing = False
  207. self._needs_serialization = False
  208. @staticmethod
  209. def _parse_object_header(magic, f):
  210. """Parse a new style object, creating it but not reading the file."""
  211. num_type = (ord(magic[0]) >> 4) & 7
  212. obj_class = object_class(num_type)
  213. if not obj_class:
  214. raise ObjectFormatException("Not a known type: %d" % num_type)
  215. return obj_class()
  216. def _parse_object(self, f):
  217. """Parse a new style object, setting self._text."""
  218. size = os.path.getsize(f.name)
  219. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  220. try:
  221. # skip type and size; type must have already been determined, and
  222. # we trust zlib to fail if it's otherwise corrupted
  223. byte = ord(map[0])
  224. used = 1
  225. while (byte & 0x80) != 0:
  226. byte = ord(map[used])
  227. used += 1
  228. raw = map[used:]
  229. self.set_raw_string(_decompress(raw))
  230. finally:
  231. map.close()
  232. @classmethod
  233. def _is_legacy_object(cls, magic):
  234. b0, b1 = map(ord, magic)
  235. word = (b0 << 8) + b1
  236. return b0 == 0x78 and (word % 31) == 0
  237. @classmethod
  238. def _parse_file_header(cls, f):
  239. magic = f.read(2)
  240. if cls._is_legacy_object(magic):
  241. return cls._parse_legacy_object_header(magic, f)
  242. else:
  243. return cls._parse_object_header(magic, f)
  244. def __init__(self):
  245. """Don't call this directly"""
  246. self._sha = None
  247. self._path = None
  248. self._file = None
  249. self._chunked_text = []
  250. self._needs_parsing = False
  251. self._needs_serialization = True
  252. def _deserialize(self, chunks):
  253. raise NotImplementedError(self._deserialize)
  254. def _serialize(self):
  255. raise NotImplementedError(self._serialize)
  256. def _parse_path(self):
  257. f = GitFile(self._path, 'rb')
  258. try:
  259. self._parse_file(f)
  260. finally:
  261. f.close()
  262. def _parse_file(self, f):
  263. magic = f.read(2)
  264. if self._is_legacy_object(magic):
  265. self._parse_legacy_object(f)
  266. else:
  267. self._parse_object(f)
  268. @classmethod
  269. def from_path(cls, path):
  270. f = GitFile(path, 'rb')
  271. try:
  272. obj = cls.from_file(f)
  273. obj._path = path
  274. obj._sha = FixedSha(filename_to_hex(path))
  275. obj._file = None
  276. return obj
  277. finally:
  278. f.close()
  279. @classmethod
  280. def from_file(cls, f):
  281. """Get the contents of a SHA file on disk."""
  282. try:
  283. obj = cls._parse_file_header(f)
  284. obj._sha = None
  285. obj._needs_parsing = True
  286. obj._needs_serialization = True
  287. obj._file = f
  288. return obj
  289. except (IndexError, ValueError), e:
  290. raise ObjectFormatException("invalid object header")
  291. @staticmethod
  292. def from_raw_string(type_num, string):
  293. """Creates an object of the indicated type from the raw string given.
  294. :param type_num: The numeric type of the object.
  295. :param string: The raw uncompressed contents.
  296. """
  297. obj = object_class(type_num)()
  298. obj.set_raw_string(string)
  299. return obj
  300. @staticmethod
  301. def from_raw_chunks(type_num, chunks):
  302. """Creates an object of the indicated type from the raw chunks given.
  303. :param type_num: The numeric type of the object.
  304. :param chunks: An iterable of the raw uncompressed contents.
  305. """
  306. obj = object_class(type_num)()
  307. obj.set_raw_chunks(chunks)
  308. return obj
  309. @classmethod
  310. def from_string(cls, string):
  311. """Create a ShaFile from a string."""
  312. obj = cls()
  313. obj.set_raw_string(string)
  314. return obj
  315. def _check_has_member(self, member, error_msg):
  316. """Check that the object has a given member variable.
  317. :param member: the member variable to check for
  318. :param error_msg: the message for an error if the member is missing
  319. :raise ObjectFormatException: with the given error_msg if member is
  320. missing or is None
  321. """
  322. if getattr(self, member, None) is None:
  323. raise ObjectFormatException(error_msg)
  324. def check(self):
  325. """Check this object for internal consistency.
  326. :raise ObjectFormatException: if the object is malformed in some way
  327. :raise ChecksumMismatch: if the object was created with a SHA that does
  328. not match its contents
  329. """
  330. # TODO: if we find that error-checking during object parsing is a
  331. # performance bottleneck, those checks should be moved to the class's
  332. # check() method during optimization so we can still check the object
  333. # when necessary.
  334. old_sha = self.id
  335. try:
  336. self._deserialize(self.as_raw_chunks())
  337. self._sha = None
  338. new_sha = self.id
  339. except Exception, e:
  340. raise ObjectFormatException(e)
  341. if old_sha != new_sha:
  342. raise ChecksumMismatch(new_sha, old_sha)
  343. def _header(self):
  344. return object_header(self.type, self.raw_length())
  345. def raw_length(self):
  346. """Returns the length of the raw string of this object."""
  347. ret = 0
  348. for chunk in self.as_raw_chunks():
  349. ret += len(chunk)
  350. return ret
  351. def _make_sha(self):
  352. ret = make_sha()
  353. ret.update(self._header())
  354. for chunk in self.as_raw_chunks():
  355. ret.update(chunk)
  356. return ret
  357. def sha(self):
  358. """The SHA1 object that is the name of this object."""
  359. if self._sha is None or self._needs_serialization:
  360. # this is a local because as_raw_chunks() overwrites self._sha
  361. new_sha = make_sha()
  362. new_sha.update(self._header())
  363. for chunk in self.as_raw_chunks():
  364. new_sha.update(chunk)
  365. self._sha = new_sha
  366. return self._sha
  367. @property
  368. def id(self):
  369. return self.sha().hexdigest()
  370. def get_type(self):
  371. return self.type_num
  372. def set_type(self, type):
  373. self.type_num = type
  374. # DEPRECATED: use type_num or type_name as needed.
  375. type = property(get_type, set_type)
  376. def __repr__(self):
  377. return "<%s %s>" % (self.__class__.__name__, self.id)
  378. def __ne__(self, other):
  379. return self.id != other.id
  380. def __eq__(self, other):
  381. """Return true if the sha of the two objects match.
  382. The __le__ etc methods aren't overriden as they make no sense,
  383. certainly at this level.
  384. """
  385. return self.id == other.id
  386. class Blob(ShaFile):
  387. """A Git Blob object."""
  388. type_name = 'blob'
  389. type_num = 3
  390. def __init__(self):
  391. super(Blob, self).__init__()
  392. self._chunked_text = []
  393. self._needs_parsing = False
  394. self._needs_serialization = False
  395. def _get_data(self):
  396. return self.as_raw_string()
  397. def _set_data(self, data):
  398. self.set_raw_string(data)
  399. data = property(_get_data, _set_data,
  400. "The text contained within the blob object.")
  401. def _get_chunked(self):
  402. self._ensure_parsed()
  403. return self._chunked_text
  404. def _set_chunked(self, chunks):
  405. self._chunked_text = chunks
  406. def _serialize(self):
  407. if not self._chunked_text:
  408. self._ensure_parsed()
  409. self._needs_serialization = False
  410. return self._chunked_text
  411. def _deserialize(self, chunks):
  412. self._chunked_text = chunks
  413. chunked = property(_get_chunked, _set_chunked,
  414. "The text within the blob object, as chunks (not necessarily lines).")
  415. @classmethod
  416. def from_path(cls, path):
  417. blob = ShaFile.from_path(path)
  418. if not isinstance(blob, cls):
  419. raise NotBlobError(path)
  420. return blob
  421. def check(self):
  422. """Check this object for internal consistency.
  423. :raise ObjectFormatException: if the object is malformed in some way
  424. """
  425. super(Blob, self).check()
  426. def _parse_tag_or_commit(text):
  427. """Parse tag or commit text.
  428. :param text: the raw text of the tag or commit object.
  429. :yield: tuples of (field, value), one per header line, in the order read
  430. from the text, possibly including duplicates. Includes a field named
  431. None for the freeform tag/commit text.
  432. """
  433. f = StringIO(text)
  434. for l in f:
  435. l = l.rstrip("\n")
  436. if l == "":
  437. # Empty line indicates end of headers
  438. break
  439. yield l.split(" ", 1)
  440. yield (None, f.read())
  441. f.close()
  442. def parse_tag(text):
  443. return _parse_tag_or_commit(text)
  444. class Tag(ShaFile):
  445. """A Git Tag object."""
  446. type_name = 'tag'
  447. type_num = 4
  448. def __init__(self):
  449. super(Tag, self).__init__()
  450. self._tag_timezone_neg_utc = False
  451. @classmethod
  452. def from_path(cls, filename):
  453. tag = ShaFile.from_path(filename)
  454. if not isinstance(tag, cls):
  455. raise NotTagError(filename)
  456. return tag
  457. def check(self):
  458. """Check this object for internal consistency.
  459. :raise ObjectFormatException: if the object is malformed in some way
  460. """
  461. super(Tag, self).check()
  462. self._check_has_member("_object_sha", "missing object sha")
  463. self._check_has_member("_object_class", "missing object type")
  464. self._check_has_member("_name", "missing tag name")
  465. if not self._name:
  466. raise ObjectFormatException("empty tag name")
  467. check_hexsha(self._object_sha, "invalid object sha")
  468. if getattr(self, "_tagger", None):
  469. check_identity(self._tagger, "invalid tagger")
  470. last = None
  471. for field, _ in parse_tag("".join(self._chunked_text)):
  472. if field == _OBJECT_HEADER and last is not None:
  473. raise ObjectFormatException("unexpected object")
  474. elif field == _TYPE_HEADER and last != _OBJECT_HEADER:
  475. raise ObjectFormatException("unexpected type")
  476. elif field == _TAG_HEADER and last != _TYPE_HEADER:
  477. raise ObjectFormatException("unexpected tag name")
  478. elif field == _TAGGER_HEADER and last != _TAG_HEADER:
  479. raise ObjectFormatException("unexpected tagger")
  480. last = field
  481. def _serialize(self):
  482. chunks = []
  483. chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
  484. chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
  485. chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
  486. if self._tagger:
  487. if self._tag_time is None:
  488. chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
  489. else:
  490. chunks.append("%s %s %d %s\n" % (
  491. _TAGGER_HEADER, self._tagger, self._tag_time,
  492. format_timezone(self._tag_timezone,
  493. self._tag_timezone_neg_utc)))
  494. chunks.append("\n") # To close headers
  495. chunks.append(self._message)
  496. return chunks
  497. def _deserialize(self, chunks):
  498. """Grab the metadata attached to the tag"""
  499. self._tagger = None
  500. for field, value in parse_tag("".join(chunks)):
  501. if field == _OBJECT_HEADER:
  502. self._object_sha = value
  503. elif field == _TYPE_HEADER:
  504. obj_class = object_class(value)
  505. if not obj_class:
  506. raise ObjectFormatException("Not a known type: %s" % value)
  507. self._object_class = obj_class
  508. elif field == _TAG_HEADER:
  509. self._name = value
  510. elif field == _TAGGER_HEADER:
  511. try:
  512. sep = value.index("> ")
  513. except ValueError:
  514. self._tagger = value
  515. self._tag_time = None
  516. self._tag_timezone = None
  517. self._tag_timezone_neg_utc = False
  518. else:
  519. self._tagger = value[0:sep+1]
  520. try:
  521. (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
  522. self._tag_time = int(timetext)
  523. self._tag_timezone, self._tag_timezone_neg_utc = \
  524. parse_timezone(timezonetext)
  525. except ValueError, e:
  526. raise ObjectFormatException(e)
  527. elif field is None:
  528. self._message = value
  529. else:
  530. raise ObjectFormatException("Unknown field %s" % field)
  531. def _get_object(self):
  532. """Get the object pointed to by this tag.
  533. :return: tuple of (object class, sha).
  534. """
  535. self._ensure_parsed()
  536. return (self._object_class, self._object_sha)
  537. def _set_object(self, value):
  538. self._ensure_parsed()
  539. (self._object_class, self._object_sha) = value
  540. self._needs_serialization = True
  541. object = property(_get_object, _set_object)
  542. name = serializable_property("name", "The name of this tag")
  543. tagger = serializable_property("tagger",
  544. "Returns the name of the person who created this tag")
  545. tag_time = serializable_property("tag_time",
  546. "The creation timestamp of the tag. As the number of seconds since the epoch")
  547. tag_timezone = serializable_property("tag_timezone",
  548. "The timezone that tag_time is in.")
  549. message = serializable_property("message", "The message attached to this tag")
  550. def parse_tree(text):
  551. """Parse a tree text.
  552. :param text: Serialized text to parse
  553. :yields: tuples of (name, mode, sha)
  554. """
  555. count = 0
  556. l = len(text)
  557. while count < l:
  558. mode_end = text.index(' ', count)
  559. mode = int(text[count:mode_end], 8)
  560. name_end = text.index('\0', mode_end)
  561. name = text[mode_end+1:name_end]
  562. count = name_end+21
  563. sha = text[name_end+1:count]
  564. yield (name, mode, sha_to_hex(sha))
  565. def serialize_tree(items):
  566. """Serialize the items in a tree to a text.
  567. :param items: Sorted iterable over (name, mode, sha) tuples
  568. :return: Serialized tree text as chunks
  569. """
  570. for name, mode, hexsha in items:
  571. yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
  572. def sorted_tree_items(entries):
  573. """Iterate over a tree entries dictionary in the order in which
  574. the items would be serialized.
  575. :param entries: Dictionary mapping names to (mode, sha) tuples
  576. :return: Iterator over (name, mode, sha)
  577. """
  578. for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
  579. yield name, entry[0], entry[1]
  580. def cmp_entry((name1, value1), (name2, value2)):
  581. """Compare two tree entries."""
  582. if stat.S_ISDIR(value1[0]):
  583. name1 += "/"
  584. if stat.S_ISDIR(value2[0]):
  585. name2 += "/"
  586. return cmp(name1, name2)
  587. class Tree(ShaFile):
  588. """A Git tree object"""
  589. type_name = 'tree'
  590. type_num = 2
  591. def __init__(self):
  592. super(Tree, self).__init__()
  593. self._entries = {}
  594. @classmethod
  595. def from_path(cls, filename):
  596. tree = ShaFile.from_path(filename)
  597. if not isinstance(tree, cls):
  598. raise NotTreeError(filename)
  599. return tree
  600. def __contains__(self, name):
  601. self._ensure_parsed()
  602. return name in self._entries
  603. def __getitem__(self, name):
  604. self._ensure_parsed()
  605. return self._entries[name]
  606. def __setitem__(self, name, value):
  607. assert isinstance(value, tuple)
  608. assert len(value) == 2
  609. self._ensure_parsed()
  610. self._entries[name] = value
  611. self._needs_serialization = True
  612. def __delitem__(self, name):
  613. self._ensure_parsed()
  614. del self._entries[name]
  615. self._needs_serialization = True
  616. def __len__(self):
  617. self._ensure_parsed()
  618. return len(self._entries)
  619. def __iter__(self):
  620. self._ensure_parsed()
  621. return iter(self._entries)
  622. def add(self, mode, name, hexsha):
  623. assert type(mode) == int
  624. assert type(name) == str
  625. assert type(hexsha) == str
  626. self._ensure_parsed()
  627. self._entries[name] = mode, hexsha
  628. self._needs_serialization = True
  629. def entries(self):
  630. """Return a list of tuples describing the tree entries"""
  631. self._ensure_parsed()
  632. # The order of this is different from iteritems() for historical
  633. # reasons
  634. return [
  635. (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
  636. def iteritems(self):
  637. """Iterate over entries in the order in which they would be serialized.
  638. :return: Iterator over (name, mode, sha) tuples
  639. """
  640. self._ensure_parsed()
  641. return sorted_tree_items(self._entries)
  642. def _deserialize(self, chunks):
  643. """Grab the entries in the tree"""
  644. try:
  645. parsed_entries = parse_tree("".join(chunks))
  646. except ValueError, e:
  647. raise ObjectFormatException(e)
  648. # TODO: list comprehension is for efficiency in the common (small) case;
  649. # if memory efficiency in the large case is a concern, use a genexp.
  650. self._entries = dict([(n, (m, s)) for n, m, s in parsed_entries])
  651. def check(self):
  652. """Check this object for internal consistency.
  653. :raise ObjectFormatException: if the object is malformed in some way
  654. """
  655. super(Tree, self).check()
  656. last = None
  657. allowed_modes = (stat.S_IFREG | 0755, stat.S_IFREG | 0644,
  658. stat.S_IFLNK, stat.S_IFDIR, S_IFGITLINK,
  659. # TODO: optionally exclude as in git fsck --strict
  660. stat.S_IFREG | 0664)
  661. for name, mode, sha in parse_tree("".join(self._chunked_text)):
  662. check_hexsha(sha, 'invalid sha %s' % sha)
  663. if '/' in name or name in ('', '.', '..'):
  664. raise ObjectFormatException('invalid name %s' % name)
  665. if mode not in allowed_modes:
  666. raise ObjectFormatException('invalid mode %06o' % mode)
  667. entry = (name, (mode, sha))
  668. if last:
  669. if cmp_entry(last, entry) > 0:
  670. raise ObjectFormatException('entries not sorted')
  671. if name == last[0]:
  672. raise ObjectFormatException('duplicate entry %s' % name)
  673. last = entry
  674. def _serialize(self):
  675. return list(serialize_tree(self.iteritems()))
  676. def as_pretty_string(self):
  677. text = []
  678. for name, mode, hexsha in self.iteritems():
  679. if mode & stat.S_IFDIR:
  680. kind = "tree"
  681. else:
  682. kind = "blob"
  683. text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
  684. return "".join(text)
  685. def parse_timezone(text):
  686. offset = int(text)
  687. negative_utc = (offset == 0 and text[0] == '-')
  688. signum = (offset < 0) and -1 or 1
  689. offset = abs(offset)
  690. hours = int(offset / 100)
  691. minutes = (offset % 100)
  692. return signum * (hours * 3600 + minutes * 60), negative_utc
  693. def format_timezone(offset, negative_utc=False):
  694. if offset % 60 != 0:
  695. raise ValueError("Unable to handle non-minute offset.")
  696. if offset < 0 or (offset == 0 and negative_utc):
  697. sign = '-'
  698. else:
  699. sign = '+'
  700. offset = abs(offset)
  701. return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
  702. def parse_commit(text):
  703. return _parse_tag_or_commit(text)
  704. class Commit(ShaFile):
  705. """A git commit object"""
  706. type_name = 'commit'
  707. type_num = 1
  708. def __init__(self):
  709. super(Commit, self).__init__()
  710. self._parents = []
  711. self._encoding = None
  712. self._extra = {}
  713. self._author_timezone_neg_utc = False
  714. self._commit_timezone_neg_utc = False
  715. @classmethod
  716. def from_path(cls, path):
  717. commit = ShaFile.from_path(path)
  718. if not isinstance(commit, cls):
  719. raise NotCommitError(path)
  720. return commit
  721. def _deserialize(self, chunks):
  722. self._parents = []
  723. self._extra = []
  724. self._author = None
  725. for field, value in parse_commit("".join(self._chunked_text)):
  726. if field == _TREE_HEADER:
  727. self._tree = value
  728. elif field == _PARENT_HEADER:
  729. self._parents.append(value)
  730. elif field == _AUTHOR_HEADER:
  731. self._author, timetext, timezonetext = value.rsplit(" ", 2)
  732. self._author_time = int(timetext)
  733. self._author_timezone, self._author_timezone_neg_utc =\
  734. parse_timezone(timezonetext)
  735. elif field == _COMMITTER_HEADER:
  736. self._committer, timetext, timezonetext = value.rsplit(" ", 2)
  737. self._commit_time = int(timetext)
  738. self._commit_timezone, self._commit_timezone_neg_utc =\
  739. parse_timezone(timezonetext)
  740. elif field == _ENCODING_HEADER:
  741. self._encoding = value
  742. elif field is None:
  743. self._message = value
  744. else:
  745. self._extra.append((field, value))
  746. def check(self):
  747. """Check this object for internal consistency.
  748. :raise ObjectFormatException: if the object is malformed in some way
  749. """
  750. super(Commit, self).check()
  751. self._check_has_member("_tree", "missing tree")
  752. self._check_has_member("_author", "missing author")
  753. self._check_has_member("_committer", "missing committer")
  754. # times are currently checked when set
  755. for parent in self._parents:
  756. check_hexsha(parent, "invalid parent sha")
  757. check_hexsha(self._tree, "invalid tree sha")
  758. check_identity(self._author, "invalid author")
  759. check_identity(self._committer, "invalid committer")
  760. last = None
  761. for field, _ in parse_commit("".join(self._chunked_text)):
  762. if field == _TREE_HEADER and last is not None:
  763. raise ObjectFormatException("unexpected tree")
  764. elif field == _PARENT_HEADER and last not in (_PARENT_HEADER,
  765. _TREE_HEADER):
  766. raise ObjectFormatException("unexpected parent")
  767. elif field == _AUTHOR_HEADER and last not in (_TREE_HEADER,
  768. _PARENT_HEADER):
  769. raise ObjectFormatException("unexpected author")
  770. elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER:
  771. raise ObjectFormatException("unexpected committer")
  772. elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER:
  773. raise ObjectFormatException("unexpected encoding")
  774. last = field
  775. # TODO: optionally check for duplicate parents
  776. def _serialize(self):
  777. chunks = []
  778. chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
  779. for p in self._parents:
  780. chunks.append("%s %s\n" % (_PARENT_HEADER, p))
  781. chunks.append("%s %s %s %s\n" % (
  782. _AUTHOR_HEADER, self._author, str(self._author_time),
  783. format_timezone(self._author_timezone,
  784. self._author_timezone_neg_utc)))
  785. chunks.append("%s %s %s %s\n" % (
  786. _COMMITTER_HEADER, self._committer, str(self._commit_time),
  787. format_timezone(self._commit_timezone,
  788. self._commit_timezone_neg_utc)))
  789. if self.encoding:
  790. chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
  791. for k, v in self.extra:
  792. if "\n" in k or "\n" in v:
  793. raise AssertionError("newline in extra data: %r -> %r" % (k, v))
  794. chunks.append("%s %s\n" % (k, v))
  795. chunks.append("\n") # There must be a new line after the headers
  796. chunks.append(self._message)
  797. return chunks
  798. tree = serializable_property("tree", "Tree that is the state of this commit")
  799. def _get_parents(self):
  800. """Return a list of parents of this commit."""
  801. self._ensure_parsed()
  802. return self._parents
  803. def _set_parents(self, value):
  804. """Set a list of parents of this commit."""
  805. self._ensure_parsed()
  806. self._needs_serialization = True
  807. self._parents = value
  808. parents = property(_get_parents, _set_parents)
  809. def _get_extra(self):
  810. """Return extra settings of this commit."""
  811. self._ensure_parsed()
  812. return self._extra
  813. extra = property(_get_extra)
  814. author = serializable_property("author",
  815. "The name of the author of the commit")
  816. committer = serializable_property("committer",
  817. "The name of the committer of the commit")
  818. message = serializable_property("message",
  819. "The commit message")
  820. commit_time = serializable_property("commit_time",
  821. "The timestamp of the commit. As the number of seconds since the epoch.")
  822. commit_timezone = serializable_property("commit_timezone",
  823. "The zone the commit time is in")
  824. author_time = serializable_property("author_time",
  825. "The timestamp the commit was written. as the number of seconds since the epoch.")
  826. author_timezone = serializable_property("author_timezone",
  827. "Returns the zone the author time is in.")
  828. encoding = serializable_property("encoding",
  829. "Encoding of the commit message.")
  830. OBJECT_CLASSES = (
  831. Commit,
  832. Tree,
  833. Blob,
  834. Tag,
  835. )
  836. _TYPE_MAP = {}
  837. for cls in OBJECT_CLASSES:
  838. _TYPE_MAP[cls.type_name] = cls
  839. _TYPE_MAP[cls.type_num] = cls
  840. # Hold on to the pure-python implementations for testing
  841. _parse_tree_py = parse_tree
  842. _sorted_tree_items_py = sorted_tree_items
  843. try:
  844. # Try to import C versions
  845. from dulwich._objects import parse_tree, sorted_tree_items
  846. except ImportError:
  847. pass