objects.py 34 KB

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