objects.py 44 KB

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