util.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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. import sys
  6. __all__ = [
  7. "stream_copy",
  8. "join_path",
  9. "to_native_path_linux",
  10. "join_path_native",
  11. "Stats",
  12. "IndexFileSHA1Writer",
  13. "IterableObj",
  14. "IterableList",
  15. "BlockingLockFile",
  16. "LockFile",
  17. "Actor",
  18. "get_user_id",
  19. "assure_directory_exists",
  20. "RemoteProgress",
  21. "CallableRemoteProgress",
  22. "rmtree",
  23. "unbare_repo",
  24. "HIDE_WINDOWS_KNOWN_ERRORS",
  25. ]
  26. if sys.platform == "win32":
  27. __all__.append("to_native_path_windows")
  28. from abc import abstractmethod
  29. import contextlib
  30. from functools import wraps
  31. import getpass
  32. import logging
  33. import os
  34. import os.path as osp
  35. from pathlib import Path
  36. import platform
  37. import re
  38. import shutil
  39. import stat
  40. import subprocess
  41. import time
  42. from urllib.parse import urlsplit, urlunsplit
  43. import warnings
  44. # NOTE: Unused imports can be improved now that CI testing has fully resumed. Some of
  45. # these be used indirectly through other GitPython modules, which avoids having to write
  46. # gitdb all the time in their imports. They are not in __all__, at least currently,
  47. # because they could be removed or changed at any time, and so should not be considered
  48. # conceptually public to code outside GitPython. Linters of course do not like it.
  49. from gitdb.util import (
  50. LazyMixin, # noqa: F401
  51. LockedFD, # noqa: F401
  52. bin_to_hex, # noqa: F401
  53. file_contents_ro, # noqa: F401
  54. file_contents_ro_filepath, # noqa: F401
  55. hex_to_bin, # noqa: F401
  56. make_sha,
  57. to_bin_sha, # noqa: F401
  58. to_hex_sha, # noqa: F401
  59. )
  60. # typing ---------------------------------------------------------
  61. from typing import (
  62. Any,
  63. AnyStr,
  64. BinaryIO,
  65. Callable,
  66. Dict,
  67. Generator,
  68. IO,
  69. Iterator,
  70. List,
  71. Optional,
  72. Pattern,
  73. Sequence,
  74. Tuple,
  75. TYPE_CHECKING,
  76. TypeVar,
  77. Union,
  78. cast,
  79. overload,
  80. )
  81. if TYPE_CHECKING:
  82. from git.cmd import Git
  83. from git.config import GitConfigParser, SectionConstraint
  84. from git.remote import Remote
  85. from git.repo.base import Repo
  86. from git.types import (
  87. Files_TD,
  88. Has_id_attribute,
  89. HSH_TD,
  90. Literal,
  91. PathLike,
  92. Protocol,
  93. SupportsIndex,
  94. Total_TD,
  95. runtime_checkable,
  96. )
  97. # ---------------------------------------------------------------------
  98. T_IterableObj = TypeVar("T_IterableObj", bound=Union["IterableObj", "Has_id_attribute"], covariant=True)
  99. # So IterableList[Head] is subtype of IterableList[IterableObj].
  100. _logger = logging.getLogger(__name__)
  101. def _read_env_flag(name: str, default: bool) -> bool:
  102. """Read a boolean flag from an environment variable.
  103. :return:
  104. The flag, or the `default` value if absent or ambiguous.
  105. """
  106. try:
  107. value = os.environ[name]
  108. except KeyError:
  109. return default
  110. _logger.warning(
  111. "The %s environment variable is deprecated. Its effect has never been documented and changes without warning.",
  112. name,
  113. )
  114. adjusted_value = value.strip().lower()
  115. if adjusted_value in {"", "0", "false", "no"}:
  116. return False
  117. if adjusted_value in {"1", "true", "yes"}:
  118. return True
  119. _logger.warning("%s has unrecognized value %r, treating as %r.", name, value, default)
  120. return default
  121. def _read_win_env_flag(name: str, default: bool) -> bool:
  122. """Read a boolean flag from an environment variable on Windows.
  123. :return:
  124. On Windows, the flag, or the `default` value if absent or ambiguous.
  125. On all other operating systems, ``False``.
  126. :note:
  127. This only accesses the environment on Windows.
  128. """
  129. return sys.platform == "win32" and _read_env_flag(name, default)
  130. #: We need an easy way to see if Appveyor TCs start failing,
  131. #: so the errors marked with this var are considered "acknowledged" ones, awaiting remedy,
  132. #: till then, we wish to hide them.
  133. HIDE_WINDOWS_KNOWN_ERRORS = _read_win_env_flag("HIDE_WINDOWS_KNOWN_ERRORS", True)
  134. HIDE_WINDOWS_FREEZE_ERRORS = _read_win_env_flag("HIDE_WINDOWS_FREEZE_ERRORS", True)
  135. # { Utility Methods
  136. T = TypeVar("T")
  137. def unbare_repo(func: Callable[..., T]) -> Callable[..., T]:
  138. """Methods with this decorator raise :exc:`~git.exc.InvalidGitRepositoryError` if
  139. they encounter a bare repository."""
  140. from .exc import InvalidGitRepositoryError
  141. @wraps(func)
  142. def wrapper(self: "Remote", *args: Any, **kwargs: Any) -> T:
  143. if self.repo.bare:
  144. raise InvalidGitRepositoryError("Method '%s' cannot operate on bare repositories" % func.__name__)
  145. # END bare method
  146. return func(self, *args, **kwargs)
  147. # END wrapper
  148. return wrapper
  149. @contextlib.contextmanager
  150. def cwd(new_dir: PathLike) -> Generator[PathLike, None, None]:
  151. """Context manager to temporarily change directory.
  152. This is similar to :func:`contextlib.chdir` introduced in Python 3.11, but the
  153. context manager object returned by a single call to this function is not reentrant.
  154. """
  155. old_dir = os.getcwd()
  156. os.chdir(new_dir)
  157. try:
  158. yield new_dir
  159. finally:
  160. os.chdir(old_dir)
  161. @contextlib.contextmanager
  162. def patch_env(name: str, value: str) -> Generator[None, None, None]:
  163. """Context manager to temporarily patch an environment variable."""
  164. old_value = os.getenv(name)
  165. os.environ[name] = value
  166. try:
  167. yield
  168. finally:
  169. if old_value is None:
  170. del os.environ[name]
  171. else:
  172. os.environ[name] = old_value
  173. def rmtree(path: PathLike) -> None:
  174. """Remove the given directory tree recursively.
  175. :note:
  176. We use :func:`shutil.rmtree` but adjust its behaviour to see whether files that
  177. couldn't be deleted are read-only. Windows will not remove them in that case.
  178. """
  179. def handler(function: Callable, path: PathLike, _excinfo: Any) -> None:
  180. """Callback for :func:`shutil.rmtree`.
  181. This works as either a ``onexc`` or ``onerror`` style callback.
  182. """
  183. # Is the error an access error?
  184. os.chmod(path, stat.S_IWUSR)
  185. try:
  186. function(path)
  187. except PermissionError as ex:
  188. if HIDE_WINDOWS_KNOWN_ERRORS:
  189. from unittest import SkipTest
  190. raise SkipTest(f"FIXME: fails with: PermissionError\n {ex}") from ex
  191. raise
  192. if sys.platform != "win32":
  193. shutil.rmtree(path)
  194. elif sys.version_info >= (3, 12):
  195. shutil.rmtree(path, onexc=handler)
  196. else:
  197. shutil.rmtree(path, onerror=handler)
  198. def rmfile(path: PathLike) -> None:
  199. """Ensure file deleted also on *Windows* where read-only files need special
  200. treatment."""
  201. if osp.isfile(path):
  202. if sys.platform == "win32":
  203. os.chmod(path, 0o777)
  204. os.remove(path)
  205. def stream_copy(source: BinaryIO, destination: BinaryIO, chunk_size: int = 512 * 1024) -> int:
  206. """Copy all data from the `source` stream into the `destination` stream in chunks
  207. of size `chunk_size`.
  208. :return:
  209. Number of bytes written
  210. """
  211. br = 0
  212. while True:
  213. chunk = source.read(chunk_size)
  214. destination.write(chunk)
  215. br += len(chunk)
  216. if len(chunk) < chunk_size:
  217. break
  218. # END reading output stream
  219. return br
  220. def join_path(a: PathLike, *p: PathLike) -> PathLike:
  221. R"""Join path tokens together similar to osp.join, but always use ``/`` instead of
  222. possibly ``\`` on Windows."""
  223. path = os.fspath(a)
  224. for b in p:
  225. b = os.fspath(b)
  226. if not b:
  227. continue
  228. if b.startswith("/"):
  229. path += b[1:]
  230. elif path == "" or path.endswith("/"):
  231. path += b
  232. else:
  233. path += "/" + b
  234. # END for each path token to add
  235. return path
  236. if sys.platform == "win32":
  237. def to_native_path_windows(path: PathLike) -> PathLike:
  238. path = os.fspath(path)
  239. return path.replace("/", "\\")
  240. def to_native_path_linux(path: PathLike) -> str:
  241. path = os.fspath(path)
  242. return path.replace("\\", "/")
  243. to_native_path = to_native_path_windows
  244. else:
  245. # No need for any work on Linux.
  246. def to_native_path_linux(path: PathLike) -> str:
  247. return os.fspath(path)
  248. to_native_path = to_native_path_linux
  249. def join_path_native(a: PathLike, *p: PathLike) -> PathLike:
  250. R"""Like :func:`join_path`, but makes sure an OS native path is returned.
  251. This is only needed to play it safe on Windows and to ensure nice paths that only
  252. use ``\``.
  253. """
  254. return to_native_path(join_path(a, *p))
  255. def assure_directory_exists(path: PathLike, is_file: bool = False) -> bool:
  256. """Make sure that the directory pointed to by path exists.
  257. :param is_file:
  258. If ``True``, `path` is assumed to be a file and handled correctly.
  259. Otherwise it must be a directory.
  260. :return:
  261. ``True`` if the directory was created, ``False`` if it already existed.
  262. """
  263. if is_file:
  264. path = osp.dirname(path)
  265. # END handle file
  266. if not osp.isdir(path):
  267. os.makedirs(path, exist_ok=True)
  268. return True
  269. return False
  270. def _get_exe_extensions() -> Sequence[str]:
  271. PATHEXT = os.environ.get("PATHEXT", None)
  272. if PATHEXT:
  273. return tuple(p.upper() for p in PATHEXT.split(os.pathsep))
  274. elif sys.platform == "win32":
  275. return (".BAT", ".COM", ".EXE")
  276. else:
  277. return ()
  278. def py_where(program: str, path: Optional[PathLike] = None) -> List[str]:
  279. """Perform a path search to assist :func:`is_cygwin_git`.
  280. This is not robust for general use. It is an implementation detail of
  281. :func:`is_cygwin_git`. When a search following all shell rules is needed,
  282. :func:`shutil.which` can be used instead.
  283. :note:
  284. Neither this function nor :func:`shutil.which` will predict the effect of an
  285. executable search on a native Windows system due to a :class:`subprocess.Popen`
  286. call without ``shell=True``, because shell and non-shell executable search on
  287. Windows differ considerably.
  288. """
  289. # From: http://stackoverflow.com/a/377028/548792
  290. winprog_exts = _get_exe_extensions()
  291. def is_exec(fpath: str) -> bool:
  292. return (
  293. osp.isfile(fpath)
  294. and os.access(fpath, os.X_OK)
  295. and (
  296. sys.platform != "win32" or not winprog_exts or any(fpath.upper().endswith(ext) for ext in winprog_exts)
  297. )
  298. )
  299. progs = []
  300. if not path:
  301. path = os.environ["PATH"]
  302. for folder in os.fspath(path).split(os.pathsep):
  303. folder = folder.strip('"')
  304. if folder:
  305. exe_path = osp.join(folder, program)
  306. for f in [exe_path] + ["%s%s" % (exe_path, e) for e in winprog_exts]:
  307. if is_exec(f):
  308. progs.append(f)
  309. return progs
  310. def _cygexpath(drive: Optional[str], path: str) -> str:
  311. if osp.isabs(path) and not drive:
  312. # Invoked from `cygpath()` directly with `D:Apps\123`?
  313. # It's an error, leave it alone just slashes)
  314. p = path # convert to str if AnyPath given
  315. else:
  316. p = path and osp.normpath(osp.expandvars(osp.expanduser(path)))
  317. if osp.isabs(p):
  318. if drive:
  319. # Confusing, maybe a remote system should expand vars.
  320. p = path
  321. else:
  322. p = cygpath(p)
  323. elif drive:
  324. p = "/proc/cygdrive/%s/%s" % (drive.lower(), p)
  325. p_str = os.fspath(p) # ensure it is a str and not AnyPath
  326. return p_str.replace("\\", "/")
  327. _cygpath_parsers: Tuple[Tuple[Pattern[str], Callable, bool], ...] = (
  328. # See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
  329. # and: https://www.cygwin.com/cygwin-ug-net/using.html#unc-paths
  330. (
  331. re.compile(r"\\\\\?\\UNC\\([^\\]+)\\([^\\]+)(?:\\(.*))?"),
  332. (lambda server, share, rest_path: "//%s/%s/%s" % (server, share, rest_path.replace("\\", "/"))),
  333. False,
  334. ),
  335. (re.compile(r"\\\\\?\\(\w):[/\\](.*)"), (_cygexpath), False),
  336. (re.compile(r"(\w):[/\\](.*)"), (_cygexpath), False),
  337. (re.compile(r"file:(.*)", re.I), (lambda rest_path: rest_path), True),
  338. (re.compile(r"(\w{2,}:.*)"), (lambda url: url), False), # remote URL, do nothing
  339. )
  340. def cygpath(path: str) -> str:
  341. """Use :meth:`git.cmd.Git.polish_url` instead, that works on any environment."""
  342. path = os.fspath(path) # Ensure is str and not AnyPath.
  343. # Fix to use Paths when 3.5 dropped. Or to be just str if only for URLs?
  344. if not path.startswith(("/cygdrive", "//", "/proc/cygdrive")):
  345. for regex, parser, recurse in _cygpath_parsers:
  346. match = regex.match(path)
  347. if match:
  348. path = parser(*match.groups())
  349. if recurse:
  350. path = cygpath(path)
  351. break
  352. else:
  353. path = _cygexpath(None, path)
  354. return path
  355. _decygpath_regex = re.compile(r"(?:/proc)?/cygdrive/(\w)(/.*)?")
  356. def decygpath(path: PathLike) -> str:
  357. path = os.fspath(path)
  358. m = _decygpath_regex.match(path)
  359. if m:
  360. drive, rest_path = m.groups()
  361. path = "%s:%s" % (drive.upper(), rest_path or "")
  362. return path.replace("/", "\\")
  363. #: Store boolean flags denoting if a specific Git executable
  364. #: is from a Cygwin installation (since `cache_lru()` unsupported on PY2).
  365. _is_cygwin_cache: Dict[str, Optional[bool]] = {}
  366. def _is_cygwin_git(git_executable: str) -> bool:
  367. is_cygwin = _is_cygwin_cache.get(git_executable) # type: Optional[bool]
  368. if is_cygwin is None:
  369. is_cygwin = False
  370. try:
  371. git_dir = osp.dirname(git_executable)
  372. if not git_dir:
  373. res = py_where(git_executable)
  374. git_dir = osp.dirname(res[0]) if res else ""
  375. # Just a name given, not a real path.
  376. uname_cmd = osp.join(git_dir, "uname")
  377. if not (Path(uname_cmd).is_file() and os.access(uname_cmd, os.X_OK)):
  378. _logger.debug(f"Failed checking if running in CYGWIN: {uname_cmd} is not an executable")
  379. _is_cygwin_cache[git_executable] = is_cygwin
  380. return is_cygwin
  381. process = subprocess.Popen([uname_cmd], stdout=subprocess.PIPE, universal_newlines=True)
  382. uname_out, _ = process.communicate()
  383. # retcode = process.poll()
  384. is_cygwin = "CYGWIN" in uname_out
  385. except Exception as ex:
  386. _logger.debug("Failed checking if running in CYGWIN due to: %r", ex)
  387. _is_cygwin_cache[git_executable] = is_cygwin
  388. return is_cygwin
  389. @overload
  390. def is_cygwin_git(git_executable: None) -> Literal[False]: ...
  391. @overload
  392. def is_cygwin_git(git_executable: PathLike) -> bool: ...
  393. def is_cygwin_git(git_executable: Union[None, PathLike]) -> bool:
  394. # TODO: when py3.7 support is dropped, use the new interpolation f"{variable=}"
  395. _logger.debug(f"sys.platform={sys.platform!r}, git_executable={git_executable!r}")
  396. if sys.platform != "cygwin":
  397. return False
  398. elif git_executable is None:
  399. return False
  400. else:
  401. return _is_cygwin_git(str(git_executable))
  402. def get_user_id() -> str:
  403. """:return: String identifying the currently active system user as ``name@node``"""
  404. return "%s@%s" % (getpass.getuser(), platform.node())
  405. def finalize_process(proc: Union[subprocess.Popen, "Git.AutoInterrupt"], **kwargs: Any) -> None:
  406. """Wait for the process (clone, fetch, pull or push) and handle its errors
  407. accordingly."""
  408. # TODO: No close proc-streams??
  409. proc.wait(**kwargs)
  410. @overload
  411. def expand_path(p: None, expand_vars: bool = ...) -> None: ...
  412. @overload
  413. def expand_path(p: PathLike, expand_vars: bool = ...) -> str:
  414. # TODO: Support for Python 3.5 has been dropped, so these overloads can be improved.
  415. ...
  416. def expand_path(p: Union[None, PathLike], expand_vars: bool = True) -> Optional[PathLike]:
  417. if isinstance(p, Path):
  418. return p.resolve()
  419. try:
  420. p = osp.expanduser(p) # type: ignore[arg-type]
  421. if expand_vars:
  422. p = osp.expandvars(p)
  423. return osp.normpath(osp.abspath(p))
  424. except Exception:
  425. return None
  426. def remove_password_if_present(cmdline: Sequence[str]) -> List[str]:
  427. """Parse any command line argument and if one of the elements is an URL with a
  428. username and/or password, replace them by stars (in-place).
  429. If nothing is found, this just returns the command line as-is.
  430. This should be used for every log line that print a command line, as well as
  431. exception messages.
  432. """
  433. new_cmdline = []
  434. for index, to_parse in enumerate(cmdline):
  435. new_cmdline.append(to_parse)
  436. try:
  437. url = urlsplit(to_parse)
  438. # Remove password from the URL if present.
  439. if url.password is None and url.username is None:
  440. continue
  441. if url.password is not None:
  442. url = url._replace(netloc=url.netloc.replace(url.password, "*****"))
  443. if url.username is not None:
  444. url = url._replace(netloc=url.netloc.replace(url.username, "*****"))
  445. new_cmdline[index] = urlunsplit(url)
  446. except ValueError:
  447. # This is not a valid URL.
  448. continue
  449. return new_cmdline
  450. # } END utilities
  451. # { Classes
  452. class RemoteProgress:
  453. """Handler providing an interface to parse progress information emitted by
  454. :manpage:`git-push(1)` and :manpage:`git-fetch(1)` and to dispatch callbacks
  455. allowing subclasses to react to the progress."""
  456. _num_op_codes: int = 9
  457. (
  458. BEGIN,
  459. END,
  460. COUNTING,
  461. COMPRESSING,
  462. WRITING,
  463. RECEIVING,
  464. RESOLVING,
  465. FINDING_SOURCES,
  466. CHECKING_OUT,
  467. ) = [1 << x for x in range(_num_op_codes)]
  468. STAGE_MASK = BEGIN | END
  469. OP_MASK = ~STAGE_MASK
  470. DONE_TOKEN = "done."
  471. TOKEN_SEPARATOR = ", "
  472. __slots__ = (
  473. "_cur_line",
  474. "_seen_ops",
  475. "error_lines", # Lines that started with 'error:' or 'fatal:'.
  476. "other_lines", # Lines not denoting progress (i.e.g. push-infos).
  477. )
  478. re_op_absolute = re.compile(r"(remote: )?([\w\s]+):\s+()(\d+)()(.*)")
  479. re_op_relative = re.compile(r"(remote: )?([\w\s]+):\s+(\d+)% \((\d+)/(\d+)\)(.*)")
  480. def __init__(self) -> None:
  481. self._seen_ops: List[int] = []
  482. self._cur_line: Optional[str] = None
  483. self.error_lines: List[str] = []
  484. self.other_lines: List[str] = []
  485. def _parse_progress_line(self, line: AnyStr) -> None:
  486. """Parse progress information from the given line as retrieved by
  487. :manpage:`git-push(1)` or :manpage:`git-fetch(1)`.
  488. - Lines that do not contain progress info are stored in :attr:`other_lines`.
  489. - Lines that seem to contain an error (i.e. start with ``error:`` or ``fatal:``)
  490. are stored in :attr:`error_lines`.
  491. """
  492. # handle
  493. # Counting objects: 4, done.
  494. # Compressing objects: 50% (1/2)
  495. # Compressing objects: 100% (2/2)
  496. # Compressing objects: 100% (2/2), done.
  497. if isinstance(line, bytes): # mypy argues about ternary assignment.
  498. line_str = line.decode("utf-8")
  499. else:
  500. line_str = line
  501. self._cur_line = line_str
  502. if self._cur_line.startswith(("error:", "fatal:")):
  503. self.error_lines.append(self._cur_line)
  504. return
  505. cur_count, max_count = None, None
  506. match = self.re_op_relative.match(line_str)
  507. if match is None:
  508. match = self.re_op_absolute.match(line_str)
  509. if not match:
  510. self.line_dropped(line_str)
  511. self.other_lines.append(line_str)
  512. return
  513. # END could not get match
  514. op_code = 0
  515. _remote, op_name, _percent, cur_count, max_count, message = match.groups()
  516. # Get operation ID.
  517. if op_name == "Counting objects":
  518. op_code |= self.COUNTING
  519. elif op_name == "Compressing objects":
  520. op_code |= self.COMPRESSING
  521. elif op_name == "Writing objects":
  522. op_code |= self.WRITING
  523. elif op_name == "Receiving objects":
  524. op_code |= self.RECEIVING
  525. elif op_name == "Resolving deltas":
  526. op_code |= self.RESOLVING
  527. elif op_name == "Finding sources":
  528. op_code |= self.FINDING_SOURCES
  529. elif op_name == "Checking out files":
  530. op_code |= self.CHECKING_OUT
  531. else:
  532. # Note: On Windows it can happen that partial lines are sent.
  533. # Hence we get something like "CompreReceiving objects", which is
  534. # a blend of "Compressing objects" and "Receiving objects".
  535. # This can't really be prevented, so we drop the line verbosely
  536. # to make sure we get informed in case the process spits out new
  537. # commands at some point.
  538. self.line_dropped(line_str)
  539. # Note: Don't add this line to the other lines, as we have to silently
  540. # drop it.
  541. return
  542. # END handle op code
  543. # Figure out stage.
  544. if op_code not in self._seen_ops:
  545. self._seen_ops.append(op_code)
  546. op_code |= self.BEGIN
  547. # END begin opcode
  548. if message is None:
  549. message = ""
  550. # END message handling
  551. message = message.strip()
  552. if message.endswith(self.DONE_TOKEN):
  553. op_code |= self.END
  554. message = message[: -len(self.DONE_TOKEN)]
  555. # END end message handling
  556. message = message.strip(self.TOKEN_SEPARATOR)
  557. self.update(
  558. op_code,
  559. cur_count and float(cur_count),
  560. max_count and float(max_count),
  561. message,
  562. )
  563. def new_message_handler(self) -> Callable[[str], None]:
  564. """
  565. :return:
  566. A progress handler suitable for :func:`~git.cmd.handle_process_output`,
  567. passing lines on to this progress handler in a suitable format.
  568. """
  569. def handler(line: AnyStr) -> None:
  570. return self._parse_progress_line(line.rstrip())
  571. # END handler
  572. return handler
  573. def line_dropped(self, line: str) -> None:
  574. """Called whenever a line could not be understood and was therefore dropped."""
  575. pass
  576. def update(
  577. self,
  578. op_code: int,
  579. cur_count: Union[str, float],
  580. max_count: Union[str, float, None] = None,
  581. message: str = "",
  582. ) -> None:
  583. """Called whenever the progress changes.
  584. :param op_code:
  585. Integer allowing to be compared against Operation IDs and stage IDs.
  586. Stage IDs are :const:`BEGIN` and :const:`END`. :const:`BEGIN` will only be
  587. set once for each Operation ID as well as :const:`END`. It may be that
  588. :const:`BEGIN` and :const:`END` are set at once in case only one progress
  589. message was emitted due to the speed of the operation. Between
  590. :const:`BEGIN` and :const:`END`, none of these flags will be set.
  591. Operation IDs are all held within the :const:`OP_MASK`. Only one Operation
  592. ID will be active per call.
  593. :param cur_count:
  594. Current absolute count of items.
  595. :param max_count:
  596. The maximum count of items we expect. It may be ``None`` in case there is no
  597. maximum number of items or if it is (yet) unknown.
  598. :param message:
  599. In case of the :const:`WRITING` operation, it contains the amount of bytes
  600. transferred. It may possibly be used for other purposes as well.
  601. :note:
  602. You may read the contents of the current line in
  603. :attr:`self._cur_line <_cur_line>`.
  604. """
  605. pass
  606. class CallableRemoteProgress(RemoteProgress):
  607. """A :class:`RemoteProgress` implementation forwarding updates to any callable.
  608. :note:
  609. Like direct instances of :class:`RemoteProgress`, instances of this
  610. :class:`CallableRemoteProgress` class are not themselves directly callable.
  611. Rather, instances of this class wrap a callable and forward to it. This should
  612. therefore not be confused with :class:`git.types.CallableProgress`.
  613. """
  614. __slots__ = ("_callable",)
  615. def __init__(self, fn: Callable) -> None:
  616. self._callable = fn
  617. super().__init__()
  618. def update(self, *args: Any, **kwargs: Any) -> None:
  619. self._callable(*args, **kwargs)
  620. class Actor:
  621. """Actors hold information about a person acting on the repository. They can be
  622. committers and authors or anything with a name and an email as mentioned in the git
  623. log entries."""
  624. # PRECOMPILED REGEX
  625. name_only_regex = re.compile(r"<(.*)>")
  626. name_email_regex = re.compile(r"(.*) <(.*?)>")
  627. # ENVIRONMENT VARIABLES
  628. # These are read when creating new commits.
  629. env_author_name = "GIT_AUTHOR_NAME"
  630. env_author_email = "GIT_AUTHOR_EMAIL"
  631. env_committer_name = "GIT_COMMITTER_NAME"
  632. env_committer_email = "GIT_COMMITTER_EMAIL"
  633. # CONFIGURATION KEYS
  634. conf_name = "name"
  635. conf_email = "email"
  636. __slots__ = ("name", "email")
  637. def __init__(self, name: Optional[str], email: Optional[str]) -> None:
  638. self.name = name
  639. self.email = email
  640. def __eq__(self, other: Any) -> bool:
  641. return self.name == other.name and self.email == other.email
  642. def __ne__(self, other: Any) -> bool:
  643. return not (self == other)
  644. def __hash__(self) -> int:
  645. return hash((self.name, self.email))
  646. def __str__(self) -> str:
  647. return self.name if self.name else ""
  648. def __repr__(self) -> str:
  649. return '<git.Actor "%s <%s>">' % (self.name, self.email)
  650. @classmethod
  651. def _from_string(cls, string: str) -> "Actor":
  652. """Create an :class:`Actor` from a string.
  653. :param string:
  654. The string, which is expected to be in regular git format::
  655. John Doe <jdoe@example.com>
  656. :return:
  657. :class:`Actor`
  658. """
  659. m = cls.name_email_regex.search(string)
  660. if m:
  661. name, email = m.groups()
  662. return Actor(name, email)
  663. else:
  664. m = cls.name_only_regex.search(string)
  665. if m:
  666. return Actor(m.group(1), None)
  667. # Assume the best and use the whole string as name.
  668. return Actor(string, None)
  669. # END special case name
  670. # END handle name/email matching
  671. @classmethod
  672. def _main_actor(
  673. cls,
  674. env_name: str,
  675. env_email: str,
  676. config_reader: Union[None, "GitConfigParser", "SectionConstraint"] = None,
  677. ) -> "Actor":
  678. actor = Actor("", "")
  679. user_id = None # We use this to avoid multiple calls to getpass.getuser().
  680. def default_email() -> str:
  681. nonlocal user_id
  682. if not user_id:
  683. user_id = get_user_id()
  684. return user_id
  685. def default_name() -> str:
  686. return default_email().split("@")[0]
  687. for attr, evar, cvar, default in (
  688. ("name", env_name, cls.conf_name, default_name),
  689. ("email", env_email, cls.conf_email, default_email),
  690. ):
  691. try:
  692. val = os.environ[evar]
  693. setattr(actor, attr, val)
  694. except KeyError:
  695. if config_reader is not None:
  696. try:
  697. val = config_reader.get("user", cvar)
  698. except Exception:
  699. val = default()
  700. setattr(actor, attr, val)
  701. # END config-reader handling
  702. if not getattr(actor, attr):
  703. setattr(actor, attr, default())
  704. # END handle name
  705. # END for each item to retrieve
  706. return actor
  707. @classmethod
  708. def committer(cls, config_reader: Union[None, "GitConfigParser", "SectionConstraint"] = None) -> "Actor":
  709. """
  710. :return:
  711. :class:`Actor` instance corresponding to the configured committer. It
  712. behaves similar to the git implementation, such that the environment will
  713. override configuration values of `config_reader`. If no value is set at all,
  714. it will be generated.
  715. :param config_reader:
  716. ConfigReader to use to retrieve the values from in case they are not set in
  717. the environment.
  718. """
  719. return cls._main_actor(cls.env_committer_name, cls.env_committer_email, config_reader)
  720. @classmethod
  721. def author(cls, config_reader: Union[None, "GitConfigParser", "SectionConstraint"] = None) -> "Actor":
  722. """Same as :meth:`committer`, but defines the main author. It may be specified
  723. in the environment, but defaults to the committer."""
  724. return cls._main_actor(cls.env_author_name, cls.env_author_email, config_reader)
  725. class Stats:
  726. """Represents stat information as presented by git at the end of a merge. It is
  727. created from the output of a diff operation.
  728. Example::
  729. c = Commit( sha1 )
  730. s = c.stats
  731. s.total # full-stat-dict
  732. s.files # dict( filepath : stat-dict )
  733. ``stat-dict``
  734. A dictionary with the following keys and values::
  735. deletions = number of deleted lines as int
  736. insertions = number of inserted lines as int
  737. lines = total number of lines changed as int, or deletions + insertions
  738. change_type = type of change as str, A|C|D|M|R|T|U|X|B
  739. ``full-stat-dict``
  740. In addition to the items in the stat-dict, it features additional information::
  741. files = number of changed files as int
  742. """
  743. __slots__ = ("total", "files")
  744. def __init__(self, total: Total_TD, files: Dict[PathLike, Files_TD]) -> None:
  745. self.total = total
  746. self.files = files
  747. @classmethod
  748. def _list_from_string(cls, repo: "Repo", text: str) -> "Stats":
  749. """Create a :class:`Stats` object from output retrieved by
  750. :manpage:`git-diff(1)`.
  751. :return:
  752. :class:`git.Stats`
  753. """
  754. hsh: HSH_TD = {
  755. "total": {"insertions": 0, "deletions": 0, "lines": 0, "files": 0},
  756. "files": {},
  757. }
  758. for line in text.splitlines():
  759. (change_type, raw_insertions, raw_deletions, filename) = line.split("\t")
  760. insertions = raw_insertions != "-" and int(raw_insertions) or 0
  761. deletions = raw_deletions != "-" and int(raw_deletions) or 0
  762. hsh["total"]["insertions"] += insertions
  763. hsh["total"]["deletions"] += deletions
  764. hsh["total"]["lines"] += insertions + deletions
  765. hsh["total"]["files"] += 1
  766. files_dict: Files_TD = {
  767. "insertions": insertions,
  768. "deletions": deletions,
  769. "lines": insertions + deletions,
  770. "change_type": change_type,
  771. }
  772. hsh["files"][filename.strip()] = files_dict
  773. return Stats(hsh["total"], hsh["files"])
  774. class IndexFileSHA1Writer:
  775. """Wrapper around a file-like object that remembers the SHA1 of the data written to
  776. it. It will write a sha when the stream is closed or if asked for explicitly using
  777. :meth:`write_sha`.
  778. Only useful to the index file.
  779. :note:
  780. Based on the dulwich project.
  781. """
  782. __slots__ = ("f", "sha1")
  783. def __init__(self, f: IO) -> None:
  784. self.f = f
  785. self.sha1 = make_sha(b"")
  786. def write(self, data: AnyStr) -> int:
  787. self.sha1.update(data)
  788. return self.f.write(data)
  789. def write_sha(self) -> bytes:
  790. sha = self.sha1.digest()
  791. self.f.write(sha)
  792. return sha
  793. def close(self) -> bytes:
  794. sha = self.write_sha()
  795. self.f.close()
  796. return sha
  797. def tell(self) -> int:
  798. return self.f.tell()
  799. class LockFile:
  800. """Provides methods to obtain, check for, and release a file based lock which
  801. should be used to handle concurrent access to the same file.
  802. As we are a utility class to be derived from, we only use protected methods.
  803. Locks will automatically be released on destruction.
  804. """
  805. __slots__ = ("_file_path", "_owns_lock")
  806. def __init__(self, file_path: PathLike) -> None:
  807. self._file_path = file_path
  808. self._owns_lock = False
  809. def __del__(self) -> None:
  810. self._release_lock()
  811. def _lock_file_path(self) -> str:
  812. """:return: Path to lockfile"""
  813. return "%s.lock" % (self._file_path)
  814. def _has_lock(self) -> bool:
  815. """
  816. :return:
  817. True if we have a lock and if the lockfile still exists
  818. :raise AssertionError:
  819. If our lock-file does not exist.
  820. """
  821. return self._owns_lock
  822. def _obtain_lock_or_raise(self) -> None:
  823. """Create a lock file as flag for other instances, mark our instance as
  824. lock-holder.
  825. :raise IOError:
  826. If a lock was already present or a lock file could not be written.
  827. """
  828. if self._has_lock():
  829. return
  830. lock_file = self._lock_file_path()
  831. if osp.isfile(lock_file):
  832. raise IOError(
  833. "Lock for file %r did already exist, delete %r in case the lock is illegal"
  834. % (self._file_path, lock_file)
  835. )
  836. try:
  837. with open(lock_file, mode="w"):
  838. pass
  839. except OSError as e:
  840. raise IOError(str(e)) from e
  841. self._owns_lock = True
  842. def _obtain_lock(self) -> None:
  843. """The default implementation will raise if a lock cannot be obtained.
  844. Subclasses may override this method to provide a different implementation.
  845. """
  846. return self._obtain_lock_or_raise()
  847. def _release_lock(self) -> None:
  848. """Release our lock if we have one."""
  849. if not self._has_lock():
  850. return
  851. # If someone removed our file beforehand, lets just flag this issue instead of
  852. # failing, to make it more usable.
  853. lfp = self._lock_file_path()
  854. try:
  855. rmfile(lfp)
  856. except OSError:
  857. pass
  858. self._owns_lock = False
  859. class BlockingLockFile(LockFile):
  860. """The lock file will block until a lock could be obtained, or fail after a
  861. specified timeout.
  862. :note:
  863. If the directory containing the lock was removed, an exception will be raised
  864. during the blocking period, preventing hangs as the lock can never be obtained.
  865. """
  866. __slots__ = ("_check_interval", "_max_block_time")
  867. def __init__(
  868. self,
  869. file_path: PathLike,
  870. check_interval_s: float = 0.3,
  871. max_block_time_s: int = sys.maxsize,
  872. ) -> None:
  873. """Configure the instance.
  874. :param check_interval_s:
  875. Period of time to sleep until the lock is checked the next time.
  876. By default, it waits a nearly unlimited time.
  877. :param max_block_time_s:
  878. Maximum amount of seconds we may lock.
  879. """
  880. super().__init__(file_path)
  881. self._check_interval = check_interval_s
  882. self._max_block_time = max_block_time_s
  883. def _obtain_lock(self) -> None:
  884. """This method blocks until it obtained the lock, or raises :exc:`IOError` if it
  885. ran out of time or if the parent directory was not available anymore.
  886. If this method returns, you are guaranteed to own the lock.
  887. """
  888. starttime = time.time()
  889. maxtime = starttime + float(self._max_block_time)
  890. while True:
  891. try:
  892. super()._obtain_lock()
  893. except IOError as e:
  894. # synity check: if the directory leading to the lockfile is not
  895. # readable anymore, raise an exception
  896. curtime = time.time()
  897. if not osp.isdir(osp.dirname(self._lock_file_path())):
  898. msg = "Directory containing the lockfile %r was not readable anymore after waiting %g seconds" % (
  899. self._lock_file_path(),
  900. curtime - starttime,
  901. )
  902. raise IOError(msg) from e
  903. # END handle missing directory
  904. if curtime >= maxtime:
  905. msg = "Waited %g seconds for lock at %r" % (
  906. maxtime - starttime,
  907. self._lock_file_path(),
  908. )
  909. raise IOError(msg) from e
  910. # END abort if we wait too long
  911. time.sleep(self._check_interval)
  912. else:
  913. break
  914. # END endless loop
  915. class IterableList(List[T_IterableObj]): # type: ignore[type-var]
  916. """List of iterable objects allowing to query an object by id or by named index::
  917. heads = repo.heads
  918. heads.master
  919. heads['master']
  920. heads[0]
  921. Iterable parent objects:
  922. * :class:`Commit <git.objects.Commit>`
  923. * :class:`Submodule <git.objects.submodule.base.Submodule>`
  924. * :class:`Reference <git.refs.reference.Reference>`
  925. * :class:`FetchInfo <git.remote.FetchInfo>`
  926. * :class:`PushInfo <git.remote.PushInfo>`
  927. Iterable via inheritance:
  928. * :class:`Head <git.refs.head.Head>`
  929. * :class:`TagReference <git.refs.tag.TagReference>`
  930. * :class:`RemoteReference <git.refs.remote.RemoteReference>`
  931. This requires an ``id_attribute`` name to be set which will be queried from its
  932. contained items to have a means for comparison.
  933. A prefix can be specified which is to be used in case the id returned by the items
  934. always contains a prefix that does not matter to the user, so it can be left out.
  935. """
  936. __slots__ = ("_id_attr", "_prefix")
  937. def __new__(cls, id_attr: str, prefix: str = "") -> "IterableList[T_IterableObj]":
  938. return super().__new__(cls)
  939. def __init__(self, id_attr: str, prefix: str = "") -> None:
  940. self._id_attr = id_attr
  941. self._prefix = prefix
  942. def __contains__(self, attr: object) -> bool:
  943. # First try identity match for performance.
  944. try:
  945. rval = list.__contains__(self, attr)
  946. if rval:
  947. return rval
  948. except (AttributeError, TypeError):
  949. pass
  950. # END handle match
  951. # Otherwise make a full name search.
  952. try:
  953. getattr(self, cast(str, attr)) # Use cast to silence mypy.
  954. return True
  955. except (AttributeError, TypeError):
  956. return False
  957. # END handle membership
  958. def __getattr__(self, attr: str) -> T_IterableObj:
  959. attr = self._prefix + attr
  960. for item in self:
  961. if getattr(item, self._id_attr) == attr:
  962. return item
  963. # END for each item
  964. return list.__getattribute__(self, attr)
  965. def __getitem__(self, index: Union[SupportsIndex, int, slice, str]) -> T_IterableObj: # type: ignore[override]
  966. if isinstance(index, int):
  967. return list.__getitem__(self, index)
  968. elif isinstance(index, slice):
  969. raise ValueError("Index should be an int or str")
  970. else:
  971. try:
  972. return getattr(self, cast(str, index))
  973. except AttributeError as e:
  974. raise IndexError(f"No item found with id {self._prefix}{index}") from e
  975. # END handle getattr
  976. def __delitem__(self, index: Union[SupportsIndex, int, slice, str]) -> None:
  977. delindex = cast(int, index)
  978. if isinstance(index, str):
  979. delindex = -1
  980. name = self._prefix + index
  981. for i, item in enumerate(self):
  982. if getattr(item, self._id_attr) == name:
  983. delindex = i
  984. break
  985. # END search index
  986. # END for each item
  987. if delindex == -1:
  988. raise IndexError("Item with name %s not found" % name)
  989. # END handle error
  990. # END get index to delete
  991. list.__delitem__(self, delindex)
  992. @runtime_checkable
  993. class IterableObj(Protocol):
  994. """Defines an interface for iterable items, so there is a uniform way to retrieve
  995. and iterate items within the git repository.
  996. Subclasses:
  997. * :class:`Submodule <git.objects.submodule.base.Submodule>`
  998. * :class:`Commit <git.objects.Commit>`
  999. * :class:`Reference <git.refs.reference.Reference>`
  1000. * :class:`PushInfo <git.remote.PushInfo>`
  1001. * :class:`FetchInfo <git.remote.FetchInfo>`
  1002. * :class:`Remote <git.remote.Remote>`
  1003. """
  1004. __slots__ = ()
  1005. _id_attribute_: str
  1006. @classmethod
  1007. @abstractmethod
  1008. def iter_items(cls, repo: "Repo", *args: Any, **kwargs: Any) -> Iterator[T_IterableObj]:
  1009. # Return-typed to be compatible with subtypes e.g. Remote.
  1010. """Find (all) items of this type.
  1011. Subclasses can specify `args` and `kwargs` differently, and may use them for
  1012. filtering. However, when the method is called with no additional positional or
  1013. keyword arguments, subclasses are obliged to to yield all items.
  1014. :return:
  1015. Iterator yielding Items
  1016. """
  1017. raise NotImplementedError("To be implemented by Subclass")
  1018. @classmethod
  1019. def list_items(cls, repo: "Repo", *args: Any, **kwargs: Any) -> IterableList[T_IterableObj]:
  1020. """Find (all) items of this type and collect them into a list.
  1021. For more information about the arguments, see :meth:`iter_items`.
  1022. :note:
  1023. Favor the :meth:`iter_items` method as it will avoid eagerly collecting all
  1024. items. When there are many items, that can slow performance and increase
  1025. memory usage.
  1026. :return:
  1027. list(Item,...) list of item instances
  1028. """
  1029. out_list: IterableList = IterableList(cls._id_attribute_)
  1030. out_list.extend(cls.iter_items(repo, *args, **kwargs))
  1031. return out_list
  1032. class IterableClassWatcher(type):
  1033. """Metaclass that issues :exc:`DeprecationWarning` when :class:`git.util.Iterable`
  1034. is subclassed."""
  1035. def __init__(cls, name: str, bases: Tuple, clsdict: Dict) -> None:
  1036. for base in bases:
  1037. if type(base) is IterableClassWatcher:
  1038. warnings.warn(
  1039. f"GitPython Iterable subclassed by {name}."
  1040. " Iterable is deprecated due to naming clash since v3.1.18"
  1041. " and will be removed in 4.0.0."
  1042. " Use IterableObj instead.",
  1043. DeprecationWarning,
  1044. stacklevel=2,
  1045. )
  1046. class Iterable(metaclass=IterableClassWatcher):
  1047. """Deprecated, use :class:`IterableObj` instead.
  1048. Defines an interface for iterable items, so there is a uniform way to retrieve
  1049. and iterate items within the git repository.
  1050. """
  1051. __slots__ = ()
  1052. _id_attribute_ = "attribute that most suitably identifies your instance"
  1053. @classmethod
  1054. def iter_items(cls, repo: "Repo", *args: Any, **kwargs: Any) -> Any:
  1055. """Deprecated, use :class:`IterableObj` instead.
  1056. Find (all) items of this type.
  1057. See :meth:`IterableObj.iter_items` for details on usage.
  1058. :return:
  1059. Iterator yielding Items
  1060. """
  1061. raise NotImplementedError("To be implemented by Subclass")
  1062. @classmethod
  1063. def list_items(cls, repo: "Repo", *args: Any, **kwargs: Any) -> Any:
  1064. """Deprecated, use :class:`IterableObj` instead.
  1065. Find (all) items of this type and collect them into a list.
  1066. See :meth:`IterableObj.list_items` for details on usage.
  1067. :return:
  1068. list(Item,...) list of item instances
  1069. """
  1070. out_list: Any = IterableList(cls._id_attribute_)
  1071. out_list.extend(cls.iter_items(repo, *args, **kwargs))
  1072. return out_list
  1073. # } END classes