objects.py 42 KB

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