objects.py 41 KB

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