objects.py 43 KB

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