2
0

objects.py 42 KB

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