objects.py 52 KB

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