objects.py 36 KB

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