objects.py 52 KB

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