2
0

utils.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. TestCase,
  30. TestSkipped,
  31. )
  32. _DEFAULT_GIT = 'git'
  33. def git_version(git_path=_DEFAULT_GIT):
  34. """Attempt to determine the version of git currently installed.
  35. :param git_path: Path to the git executable; defaults to the version in
  36. the system path.
  37. :return: A tuple of ints of the form (major, minor, point), or None if no
  38. git installation was found.
  39. """
  40. try:
  41. _, output = run_git(['--version'], git_path=git_path,
  42. capture_stdout=True)
  43. except OSError:
  44. return None
  45. version_prefix = 'git version '
  46. if not output.startswith(version_prefix):
  47. return None
  48. output = output[len(version_prefix):]
  49. nums = output.split('.')
  50. if len(nums) == 2:
  51. nums.add('0')
  52. else:
  53. nums = nums[:3]
  54. try:
  55. return tuple(int(x) for x in nums)
  56. except ValueError:
  57. return None
  58. def require_git_version(required_version, git_path=_DEFAULT_GIT):
  59. """Require git version >= version, or skip the calling test."""
  60. found_version = git_version(git_path=git_path)
  61. if found_version < required_version:
  62. required_version = '.'.join(map(str, required_version))
  63. found_version = '.'.join(map(str, found_version))
  64. raise TestSkipped('Test requires git >= %s, found %s' %
  65. (required_version, found_version))
  66. def run_git(args, git_path=_DEFAULT_GIT, input=None, capture_stdout=False,
  67. **popen_kwargs):
  68. """Run a git command.
  69. Input is piped from the input parameter and output is sent to the standard
  70. streams, unless capture_stdout is set.
  71. :param args: A list of args to the git command.
  72. :param git_path: Path to to the git executable.
  73. :param input: Input data to be sent to stdin.
  74. :param capture_stdout: Whether to capture and return stdout.
  75. :param popen_kwargs: Additional kwargs for subprocess.Popen;
  76. stdin/stdout args are ignored.
  77. :return: A tuple of (returncode, stdout contents). If capture_stdout is
  78. False, None will be returned as stdout contents.
  79. :raise OSError: if the git executable was not found.
  80. """
  81. args = [git_path] + args
  82. popen_kwargs['stdin'] = subprocess.PIPE
  83. if capture_stdout:
  84. popen_kwargs['stdout'] = subprocess.PIPE
  85. else:
  86. popen_kwargs.pop('stdout', None)
  87. p = subprocess.Popen(args, **popen_kwargs)
  88. stdout, stderr = p.communicate(input=input)
  89. return (p.returncode, stdout)
  90. def run_git_or_fail(args, git_path=_DEFAULT_GIT, input=None, **popen_kwargs):
  91. """Run a git command, capture stdout/stderr, and fail if git fails."""
  92. popen_kwargs['stderr'] = subprocess.STDOUT
  93. returncode, stdout = run_git(args, git_path=git_path, input=input,
  94. capture_stdout=True, **popen_kwargs)
  95. assert returncode == 0
  96. return stdout
  97. def import_repo_to_dir(name):
  98. """Import a repo from a fast-export file in a temporary directory.
  99. These are used rather than binary repos for compat tests because they are
  100. more compact an human-editable, and we already depend on git.
  101. :param name: The name of the repository export file, relative to
  102. dulwich/tests/data/repos.
  103. :returns: The path to the imported repository.
  104. """
  105. temp_dir = tempfile.mkdtemp()
  106. export_path = os.path.join(os.path.dirname(__file__), os.pardir, 'data',
  107. 'repos', name)
  108. temp_repo_dir = os.path.join(temp_dir, name)
  109. export_file = open(export_path, 'rb')
  110. run_git_or_fail(['init', '--bare', temp_repo_dir])
  111. run_git_or_fail(['fast-import'], input=export_file.read(),
  112. cwd=temp_repo_dir)
  113. export_file.close()
  114. return temp_repo_dir
  115. def import_repo(name):
  116. """Import a repo from a fast-export file in a temporary directory.
  117. :param name: The name of the repository export file, relative to
  118. dulwich/tests/data/repos.
  119. :returns: An initialized Repo object that lives in a temporary directory.
  120. """
  121. return Repo(import_repo_to_dir(name))
  122. def check_for_daemon(limit=10, delay=0.1, timeout=0.1, port=TCP_GIT_PORT):
  123. """Check for a running TCP daemon.
  124. Defaults to checking 10 times with a delay of 0.1 sec between tries.
  125. :param limit: Number of attempts before deciding no daemon is running.
  126. :param delay: Delay between connection attempts.
  127. :param timeout: Socket timeout for connection attempts.
  128. :param port: Port on which we expect the daemon to appear.
  129. :returns: A boolean, true if a daemon is running on the specified port,
  130. false if not.
  131. """
  132. for _ in xrange(limit):
  133. time.sleep(delay)
  134. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  135. s.settimeout(delay)
  136. try:
  137. s.connect(('localhost', port))
  138. s.close()
  139. return True
  140. except socket.error, e:
  141. if getattr(e, 'errno', False) and e.errno != errno.ECONNREFUSED:
  142. raise
  143. elif e.args[0] != errno.ECONNREFUSED:
  144. raise
  145. return False
  146. class CompatTestCase(TestCase):
  147. """Test case that requires git for compatibility checks.
  148. Subclasses can change the git version required by overriding
  149. min_git_version.
  150. """
  151. min_git_version = (1, 5, 0)
  152. def setUp(self):
  153. require_git_version(self.min_git_version)
  154. def assertReposEqual(self, repo1, repo2):
  155. self.assertEqual(repo1.get_refs(), repo2.get_refs())
  156. self.assertEqual(sorted(set(repo1.object_store)),
  157. sorted(set(repo2.object_store)))
  158. def assertReposNotEqual(self, repo1, repo2):
  159. refs1 = repo1.get_refs()
  160. objs1 = set(repo1.object_store)
  161. refs2 = repo2.get_refs()
  162. objs2 = set(repo2.object_store)
  163. self.assertFalse(refs1 == refs2 and objs1 == objs2)