commit.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  2. #
  3. # This module is part of GitPython and is released under the
  4. # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
  5. __all__ = ["Commit"]
  6. from collections import defaultdict
  7. import datetime
  8. from io import BytesIO
  9. import logging
  10. import os
  11. import re
  12. from subprocess import Popen, PIPE
  13. import sys
  14. from time import altzone, daylight, localtime, time, timezone
  15. import warnings
  16. from gitdb import IStream
  17. from git.cmd import Git
  18. from git.diff import Diffable
  19. from git.util import Actor, Stats, finalize_process, hex_to_bin
  20. from . import base
  21. from .tree import Tree
  22. from .util import (
  23. Serializable,
  24. TraversableIterableObj,
  25. altz_to_utctz_str,
  26. from_timestamp,
  27. parse_actor_and_date,
  28. parse_date,
  29. )
  30. # typing ------------------------------------------------------------------
  31. from typing import (
  32. Any,
  33. Dict,
  34. IO,
  35. Iterator,
  36. List,
  37. Sequence,
  38. Tuple,
  39. TYPE_CHECKING,
  40. Union,
  41. cast,
  42. )
  43. if sys.version_info >= (3, 8):
  44. from typing import Literal
  45. else:
  46. from typing_extensions import Literal
  47. from git.types import PathLike
  48. if TYPE_CHECKING:
  49. from git.refs import SymbolicReference
  50. from git.repo import Repo
  51. # ------------------------------------------------------------------------
  52. _logger = logging.getLogger(__name__)
  53. class Commit(base.Object, TraversableIterableObj, Diffable, Serializable):
  54. """Wraps a git commit object.
  55. See :manpage:`gitglossary(7)` on "commit object":
  56. https://git-scm.com/docs/gitglossary#def_commit_object
  57. :note:
  58. This class will act lazily on some of its attributes and will query the value on
  59. demand only if it involves calling the git binary.
  60. """
  61. # ENVIRONMENT VARIABLES
  62. # Read when creating new commits.
  63. env_author_date = "GIT_AUTHOR_DATE"
  64. env_committer_date = "GIT_COMMITTER_DATE"
  65. # CONFIGURATION KEYS
  66. conf_encoding = "i18n.commitencoding"
  67. # INVARIANTS
  68. default_encoding = "UTF-8"
  69. type: Literal["commit"] = "commit"
  70. __slots__ = (
  71. "tree",
  72. "author",
  73. "authored_date",
  74. "author_tz_offset",
  75. "committer",
  76. "committed_date",
  77. "committer_tz_offset",
  78. "message",
  79. "parents",
  80. "encoding",
  81. "gpgsig",
  82. )
  83. _id_attribute_ = "hexsha"
  84. parents: Sequence["Commit"]
  85. def __init__(
  86. self,
  87. repo: "Repo",
  88. binsha: bytes,
  89. tree: Union[Tree, None] = None,
  90. author: Union[Actor, None] = None,
  91. authored_date: Union[int, None] = None,
  92. author_tz_offset: Union[None, float] = None,
  93. committer: Union[Actor, None] = None,
  94. committed_date: Union[int, None] = None,
  95. committer_tz_offset: Union[None, float] = None,
  96. message: Union[str, bytes, None] = None,
  97. parents: Union[Sequence["Commit"], None] = None,
  98. encoding: Union[str, None] = None,
  99. gpgsig: Union[str, None] = None,
  100. ) -> None:
  101. """Instantiate a new :class:`Commit`. All keyword arguments taking ``None`` as
  102. default will be implicitly set on first query.
  103. :param binsha:
  104. 20 byte sha1.
  105. :param tree:
  106. A :class:`~git.objects.tree.Tree` object.
  107. :param author:
  108. The author :class:`~git.util.Actor` object.
  109. :param authored_date: int_seconds_since_epoch
  110. The authored DateTime - use :func:`time.gmtime` to convert it into a
  111. different format.
  112. :param author_tz_offset: int_seconds_west_of_utc
  113. The timezone that the `authored_date` is in.
  114. :param committer:
  115. The committer string, as an :class:`~git.util.Actor` object.
  116. :param committed_date: int_seconds_since_epoch
  117. The committed DateTime - use :func:`time.gmtime` to convert it into a
  118. different format.
  119. :param committer_tz_offset: int_seconds_west_of_utc
  120. The timezone that the `committed_date` is in.
  121. :param message: string
  122. The commit message.
  123. :param encoding: string
  124. Encoding of the message, defaults to UTF-8.
  125. :param parents:
  126. List or tuple of :class:`Commit` objects which are our parent(s) in the
  127. commit dependency graph.
  128. :return:
  129. :class:`Commit`
  130. :note:
  131. Timezone information is in the same format and in the same sign as what
  132. :func:`time.altzone` returns. The sign is inverted compared to git's UTC
  133. timezone.
  134. """
  135. super().__init__(repo, binsha)
  136. self.binsha = binsha
  137. if tree is not None:
  138. assert isinstance(tree, Tree), "Tree needs to be a Tree instance, was %s" % type(tree)
  139. if tree is not None:
  140. self.tree = tree
  141. if author is not None:
  142. self.author = author
  143. if authored_date is not None:
  144. self.authored_date = authored_date
  145. if author_tz_offset is not None:
  146. self.author_tz_offset = author_tz_offset
  147. if committer is not None:
  148. self.committer = committer
  149. if committed_date is not None:
  150. self.committed_date = committed_date
  151. if committer_tz_offset is not None:
  152. self.committer_tz_offset = committer_tz_offset
  153. if message is not None:
  154. self.message = message
  155. if parents is not None:
  156. self.parents = parents
  157. if encoding is not None:
  158. self.encoding = encoding
  159. if gpgsig is not None:
  160. self.gpgsig = gpgsig
  161. @classmethod
  162. def _get_intermediate_items(cls, commit: "Commit") -> Tuple["Commit", ...]:
  163. return tuple(commit.parents)
  164. @classmethod
  165. def _calculate_sha_(cls, repo: "Repo", commit: "Commit") -> bytes:
  166. """Calculate the sha of a commit.
  167. :param repo:
  168. :class:`~git.repo.base.Repo` object the commit should be part of.
  169. :param commit:
  170. :class:`Commit` object for which to generate the sha.
  171. """
  172. stream = BytesIO()
  173. commit._serialize(stream)
  174. streamlen = stream.tell()
  175. stream.seek(0)
  176. istream = repo.odb.store(IStream(cls.type, streamlen, stream))
  177. return istream.binsha
  178. def replace(self, **kwargs: Any) -> "Commit":
  179. """Create new commit object from an existing commit object.
  180. Any values provided as keyword arguments will replace the corresponding
  181. attribute in the new object.
  182. """
  183. attrs = {k: getattr(self, k) for k in self.__slots__}
  184. for attrname in kwargs:
  185. if attrname not in self.__slots__:
  186. raise ValueError("invalid attribute name")
  187. attrs.update(kwargs)
  188. new_commit = self.__class__(self.repo, self.NULL_BIN_SHA, **attrs)
  189. new_commit.binsha = self._calculate_sha_(self.repo, new_commit)
  190. return new_commit
  191. def _set_cache_(self, attr: str) -> None:
  192. if attr in Commit.__slots__:
  193. # Read the data in a chunk, its faster - then provide a file wrapper.
  194. _binsha, _typename, self.size, stream = self.repo.odb.stream(self.binsha)
  195. self._deserialize(BytesIO(stream.read()))
  196. else:
  197. super()._set_cache_(attr)
  198. # END handle attrs
  199. @property
  200. def authored_datetime(self) -> datetime.datetime:
  201. return from_timestamp(self.authored_date, self.author_tz_offset)
  202. @property
  203. def committed_datetime(self) -> datetime.datetime:
  204. return from_timestamp(self.committed_date, self.committer_tz_offset)
  205. @property
  206. def summary(self) -> Union[str, bytes]:
  207. """:return: First line of the commit message"""
  208. if isinstance(self.message, str):
  209. return self.message.split("\n", 1)[0]
  210. else:
  211. return self.message.split(b"\n", 1)[0]
  212. def count(self, paths: Union[PathLike, Sequence[PathLike]] = "", **kwargs: Any) -> int:
  213. """Count the number of commits reachable from this commit.
  214. :param paths:
  215. An optional path or a list of paths restricting the return value to commits
  216. actually containing the paths.
  217. :param kwargs:
  218. Additional options to be passed to :manpage:`git-rev-list(1)`. They must not
  219. alter the output style of the command, or parsing will yield incorrect
  220. results.
  221. :return:
  222. An int defining the number of reachable commits
  223. """
  224. # Yes, it makes a difference whether empty paths are given or not in our case as
  225. # the empty paths version will ignore merge commits for some reason.
  226. if paths:
  227. return len(self.repo.git.rev_list(self.hexsha, "--", paths, **kwargs).splitlines())
  228. return len(self.repo.git.rev_list(self.hexsha, **kwargs).splitlines())
  229. @property
  230. def name_rev(self) -> str:
  231. """
  232. :return:
  233. String describing the commits hex sha based on the closest
  234. :class:`~git.refs.reference.Reference`.
  235. :note:
  236. Mostly useful for UI purposes.
  237. """
  238. return self.repo.git.name_rev(self)
  239. @classmethod
  240. def iter_items(
  241. cls,
  242. repo: "Repo",
  243. rev: Union[str, "Commit", "SymbolicReference"],
  244. paths: Union[PathLike, Sequence[PathLike]] = "",
  245. **kwargs: Any,
  246. ) -> Iterator["Commit"]:
  247. R"""Find all commits matching the given criteria.
  248. :param repo:
  249. The :class:`~git.repo.base.Repo`.
  250. :param rev:
  251. Revision specifier. See :manpage:`git-rev-parse(1)` for viable options.
  252. :param paths:
  253. An optional path or list of paths. If set only :class:`Commit`\s that
  254. include the path or paths will be considered.
  255. :param kwargs:
  256. Optional keyword arguments to :manpage:`git-rev-list(1)` where:
  257. * ``max_count`` is the maximum number of commits to fetch.
  258. * ``skip`` is the number of commits to skip.
  259. * ``since`` selects all commits since some date, e.g. ``"1970-01-01"``.
  260. :return:
  261. Iterator yielding :class:`Commit` items.
  262. """
  263. if "pretty" in kwargs:
  264. raise ValueError("--pretty cannot be used as parsing expects single sha's only")
  265. # END handle pretty
  266. # Use -- in all cases, to prevent possibility of ambiguous arguments.
  267. # See https://github.com/gitpython-developers/GitPython/issues/264.
  268. args_list: List[PathLike] = ["--"]
  269. if paths:
  270. paths_tup: Tuple[PathLike, ...]
  271. if isinstance(paths, (str, os.PathLike)):
  272. paths_tup = (paths,)
  273. else:
  274. paths_tup = tuple(paths)
  275. args_list.extend(paths_tup)
  276. # END if paths
  277. proc = repo.git.rev_list(rev, args_list, as_process=True, **kwargs)
  278. return cls._iter_from_process_or_stream(repo, proc)
  279. def iter_parents(self, paths: Union[PathLike, Sequence[PathLike]] = "", **kwargs: Any) -> Iterator["Commit"]:
  280. R"""Iterate *all* parents of this commit.
  281. :param paths:
  282. Optional path or list of paths limiting the :class:`Commit`\s to those that
  283. contain at least one of the paths.
  284. :param kwargs:
  285. All arguments allowed by :manpage:`git-rev-list(1)`.
  286. :return:
  287. Iterator yielding :class:`Commit` objects which are parents of ``self``
  288. """
  289. # skip ourselves
  290. skip = kwargs.get("skip", 1)
  291. if skip == 0: # skip ourselves
  292. skip = 1
  293. kwargs["skip"] = skip
  294. return self.iter_items(self.repo, self, paths, **kwargs)
  295. @property
  296. def stats(self) -> Stats:
  297. """Create a git stat from changes between this commit and its first parent
  298. or from all changes done if this is the very first commit.
  299. :return:
  300. :class:`Stats`
  301. """
  302. def process_lines(lines: List[str]) -> str:
  303. text = ""
  304. for file_info, line in zip(lines, lines[len(lines) // 2 :]):
  305. change_type = file_info.split("\t")[0][-1]
  306. (insertions, deletions, filename) = line.split("\t")
  307. text += "%s\t%s\t%s\t%s\n" % (change_type, insertions, deletions, filename)
  308. return text
  309. if not self.parents:
  310. lines = self.repo.git.diff_tree(
  311. self.hexsha, "--", numstat=True, no_renames=True, root=True, raw=True
  312. ).splitlines()[1:]
  313. text = process_lines(lines)
  314. else:
  315. lines = self.repo.git.diff(
  316. self.parents[0].hexsha, self.hexsha, "--", numstat=True, no_renames=True, raw=True
  317. ).splitlines()
  318. text = process_lines(lines)
  319. return Stats._list_from_string(self.repo, text)
  320. @property
  321. def trailers(self) -> Dict[str, str]:
  322. """Deprecated. Get the trailers of the message as a dictionary.
  323. :note:
  324. This property is deprecated, please use either :attr:`trailers_list` or
  325. :attr:`trailers_dict`.
  326. :return:
  327. Dictionary containing whitespace stripped trailer information.
  328. Only contains the latest instance of each trailer key.
  329. """
  330. warnings.warn(
  331. "Commit.trailers is deprecated, use Commit.trailers_list or Commit.trailers_dict instead",
  332. DeprecationWarning,
  333. stacklevel=2,
  334. )
  335. return {k: v[0] for k, v in self.trailers_dict.items()}
  336. @property
  337. def trailers_list(self) -> List[Tuple[str, str]]:
  338. """Get the trailers of the message as a list.
  339. Git messages can contain trailer information that are similar to :rfc:`822`
  340. e-mail headers. See :manpage:`git-interpret-trailers(1)`.
  341. This function calls ``git interpret-trailers --parse`` onto the message to
  342. extract the trailer information, returns the raw trailer data as a list.
  343. Valid message with trailer::
  344. Subject line
  345. some body information
  346. another information
  347. key1: value1.1
  348. key1: value1.2
  349. key2 : value 2 with inner spaces
  350. Returned list will look like this::
  351. [
  352. ("key1", "value1.1"),
  353. ("key1", "value1.2"),
  354. ("key2", "value 2 with inner spaces"),
  355. ]
  356. :return:
  357. List containing key-value tuples of whitespace stripped trailer information.
  358. """
  359. cmd = ["git", "interpret-trailers", "--parse"]
  360. proc: Git.AutoInterrupt = self.repo.git.execute( # type: ignore[call-overload]
  361. cmd,
  362. as_process=True,
  363. istream=PIPE,
  364. )
  365. trailer: str = proc.communicate(str(self.message).encode())[0].decode("utf8")
  366. trailer = trailer.strip()
  367. if not trailer:
  368. return []
  369. trailer_list = []
  370. for t in trailer.split("\n"):
  371. key, val = t.split(":", 1)
  372. trailer_list.append((key.strip(), val.strip()))
  373. return trailer_list
  374. @property
  375. def trailers_dict(self) -> Dict[str, List[str]]:
  376. """Get the trailers of the message as a dictionary.
  377. Git messages can contain trailer information that are similar to :rfc:`822`
  378. e-mail headers. See :manpage:`git-interpret-trailers(1)`.
  379. This function calls ``git interpret-trailers --parse`` onto the message to
  380. extract the trailer information. The key value pairs are stripped of leading and
  381. trailing whitespaces before they get saved into a dictionary.
  382. Valid message with trailer::
  383. Subject line
  384. some body information
  385. another information
  386. key1: value1.1
  387. key1: value1.2
  388. key2 : value 2 with inner spaces
  389. Returned dictionary will look like this::
  390. {
  391. "key1": ["value1.1", "value1.2"],
  392. "key2": ["value 2 with inner spaces"],
  393. }
  394. :return:
  395. Dictionary containing whitespace stripped trailer information, mapping
  396. trailer keys to a list of their corresponding values.
  397. """
  398. d = defaultdict(list)
  399. for key, val in self.trailers_list:
  400. d[key].append(val)
  401. return dict(d)
  402. @classmethod
  403. def _iter_from_process_or_stream(cls, repo: "Repo", proc_or_stream: Union[Popen, IO]) -> Iterator["Commit"]:
  404. """Parse out commit information into a list of :class:`Commit` objects.
  405. We expect one line per commit, and parse the actual commit information directly
  406. from our lighting fast object database.
  407. :param proc:
  408. :manpage:`git-rev-list(1)` process instance - one sha per line.
  409. :return:
  410. Iterator supplying :class:`Commit` objects
  411. """
  412. # def is_proc(inp) -> TypeGuard[Popen]:
  413. # return hasattr(proc_or_stream, 'wait') and not hasattr(proc_or_stream, 'readline')
  414. # def is_stream(inp) -> TypeGuard[IO]:
  415. # return hasattr(proc_or_stream, 'readline')
  416. if hasattr(proc_or_stream, "wait"):
  417. proc_or_stream = cast(Popen, proc_or_stream)
  418. if proc_or_stream.stdout is not None:
  419. stream = proc_or_stream.stdout
  420. elif hasattr(proc_or_stream, "readline"):
  421. proc_or_stream = cast(IO, proc_or_stream) # type: ignore[redundant-cast]
  422. stream = proc_or_stream
  423. readline = stream.readline
  424. while True:
  425. line = readline()
  426. if not line:
  427. break
  428. hexsha = line.strip()
  429. if len(hexsha) > 40:
  430. # Split additional information, as returned by bisect for instance.
  431. hexsha, _ = line.split(None, 1)
  432. # END handle extra info
  433. assert len(hexsha) == 40, "Invalid line: %s" % hexsha
  434. yield cls(repo, hex_to_bin(hexsha))
  435. # END for each line in stream
  436. # TODO: Review this - it seems process handling got a bit out of control due to
  437. # many developers trying to fix the open file handles issue.
  438. if hasattr(proc_or_stream, "wait"):
  439. proc_or_stream = cast(Popen, proc_or_stream)
  440. finalize_process(proc_or_stream)
  441. @classmethod
  442. def create_from_tree(
  443. cls,
  444. repo: "Repo",
  445. tree: Union[Tree, str],
  446. message: str,
  447. parent_commits: Union[None, List["Commit"]] = None,
  448. head: bool = False,
  449. author: Union[None, Actor] = None,
  450. committer: Union[None, Actor] = None,
  451. author_date: Union[None, str, datetime.datetime] = None,
  452. commit_date: Union[None, str, datetime.datetime] = None,
  453. ) -> "Commit":
  454. """Commit the given tree, creating a :class:`Commit` object.
  455. :param repo:
  456. :class:`~git.repo.base.Repo` object the commit should be part of.
  457. :param tree:
  458. :class:`~git.objects.tree.Tree` object or hex or bin sha.
  459. The tree of the new commit.
  460. :param message:
  461. Commit message. It may be an empty string if no message is provided. It will
  462. be converted to a string, in any case.
  463. :param parent_commits:
  464. Optional :class:`Commit` objects to use as parents for the new commit. If
  465. empty list, the commit will have no parents at all and become a root commit.
  466. If ``None``, the current head commit will be the parent of the new commit
  467. object.
  468. :param head:
  469. If ``True``, the HEAD will be advanced to the new commit automatically.
  470. Otherwise the HEAD will remain pointing on the previous commit. This could
  471. lead to undesired results when diffing files.
  472. :param author:
  473. The name of the author, optional.
  474. If unset, the repository configuration is used to obtain this value.
  475. :param committer:
  476. The name of the committer, optional.
  477. If unset, the repository configuration is used to obtain this value.
  478. :param author_date:
  479. The timestamp for the author field.
  480. :param commit_date:
  481. The timestamp for the committer field.
  482. :return:
  483. :class:`Commit` object representing the new commit.
  484. :note:
  485. Additional information about the committer and author are taken from the
  486. environment or from the git configuration. See :manpage:`git-commit-tree(1)`
  487. for more information.
  488. """
  489. if parent_commits is None:
  490. try:
  491. parent_commits = [repo.head.commit]
  492. except ValueError:
  493. # Empty repositories have no head commit.
  494. parent_commits = []
  495. # END handle parent commits
  496. else:
  497. for p in parent_commits:
  498. if not isinstance(p, cls):
  499. raise ValueError(f"Parent commit '{p!r}' must be of type {cls}")
  500. # END check parent commit types
  501. # END if parent commits are unset
  502. # Retrieve all additional information, create a commit object, and serialize it.
  503. # Generally:
  504. # * Environment variables override configuration values.
  505. # * Sensible defaults are set according to the git documentation.
  506. # COMMITTER AND AUTHOR INFO
  507. cr = repo.config_reader()
  508. env = os.environ
  509. committer = committer or Actor.committer(cr)
  510. author = author or Actor.author(cr)
  511. # PARSE THE DATES
  512. unix_time = int(time())
  513. is_dst = daylight and localtime().tm_isdst > 0
  514. offset = altzone if is_dst else timezone
  515. author_date_str = env.get(cls.env_author_date, "")
  516. if author_date:
  517. author_time, author_offset = parse_date(author_date)
  518. elif author_date_str:
  519. author_time, author_offset = parse_date(author_date_str)
  520. else:
  521. author_time, author_offset = unix_time, offset
  522. # END set author time
  523. committer_date_str = env.get(cls.env_committer_date, "")
  524. if commit_date:
  525. committer_time, committer_offset = parse_date(commit_date)
  526. elif committer_date_str:
  527. committer_time, committer_offset = parse_date(committer_date_str)
  528. else:
  529. committer_time, committer_offset = unix_time, offset
  530. # END set committer time
  531. # Assume UTF-8 encoding.
  532. enc_section, enc_option = cls.conf_encoding.split(".")
  533. conf_encoding = cr.get_value(enc_section, enc_option, cls.default_encoding)
  534. if not isinstance(conf_encoding, str):
  535. raise TypeError("conf_encoding could not be coerced to str")
  536. # If the tree is no object, make sure we create one - otherwise the created
  537. # commit object is invalid.
  538. if isinstance(tree, str):
  539. tree = repo.tree(tree)
  540. # END tree conversion
  541. # CREATE NEW COMMIT
  542. new_commit = cls(
  543. repo,
  544. cls.NULL_BIN_SHA,
  545. tree,
  546. author,
  547. author_time,
  548. author_offset,
  549. committer,
  550. committer_time,
  551. committer_offset,
  552. message,
  553. parent_commits,
  554. conf_encoding,
  555. )
  556. new_commit.binsha = cls._calculate_sha_(repo, new_commit)
  557. if head:
  558. # Need late import here, importing git at the very beginning throws as
  559. # well...
  560. import git.refs
  561. try:
  562. repo.head.set_commit(new_commit, logmsg=message)
  563. except ValueError:
  564. # head is not yet set to the ref our HEAD points to.
  565. # Happens on first commit.
  566. master = git.refs.Head.create(
  567. repo,
  568. repo.head.ref,
  569. new_commit,
  570. logmsg="commit (initial): %s" % message,
  571. )
  572. repo.head.set_reference(master, logmsg="commit: Switching to %s" % master)
  573. # END handle empty repositories
  574. # END advance head handling
  575. return new_commit
  576. # { Serializable Implementation
  577. def _serialize(self, stream: BytesIO) -> "Commit":
  578. write = stream.write
  579. write(("tree %s\n" % self.tree).encode("ascii"))
  580. for p in self.parents:
  581. write(("parent %s\n" % p).encode("ascii"))
  582. a = self.author
  583. aname = a.name
  584. c = self.committer
  585. fmt = "%s %s <%s> %s %s\n"
  586. write(
  587. (
  588. fmt
  589. % (
  590. "author",
  591. aname,
  592. a.email,
  593. self.authored_date,
  594. altz_to_utctz_str(self.author_tz_offset),
  595. )
  596. ).encode(self.encoding)
  597. )
  598. # Encode committer.
  599. aname = c.name
  600. write(
  601. (
  602. fmt
  603. % (
  604. "committer",
  605. aname,
  606. c.email,
  607. self.committed_date,
  608. altz_to_utctz_str(self.committer_tz_offset),
  609. )
  610. ).encode(self.encoding)
  611. )
  612. if self.encoding != self.default_encoding:
  613. write(("encoding %s\n" % self.encoding).encode("ascii"))
  614. try:
  615. if self.__getattribute__("gpgsig"):
  616. write(b"gpgsig")
  617. for sigline in self.gpgsig.rstrip("\n").split("\n"):
  618. write((" " + sigline + "\n").encode("ascii"))
  619. except AttributeError:
  620. pass
  621. write(b"\n")
  622. # Write plain bytes, be sure its encoded according to our encoding.
  623. if isinstance(self.message, str):
  624. write(self.message.encode(self.encoding))
  625. else:
  626. write(self.message)
  627. # END handle encoding
  628. return self
  629. def _deserialize(self, stream: BytesIO) -> "Commit":
  630. readline = stream.readline
  631. self.tree = Tree(self.repo, hex_to_bin(readline().split()[1]), Tree.tree_id << 12, "")
  632. self.parents = []
  633. next_line = None
  634. while True:
  635. parent_line = readline()
  636. if not parent_line.startswith(b"parent"):
  637. next_line = parent_line
  638. break
  639. # END abort reading parents
  640. self.parents.append(type(self)(self.repo, hex_to_bin(parent_line.split()[-1].decode("ascii"))))
  641. # END for each parent line
  642. self.parents = tuple(self.parents)
  643. # We don't know actual author encoding before we have parsed it, so keep the
  644. # lines around.
  645. author_line = next_line
  646. committer_line = readline()
  647. # We might run into one or more mergetag blocks, skip those for now.
  648. next_line = readline()
  649. while next_line.startswith(b"mergetag "):
  650. next_line = readline()
  651. while next_line.startswith(b" "):
  652. next_line = readline()
  653. # END skip mergetags
  654. # Now we can have the encoding line, or an empty line followed by the optional
  655. # message.
  656. self.encoding = self.default_encoding
  657. self.gpgsig = ""
  658. # Read headers.
  659. enc = next_line
  660. buf = enc.strip()
  661. while buf:
  662. if buf[0:10] == b"encoding ":
  663. self.encoding = buf[buf.find(b" ") + 1 :].decode(self.encoding, "ignore")
  664. elif buf[0:7] == b"gpgsig ":
  665. sig = buf[buf.find(b" ") + 1 :] + b"\n"
  666. is_next_header = False
  667. while True:
  668. sigbuf = readline()
  669. if not sigbuf:
  670. break
  671. if sigbuf[0:1] != b" ":
  672. buf = sigbuf.strip()
  673. is_next_header = True
  674. break
  675. sig += sigbuf[1:]
  676. # END read all signature
  677. self.gpgsig = sig.rstrip(b"\n").decode(self.encoding, "ignore")
  678. if is_next_header:
  679. continue
  680. buf = readline().strip()
  681. # Decode the author's name.
  682. try:
  683. (
  684. self.author,
  685. self.authored_date,
  686. self.author_tz_offset,
  687. ) = parse_actor_and_date(author_line.decode(self.encoding, "replace"))
  688. except UnicodeDecodeError:
  689. _logger.error(
  690. "Failed to decode author line '%s' using encoding %s",
  691. author_line,
  692. self.encoding,
  693. exc_info=True,
  694. )
  695. try:
  696. (
  697. self.committer,
  698. self.committed_date,
  699. self.committer_tz_offset,
  700. ) = parse_actor_and_date(committer_line.decode(self.encoding, "replace"))
  701. except UnicodeDecodeError:
  702. _logger.error(
  703. "Failed to decode committer line '%s' using encoding %s",
  704. committer_line,
  705. self.encoding,
  706. exc_info=True,
  707. )
  708. # END handle author's encoding
  709. # A stream from our data simply gives us the plain message.
  710. # The end of our message stream is marked with a newline that we strip.
  711. self.message = stream.read()
  712. try:
  713. self.message = self.message.decode(self.encoding, "replace")
  714. except UnicodeDecodeError:
  715. _logger.error(
  716. "Failed to decode message '%s' using encoding %s",
  717. self.message,
  718. self.encoding,
  719. exc_info=True,
  720. )
  721. # END exception handling
  722. return self
  723. # } END serializable implementation
  724. @property
  725. def co_authors(self) -> List[Actor]:
  726. """Search the commit message for any co-authors of this commit.
  727. Details on co-authors:
  728. https://github.blog/2018-01-29-commit-together-with-co-authors/
  729. :return:
  730. List of co-authors for this commit (as :class:`~git.util.Actor` objects).
  731. """
  732. co_authors = []
  733. if self.message:
  734. results = re.findall(
  735. r"^Co-authored-by: (.*) <(.*?)>$",
  736. str(self.message),
  737. re.MULTILINE,
  738. )
  739. for author in results:
  740. co_authors.append(Actor(*author))
  741. return co_authors