git_command.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import sys
  17. import subprocess
  18. import tempfile
  19. from error import GitError
  20. from trace import REPO_TRACE, IsTrace, Trace
  21. GIT = 'git'
  22. MIN_GIT_VERSION = (1, 5, 4)
  23. GIT_DIR = 'GIT_DIR'
  24. LAST_GITDIR = None
  25. LAST_CWD = None
  26. _ssh_proxy_path = None
  27. _ssh_sock_path = None
  28. def _ssh_sock(create=True):
  29. global _ssh_sock_path
  30. if _ssh_sock_path is None:
  31. if not create:
  32. return None
  33. dir = '/tmp'
  34. if not os.path.exists(dir):
  35. dir = tempfile.gettempdir()
  36. _ssh_sock_path = os.path.join(
  37. tempfile.mkdtemp('', 'ssh-', dir),
  38. 'master-%r@%h:%p')
  39. return _ssh_sock_path
  40. def _ssh_proxy():
  41. global _ssh_proxy_path
  42. if _ssh_proxy_path is None:
  43. _ssh_proxy_path = os.path.join(
  44. os.path.dirname(__file__),
  45. 'git_ssh')
  46. return _ssh_proxy_path
  47. class _GitCall(object):
  48. def version(self):
  49. p = GitCommand(None, ['--version'], capture_stdout=True)
  50. if p.Wait() == 0:
  51. return p.stdout
  52. return None
  53. def __getattr__(self, name):
  54. name = name.replace('_','-')
  55. def fun(*cmdv):
  56. command = [name]
  57. command.extend(cmdv)
  58. return GitCommand(None, command).Wait() == 0
  59. return fun
  60. git = _GitCall()
  61. _git_version = None
  62. def git_require(min_version, fail=False):
  63. global _git_version
  64. if _git_version is None:
  65. ver_str = git.version()
  66. if ver_str.startswith('git version '):
  67. _git_version = tuple(
  68. map(lambda x: int(x),
  69. ver_str[len('git version '):].strip().split('.')[0:3]
  70. ))
  71. else:
  72. print >>sys.stderr, 'fatal: "%s" unsupported' % ver_str
  73. sys.exit(1)
  74. if min_version <= _git_version:
  75. return True
  76. if fail:
  77. need = '.'.join(map(lambda x: str(x), min_version))
  78. print >>sys.stderr, 'fatal: git %s or later required' % need
  79. sys.exit(1)
  80. return False
  81. class GitCommand(object):
  82. def __init__(self,
  83. project,
  84. cmdv,
  85. bare = False,
  86. provide_stdin = False,
  87. capture_stdout = False,
  88. capture_stderr = False,
  89. disable_editor = False,
  90. ssh_proxy = False,
  91. cwd = None,
  92. gitdir = None):
  93. env = dict(os.environ)
  94. for e in [REPO_TRACE,
  95. GIT_DIR,
  96. 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
  97. 'GIT_OBJECT_DIRECTORY',
  98. 'GIT_WORK_TREE',
  99. 'GIT_GRAFT_FILE',
  100. 'GIT_INDEX_FILE']:
  101. if e in env:
  102. del env[e]
  103. if disable_editor:
  104. env['GIT_EDITOR'] = ':'
  105. if ssh_proxy:
  106. env['REPO_SSH_SOCK'] = _ssh_sock()
  107. env['GIT_SSH'] = _ssh_proxy()
  108. if project:
  109. if not cwd:
  110. cwd = project.worktree
  111. if not gitdir:
  112. gitdir = project.gitdir
  113. command = [GIT]
  114. if bare:
  115. if gitdir:
  116. env[GIT_DIR] = gitdir
  117. cwd = None
  118. command.extend(cmdv)
  119. if provide_stdin:
  120. stdin = subprocess.PIPE
  121. else:
  122. stdin = None
  123. if capture_stdout:
  124. stdout = subprocess.PIPE
  125. else:
  126. stdout = None
  127. if capture_stderr:
  128. stderr = subprocess.PIPE
  129. else:
  130. stderr = None
  131. if IsTrace():
  132. global LAST_CWD
  133. global LAST_GITDIR
  134. dbg = ''
  135. if cwd and LAST_CWD != cwd:
  136. if LAST_GITDIR or LAST_CWD:
  137. dbg += '\n'
  138. dbg += ': cd %s\n' % cwd
  139. LAST_CWD = cwd
  140. if GIT_DIR in env and LAST_GITDIR != env[GIT_DIR]:
  141. if LAST_GITDIR or LAST_CWD:
  142. dbg += '\n'
  143. dbg += ': export GIT_DIR=%s\n' % env[GIT_DIR]
  144. LAST_GITDIR = env[GIT_DIR]
  145. dbg += ': '
  146. dbg += ' '.join(command)
  147. if stdin == subprocess.PIPE:
  148. dbg += ' 0<|'
  149. if stdout == subprocess.PIPE:
  150. dbg += ' 1>|'
  151. if stderr == subprocess.PIPE:
  152. dbg += ' 2>|'
  153. Trace('%s', dbg)
  154. try:
  155. p = subprocess.Popen(command,
  156. cwd = cwd,
  157. env = env,
  158. stdin = stdin,
  159. stdout = stdout,
  160. stderr = stderr)
  161. except Exception, e:
  162. raise GitError('%s: %s' % (command[1], e))
  163. self.process = p
  164. self.stdin = p.stdin
  165. def Wait(self):
  166. p = self.process
  167. if p.stdin:
  168. p.stdin.close()
  169. self.stdin = None
  170. if p.stdout:
  171. self.stdout = p.stdout.read()
  172. p.stdout.close()
  173. else:
  174. p.stdout = None
  175. if p.stderr:
  176. self.stderr = p.stderr.read()
  177. p.stderr.close()
  178. else:
  179. p.stderr = None
  180. return self.process.wait()