objects.py 51 KB

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