utils.py 9.1 KB

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