objects.py 45 KB

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