utils.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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 os
  21. import subprocess
  22. import tempfile
  23. import unittest
  24. from dulwich.repo import Repo
  25. from dulwich.tests import (
  26. TestSkipped,
  27. )
  28. _DEFAULT_GIT = 'git'
  29. def git_version(git_path=_DEFAULT_GIT):
  30. """Attempt to determine the version of git currently installed.
  31. :param git_path: Path to the git executable; defaults to the version in
  32. the system path.
  33. :return: A tuple of ints of the form (major, minor, point), or None if no
  34. git installation was found.
  35. """
  36. try:
  37. _, output = run_git(['--version'], git_path=git_path,
  38. capture_stdout=True)
  39. except OSError:
  40. return None
  41. version_prefix = 'git version '
  42. if not output.startswith(version_prefix):
  43. return None
  44. output = output[len(version_prefix):]
  45. nums = output.split('.')
  46. if len(nums) == 2:
  47. nums.add('0')
  48. else:
  49. nums = nums[:3]
  50. try:
  51. return tuple(int(x) for x in nums)
  52. except ValueError:
  53. return None
  54. def require_git_version(required_version, git_path=_DEFAULT_GIT):
  55. """Require git version >= version, or skip the calling test."""
  56. found_version = git_version(git_path=git_path)
  57. if found_version < required_version:
  58. required_version = '.'.join(map(str, required_version))
  59. found_version = '.'.join(map(str, found_version))
  60. raise TestSkipped('Test requires git >= %s, found %s' %
  61. (required_version, found_version))
  62. def run_git(args, git_path=_DEFAULT_GIT, input=None, capture_stdout=False,
  63. **popen_kwargs):
  64. """Run a git command.
  65. Input is piped from the input parameter and output is sent to the standard
  66. streams, unless capture_stdout is set.
  67. :param args: A list of args to the git command.
  68. :param git_path: Path to to the git executable.
  69. :param input: Input data to be sent to stdin.
  70. :param capture_stdout: Whether to capture and return stdout.
  71. :param popen_kwargs: Additional kwargs for subprocess.Popen;
  72. stdin/stdout args are ignored.
  73. :return: A tuple of (returncode, stdout contents). If capture_stdout is
  74. False, None will be returned as stdout contents.
  75. :raise OSError: if the git executable was not found.
  76. """
  77. args = [git_path] + args
  78. popen_kwargs['stdin'] = subprocess.PIPE
  79. if capture_stdout:
  80. popen_kwargs['stdout'] = subprocess.PIPE
  81. else:
  82. popen_kwargs.pop('stdout', None)
  83. p = subprocess.Popen(args, **popen_kwargs)
  84. stdout, stderr = p.communicate(input=input)
  85. return (p.returncode, stdout)
  86. def run_git_or_fail(args, git_path=_DEFAULT_GIT, input=None, **popen_kwargs):
  87. """Run a git command, capture stdout/stderr, and fail if git fails."""
  88. popen_kwargs['stderr'] = subprocess.STDOUT
  89. returncode, stdout = run_git(args, git_path=git_path, input=input,
  90. capture_stdout=True, **popen_kwargs)
  91. assert returncode == 0
  92. return stdout
  93. def import_repo(name):
  94. """Import a repo from a fast-export file in a temporary directory.
  95. These are used rather than binary repos for compat tests because they are
  96. more compact an human-editable, and we already depend on git.
  97. :param name: The name of the repository export file, relative to
  98. dulwich/tests/data/repos
  99. :returns: An initialized Repo object that lives in a temporary directory.
  100. """
  101. temp_dir = tempfile.mkdtemp()
  102. export_path = os.path.join(os.path.dirname(__file__), os.pardir, 'data',
  103. 'repos', name)
  104. temp_repo_dir = os.path.join(temp_dir, name)
  105. export_file = open(export_path, 'rb')
  106. run_git_or_fail(['init', '--bare', temp_repo_dir])
  107. run_git_or_fail(['fast-import'], input=export_file.read(),
  108. cwd=temp_repo_dir)
  109. export_file.close()
  110. return Repo(temp_repo_dir)
  111. class CompatTestCase(unittest.TestCase):
  112. """Test case that requires git for compatibility checks.
  113. Subclasses can change the git version required by overriding
  114. min_git_version.
  115. """
  116. min_git_version = (1, 5, 0)
  117. def setUp(self):
  118. require_git_version(self.min_git_version)