objects.py 51 KB

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