utils.py 8.8 KB

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