objects.py 43 KB

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