utils.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # utils.py -- Git compatibility utilities
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # of the License or (at your option) any later version of
  8. # the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Utilities for interacting with cgit."""
  20. import errno
  21. import os
  22. import socket
  23. import subprocess
  24. import tempfile
  25. import time
  26. from dulwich.repo import Repo
  27. from dulwich.protocol import TCP_GIT_PORT
  28. from dulwich.tests import (
  29. SkipTest,
  30. TestCase,
  31. )
  32. _DEFAULT_GIT = 'git'
  33. _VERSION_LEN = 4
  34. _REPOS_DATA_DIR = os.path.abspath(os.path.join(
  35. os.path.dirname(__file__), os.pardir, 'data', 'repos'))
  36. def git_version(git_path=_DEFAULT_GIT):
  37. """Attempt to determine the version of git currently installed.
  38. :param git_path: Path to the git executable; defaults to the version in
  39. the system path.
  40. :return: A tuple of ints of the form (major, minor, point, sub-point), or
  41. None if no git installation was found.
  42. """
  43. try:
  44. output = run_git_or_fail(['--version'], git_path=git_path)
  45. except OSError:
  46. return None
  47. version_prefix = 'git version '
  48. if not output.startswith(version_prefix):
  49. return None
  50. parts = output[len(version_prefix):].split('.')
  51. nums = []
  52. for part in parts:
  53. try:
  54. nums.append(int(part))
  55. except ValueError:
  56. break
  57. while len(nums) < _VERSION_LEN:
  58. nums.append(0)
  59. return tuple(nums[:_VERSION_LEN])
  60. def require_git_version(required_version, git_path=_DEFAULT_GIT):
  61. """Require git version >= version, or skip the calling test.
  62. :param required_version: A tuple of ints of the form (major, minor, point,
  63. sub-point); ommitted components default to 0.
  64. :param git_path: Path to the git executable; defaults to the version in
  65. the system path.
  66. :raise ValueError: if the required version tuple has too many parts.
  67. :raise SkipTest: if no suitable git version was found at the given path.
  68. """
  69. found_version = git_version(git_path=git_path)
  70. if found_version is None:
  71. raise SkipTest('Test requires git >= %s, but c git not found' %
  72. (required_version, ))
  73. if len(required_version) > _VERSION_LEN:
  74. raise ValueError('Invalid version tuple %s, expected %i parts' %
  75. (required_version, _VERSION_LEN))
  76. required_version = list(required_version)
  77. while len(found_version) < len(required_version):
  78. required_version.append(0)
  79. required_version = tuple(required_version)
  80. if found_version < required_version:
  81. required_version = '.'.join(map(str, required_version))
  82. found_version = '.'.join(map(str, found_version))
  83. raise SkipTest('Test requires git >= %s, found %s' %
  84. (required_version, found_version))
  85. def run_git(args, git_path=_DEFAULT_GIT, input=None, capture_stdout=False,
  86. **popen_kwargs):
  87. """Run a git command.
  88. Input is piped from the input parameter and output is sent to the standard
  89. streams, unless capture_stdout is set.
  90. :param args: A list of args to the git command.
  91. :param git_path: Path to to the git executable.
  92. :param input: Input data to be sent to stdin.
  93. :param capture_stdout: Whether to capture and return stdout.
  94. :param popen_kwargs: Additional kwargs for subprocess.Popen;
  95. stdin/stdout args are ignored.
  96. :return: A tuple of (returncode, stdout contents). If capture_stdout is
  97. False, None will be returned as stdout contents.
  98. :raise OSError: if the git executable was not found.
  99. """
  100. args = [git_path] + args
  101. popen_kwargs['stdin'] = subprocess.PIPE
  102. if capture_stdout:
  103. popen_kwargs['stdout'] = subprocess.PIPE
  104. else:
  105. popen_kwargs.pop('stdout', None)
  106. p = subprocess.Popen(args, **popen_kwargs)
  107. stdout, stderr = p.communicate(input=input)
  108. return (p.returncode, stdout)
  109. def run_git_or_fail(args, git_path=_DEFAULT_GIT, input=None, **popen_kwargs):
  110. """Run a git command, capture stdout/stderr, and fail if git fails."""
  111. popen_kwargs['stderr'] = subprocess.STDOUT
  112. returncode, stdout = run_git(args, git_path=git_path, input=input,
  113. capture_stdout=True, **popen_kwargs)
  114. assert returncode == 0, "git with args %r failed with %d" % (
  115. args, returncode)
  116. return stdout
  117. def import_repo_to_dir(name):
  118. """Import a repo from a fast-export file in a temporary directory.
  119. These are used rather than binary repos for compat tests because they are
  120. more compact an human-editable, and we already depend on git.
  121. :param name: The name of the repository export file, relative to
  122. dulwich/tests/data/repos.
  123. :returns: The path to the imported repository.
  124. """
  125. temp_dir = tempfile.mkdtemp()
  126. export_path = os.path.join(_REPOS_DATA_DIR, name)
  127. temp_repo_dir = os.path.join(temp_dir, name)
  128. export_file = open(export_path, 'rb')
  129. run_git_or_fail(['init', '--quiet', '--bare', temp_repo_dir])
  130. run_git_or_fail(['fast-import'], input=export_file.read(),
  131. cwd=temp_repo_dir)
  132. export_file.close()
  133. return temp_repo_dir
  134. def import_repo(name):
  135. """Import a repo from a fast-export file in a temporary directory.
  136. :param name: The name of the repository export file, relative to
  137. dulwich/tests/data/repos.
  138. :returns: An initialized Repo object that lives in a temporary directory.
  139. """
  140. return Repo(import_repo_to_dir(name))
  141. def check_for_daemon(limit=10, delay=0.1, timeout=0.1, port=TCP_GIT_PORT):
  142. """Check for a running TCP daemon.
  143. Defaults to checking 10 times with a delay of 0.1 sec between tries.
  144. :param limit: Number of attempts before deciding no daemon is running.
  145. :param delay: Delay between connection attempts.
  146. :param timeout: Socket timeout for connection attempts.
  147. :param port: Port on which we expect the daemon to appear.
  148. :returns: A boolean, true if a daemon is running on the specified port,
  149. false if not.
  150. """
  151. for _ in xrange(limit):
  152. time.sleep(delay)
  153. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  154. s.settimeout(delay)
  155. try:
  156. s.connect(('localhost', port))
  157. s.close()
  158. return True
  159. except socket.error, e:
  160. if getattr(e, 'errno', False) and e.errno != errno.ECONNREFUSED:
  161. raise
  162. elif e.args[0] != errno.ECONNREFUSED:
  163. raise
  164. return False
  165. class CompatTestCase(TestCase):
  166. """Test case that requires git for compatibility checks.
  167. Subclasses can change the git version required by overriding
  168. min_git_version.
  169. """
  170. min_git_version = (1, 5, 0)
  171. def setUp(self):
  172. super(CompatTestCase, self).setUp()
  173. require_git_version(self.min_git_version)
  174. def assertReposEqual(self, repo1, repo2):
  175. self.assertEqual(repo1.get_refs(), repo2.get_refs())
  176. self.assertEqual(sorted(set(repo1.object_store)),
  177. sorted(set(repo2.object_store)))
  178. def assertReposNotEqual(self, repo1, repo2):
  179. refs1 = repo1.get_refs()
  180. objs1 = set(repo1.object_store)
  181. refs2 = repo2.get_refs()
  182. objs2 = set(repo2.object_store)
  183. self.assertFalse(refs1 == refs2 and objs1 == objs2)