2
0

utils.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. # utils.py -- Git compatibility utilities
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  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. """Utilities for interacting with cgit."""
  22. import errno
  23. import functools
  24. import os
  25. import shutil
  26. import socket
  27. import stat
  28. import subprocess
  29. import sys
  30. import tempfile
  31. import time
  32. from dulwich.protocol import TCP_GIT_PORT
  33. from dulwich.repo import Repo
  34. from .. import SkipTest, TestCase
  35. _DEFAULT_GIT = "git"
  36. _VERSION_LEN = 4
  37. _REPOS_DATA_DIR = os.path.abspath(
  38. os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "testdata", "repos")
  39. )
  40. def git_version(git_path=_DEFAULT_GIT):
  41. """Attempt to determine the version of git currently installed.
  42. Args:
  43. git_path: Path to the git executable; defaults to the version in
  44. the system path.
  45. Returns: A tuple of ints of the form (major, minor, point, sub-point), or
  46. None if no git installation was found.
  47. """
  48. try:
  49. output = run_git_or_fail(["--version"], git_path=git_path)
  50. except OSError:
  51. return None
  52. version_prefix = b"git version "
  53. if not output.startswith(version_prefix):
  54. return None
  55. parts = output[len(version_prefix) :].split(b".")
  56. nums = []
  57. for part in parts:
  58. try:
  59. nums.append(int(part))
  60. except ValueError:
  61. break
  62. while len(nums) < _VERSION_LEN:
  63. nums.append(0)
  64. return tuple(nums[:_VERSION_LEN])
  65. def require_git_version(required_version, git_path=_DEFAULT_GIT) -> None:
  66. """Require git version >= version, or skip the calling test.
  67. Args:
  68. required_version: A tuple of ints of the form (major, minor, point,
  69. sub-point); omitted components default to 0.
  70. git_path: Path to the git executable; defaults to the version in
  71. the system path.
  72. Raises:
  73. ValueError: if the required version tuple has too many parts.
  74. SkipTest: if no suitable git version was found at the given path.
  75. """
  76. found_version = git_version(git_path=git_path)
  77. if found_version is None:
  78. raise SkipTest(f"Test requires git >= {required_version}, but c git not found")
  79. if len(required_version) > _VERSION_LEN:
  80. raise ValueError(
  81. "Invalid version tuple %s, expected %i parts"
  82. % (required_version, _VERSION_LEN)
  83. )
  84. required_version = list(required_version)
  85. while len(found_version) < len(required_version):
  86. required_version.append(0)
  87. required_version = tuple(required_version)
  88. if found_version < required_version:
  89. required_version = ".".join(map(str, required_version))
  90. found_version = ".".join(map(str, found_version))
  91. raise SkipTest(
  92. f"Test requires git >= {required_version}, found {found_version}"
  93. )
  94. def run_git(
  95. args,
  96. git_path=_DEFAULT_GIT,
  97. input=None,
  98. capture_stdout=False,
  99. capture_stderr=False,
  100. **popen_kwargs,
  101. ):
  102. """Run a git command.
  103. Input is piped from the input parameter and output is sent to the standard
  104. streams, unless capture_stdout is set.
  105. Args:
  106. args: A list of args to the git command.
  107. git_path: Path to to the git executable.
  108. input: Input data to be sent to stdin.
  109. capture_stdout: Whether to capture and return stdout.
  110. popen_kwargs: Additional kwargs for subprocess.Popen;
  111. stdin/stdout args are ignored.
  112. Returns: A tuple of (returncode, stdout contents, stderr contents).
  113. If capture_stdout is False, None will be returned as stdout contents.
  114. If capture_stderr is False, None will be returned as stderr contents.
  115. Raises:
  116. OSError: if the git executable was not found.
  117. """
  118. env = popen_kwargs.pop("env", {})
  119. env["LC_ALL"] = env["LANG"] = "C"
  120. env["PATH"] = os.getenv("PATH")
  121. args = [git_path, *args]
  122. popen_kwargs["stdin"] = subprocess.PIPE
  123. if capture_stdout:
  124. popen_kwargs["stdout"] = subprocess.PIPE
  125. else:
  126. popen_kwargs.pop("stdout", None)
  127. if capture_stderr:
  128. popen_kwargs["stderr"] = subprocess.PIPE
  129. else:
  130. popen_kwargs.pop("stderr", None)
  131. p = subprocess.Popen(args, env=env, **popen_kwargs)
  132. stdout, stderr = p.communicate(input=input)
  133. return (p.returncode, stdout, stderr)
  134. def run_git_or_fail(args, git_path=_DEFAULT_GIT, input=None, **popen_kwargs):
  135. """Run a git command, capture stdout/stderr, and fail if git fails."""
  136. if "stderr" not in popen_kwargs:
  137. popen_kwargs["stderr"] = subprocess.STDOUT
  138. returncode, stdout, stderr = run_git(
  139. args,
  140. git_path=git_path,
  141. input=input,
  142. capture_stdout=True,
  143. capture_stderr=True,
  144. **popen_kwargs,
  145. )
  146. if returncode != 0:
  147. raise AssertionError(
  148. "git with args %r failed with %d: stdout=%r stderr=%r"
  149. % (args, returncode, stdout, stderr)
  150. )
  151. return stdout
  152. def import_repo_to_dir(name):
  153. """Import a repo from a fast-export file in a temporary directory.
  154. These are used rather than binary repos for compat tests because they are
  155. more compact and human-editable, and we already depend on git.
  156. Args:
  157. name: The name of the repository export file, relative to
  158. dulwich/tests/data/repos.
  159. Returns: The path to the imported repository.
  160. """
  161. temp_dir = tempfile.mkdtemp()
  162. export_path = os.path.join(_REPOS_DATA_DIR, name)
  163. temp_repo_dir = os.path.join(temp_dir, name)
  164. export_file = open(export_path, "rb")
  165. run_git_or_fail(["init", "--quiet", "--bare", temp_repo_dir])
  166. run_git_or_fail(["fast-import"], input=export_file.read(), cwd=temp_repo_dir)
  167. export_file.close()
  168. return temp_repo_dir
  169. def check_for_daemon(limit=10, delay=0.1, timeout=0.1, port=TCP_GIT_PORT) -> bool:
  170. """Check for a running TCP daemon.
  171. Defaults to checking 10 times with a delay of 0.1 sec between tries.
  172. Args:
  173. limit: Number of attempts before deciding no daemon is running.
  174. delay: Delay between connection attempts.
  175. timeout: Socket timeout for connection attempts.
  176. port: Port on which we expect the daemon to appear.
  177. Returns: A boolean, true if a daemon is running on the specified port,
  178. false if not.
  179. """
  180. for _ in range(limit):
  181. time.sleep(delay)
  182. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  183. s.settimeout(delay)
  184. try:
  185. s.connect(("localhost", port))
  186. return True
  187. except socket.timeout:
  188. pass
  189. except OSError as e:
  190. if getattr(e, "errno", False) and e.errno != errno.ECONNREFUSED:
  191. raise
  192. elif e.args[0] != errno.ECONNREFUSED:
  193. raise
  194. finally:
  195. s.close()
  196. return False
  197. class CompatTestCase(TestCase):
  198. """Test case that requires git for compatibility checks.
  199. Subclasses can change the git version required by overriding
  200. min_git_version.
  201. """
  202. min_git_version: tuple[int, ...] = (1, 5, 0)
  203. def setUp(self) -> None:
  204. super().setUp()
  205. require_git_version(self.min_git_version)
  206. def assertObjectStoreEqual(self, store1, store2) -> None:
  207. self.assertEqual(sorted(set(store1)), sorted(set(store2)))
  208. def assertReposEqual(self, repo1, repo2) -> None:
  209. self.assertEqual(repo1.get_refs(), repo2.get_refs())
  210. self.assertObjectStoreEqual(repo1.object_store, repo2.object_store)
  211. def assertReposNotEqual(self, repo1, repo2) -> None:
  212. refs1 = repo1.get_refs()
  213. objs1 = set(repo1.object_store)
  214. refs2 = repo2.get_refs()
  215. objs2 = set(repo2.object_store)
  216. self.assertFalse(refs1 == refs2 and objs1 == objs2)
  217. def import_repo(self, name):
  218. """Import a repo from a fast-export file in a temporary directory.
  219. Args:
  220. name: The name of the repository export file, relative to
  221. dulwich/tests/data/repos.
  222. Returns: An initialized Repo object that lives in a temporary
  223. directory.
  224. """
  225. path = import_repo_to_dir(name)
  226. repo = Repo(path)
  227. def cleanup() -> None:
  228. repo.close()
  229. rmtree_ro(os.path.dirname(path.rstrip(os.sep)))
  230. self.addCleanup(cleanup)
  231. return repo
  232. if sys.platform == "win32":
  233. def remove_ro(action, name, exc) -> None:
  234. os.chmod(name, stat.S_IWRITE)
  235. os.remove(name)
  236. rmtree_ro = functools.partial(shutil.rmtree, onerror=remove_ro)
  237. else:
  238. rmtree_ro = shutil.rmtree