您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1110 行
42KB

  1. # cmd.py
  2. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  3. #
  4. # This module is part of GitPython and is released under
  5. # the BSD License: http://www.opensource.org/licenses/bsd-license.php
  6. from contextlib import contextmanager
  7. import io
  8. import logging
  9. import os
  10. import signal
  11. from subprocess import (
  12. call,
  13. Popen,
  14. PIPE
  15. )
  16. import subprocess
  17. import sys
  18. import threading
  19. from collections import OrderedDict
  20. from textwrap import dedent
  21. from git.compat import (
  22. string_types,
  23. defenc,
  24. force_bytes,
  25. PY3,
  26. # just to satisfy flake8 on py3
  27. unicode,
  28. safe_decode,
  29. is_posix,
  30. is_win,
  31. )
  32. from git.exc import CommandError
  33. from git.util import is_cygwin_git, cygpath, expand_path
  34. from .exc import (
  35. GitCommandError,
  36. GitCommandNotFound
  37. )
  38. from .util import (
  39. LazyMixin,
  40. stream_copy,
  41. )
  42. try:
  43. PermissionError
  44. except NameError: # Python < 3.3
  45. PermissionError = OSError
  46. execute_kwargs = {'istream', 'with_extended_output',
  47. 'with_exceptions', 'as_process', 'stdout_as_string',
  48. 'output_stream', 'with_stdout', 'kill_after_timeout',
  49. 'universal_newlines', 'shell', 'env', 'max_chunk_size'}
  50. log = logging.getLogger(__name__)
  51. log.addHandler(logging.NullHandler())
  52. __all__ = ('Git',)
  53. # ==============================================================================
  54. ## @name Utilities
  55. # ------------------------------------------------------------------------------
  56. # Documentation
  57. ## @{
  58. def handle_process_output(process, stdout_handler, stderr_handler,
  59. finalizer=None, decode_streams=True):
  60. """Registers for notifications to lean that process output is ready to read, and dispatches lines to
  61. the respective line handlers.
  62. This function returns once the finalizer returns
  63. :return: result of finalizer
  64. :param process: subprocess.Popen instance
  65. :param stdout_handler: f(stdout_line_string), or None
  66. :param stderr_handler: f(stderr_line_string), or None
  67. :param finalizer: f(proc) - wait for proc to finish
  68. :param decode_streams:
  69. Assume stdout/stderr streams are binary and decode them before pushing \
  70. their contents to handlers.
  71. Set it to False if `universal_newline == True` (then streams are in text-mode)
  72. or if decoding must happen later (i.e. for Diffs).
  73. """
  74. # Use 2 "pump" threads and wait for both to finish.
  75. def pump_stream(cmdline, name, stream, is_decode, handler):
  76. try:
  77. for line in stream:
  78. if handler:
  79. if is_decode:
  80. line = line.decode(defenc)
  81. handler(line)
  82. except Exception as ex:
  83. log.error("Pumping %r of cmd(%s) failed due to: %r", name, cmdline, ex)
  84. raise CommandError(['<%s-pump>' % name] + cmdline, ex)
  85. finally:
  86. stream.close()
  87. cmdline = getattr(process, 'args', '') # PY3+ only
  88. if not isinstance(cmdline, (tuple, list)):
  89. cmdline = cmdline.split()
  90. pumps = []
  91. if process.stdout:
  92. pumps.append(('stdout', process.stdout, stdout_handler))
  93. if process.stderr:
  94. pumps.append(('stderr', process.stderr, stderr_handler))
  95. threads = []
  96. for name, stream, handler in pumps:
  97. t = threading.Thread(target=pump_stream,
  98. args=(cmdline, name, stream, decode_streams, handler))
  99. t.setDaemon(True)
  100. t.start()
  101. threads.append(t)
  102. ## FIXME: Why Join?? Will block if `stdin` needs feeding...
  103. #
  104. for t in threads:
  105. t.join()
  106. if finalizer:
  107. return finalizer(process)
  108. def dashify(string):
  109. return string.replace('_', '-')
  110. def slots_to_dict(self, exclude=()):
  111. return {s: getattr(self, s) for s in self.__slots__ if s not in exclude}
  112. def dict_to_slots_and__excluded_are_none(self, d, excluded=()):
  113. for k, v in d.items():
  114. setattr(self, k, v)
  115. for k in excluded:
  116. setattr(self, k, None)
  117. ## -- End Utilities -- @}
  118. # value of Windows process creation flag taken from MSDN
  119. CREATE_NO_WINDOW = 0x08000000
  120. ## CREATE_NEW_PROCESS_GROUP is needed to allow killing it afterwards,
  121. # see https://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal
  122. PROC_CREATIONFLAGS = (CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
  123. if is_win else 0)
  124. class Git(LazyMixin):
  125. """
  126. The Git class manages communication with the Git binary.
  127. It provides a convenient interface to calling the Git binary, such as in::
  128. g = Git( git_dir )
  129. g.init() # calls 'git init' program
  130. rval = g.ls_files() # calls 'git ls-files' program
  131. ``Debugging``
  132. Set the GIT_PYTHON_TRACE environment variable print each invocation
  133. of the command to stdout.
  134. Set its value to 'full' to see details about the returned values.
  135. """
  136. __slots__ = ("_working_dir", "cat_file_all", "cat_file_header", "_version_info",
  137. "_git_options", "_persistent_git_options", "_environment")
  138. _excluded_ = ('cat_file_all', 'cat_file_header', '_version_info')
  139. def __getstate__(self):
  140. return slots_to_dict(self, exclude=self._excluded_)
  141. def __setstate__(self, d):
  142. dict_to_slots_and__excluded_are_none(self, d, excluded=self._excluded_)
  143. # CONFIGURATION
  144. git_exec_name = "git" # default that should work on linux and windows
  145. # Enables debugging of GitPython's git commands
  146. GIT_PYTHON_TRACE = os.environ.get("GIT_PYTHON_TRACE", False)
  147. # If True, a shell will be used when executing git commands.
  148. # This should only be desirable on Windows, see https://github.com/gitpython-developers/GitPython/pull/126
  149. # and check `git/test_repo.py:TestRepo.test_untracked_files()` TC for an example where it is required.
  150. # Override this value using `Git.USE_SHELL = True`
  151. USE_SHELL = False
  152. # Provide the full path to the git executable. Otherwise it assumes git is in the path
  153. _git_exec_env_var = "GIT_PYTHON_GIT_EXECUTABLE"
  154. _refresh_env_var = "GIT_PYTHON_REFRESH"
  155. GIT_PYTHON_GIT_EXECUTABLE = None
  156. # note that the git executable is actually found during the refresh step in
  157. # the top level __init__
  158. @classmethod
  159. def refresh(cls, path=None):
  160. """This gets called by the refresh function (see the top level
  161. __init__).
  162. """
  163. # discern which path to refresh with
  164. if path is not None:
  165. new_git = os.path.expanduser(path)
  166. new_git = os.path.abspath(new_git)
  167. else:
  168. new_git = os.environ.get(cls._git_exec_env_var, cls.git_exec_name)
  169. # keep track of the old and new git executable path
  170. old_git = cls.GIT_PYTHON_GIT_EXECUTABLE
  171. cls.GIT_PYTHON_GIT_EXECUTABLE = new_git
  172. # test if the new git executable path is valid
  173. # - a GitCommandNotFound error is spawned by ourselves
  174. # - a PermissionError is spawned if the git executable provided
  175. # cannot be executed for whatever reason
  176. has_git = False
  177. try:
  178. cls().version()
  179. has_git = True
  180. except (GitCommandNotFound, PermissionError):
  181. pass
  182. # warn or raise exception if test failed
  183. if not has_git:
  184. err = dedent("""\
  185. Bad git executable.
  186. The git executable must be specified in one of the following ways:
  187. - be included in your $PATH
  188. - be set via $%s
  189. - explicitly set via git.refresh()
  190. """) % cls._git_exec_env_var
  191. # revert to whatever the old_git was
  192. cls.GIT_PYTHON_GIT_EXECUTABLE = old_git
  193. if old_git is None:
  194. # on the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is
  195. # None) we only are quiet, warn, or error depending on the
  196. # GIT_PYTHON_REFRESH value
  197. # determine what the user wants to happen during the initial
  198. # refresh we expect GIT_PYTHON_REFRESH to either be unset or
  199. # be one of the following values:
  200. # 0|q|quiet|s|silence
  201. # 1|w|warn|warning
  202. # 2|r|raise|e|error
  203. mode = os.environ.get(cls._refresh_env_var, "raise").lower()
  204. quiet = ["quiet", "q", "silence", "s", "none", "n", "0"]
  205. warn = ["warn", "w", "warning", "1"]
  206. error = ["error", "e", "raise", "r", "2"]
  207. if mode in quiet:
  208. pass
  209. elif mode in warn or mode in error:
  210. err = dedent("""\
  211. %s
  212. All git commands will error until this is rectified.
  213. This initial warning can be silenced or aggravated in the future by setting the
  214. $%s environment variable. Use one of the following values:
  215. - %s: for no warning or exception
  216. - %s: for a printed warning
  217. - %s: for a raised exception
  218. Example:
  219. export %s=%s
  220. """) % (
  221. err,
  222. cls._refresh_env_var,
  223. "|".join(quiet),
  224. "|".join(warn),
  225. "|".join(error),
  226. cls._refresh_env_var,
  227. quiet[0])
  228. if mode in warn:
  229. print("WARNING: %s" % err)
  230. else:
  231. raise ImportError(err)
  232. else:
  233. err = dedent("""\
  234. %s environment variable has been set but it has been set with an invalid value.
  235. Use only the following values:
  236. - %s: for no warning or exception
  237. - %s: for a printed warning
  238. - %s: for a raised exception
  239. """) % (
  240. cls._refresh_env_var,
  241. "|".join(quiet),
  242. "|".join(warn),
  243. "|".join(error))
  244. raise ImportError(err)
  245. # we get here if this was the init refresh and the refresh mode
  246. # was not error, go ahead and set the GIT_PYTHON_GIT_EXECUTABLE
  247. # such that we discern the difference between a first import
  248. # and a second import
  249. cls.GIT_PYTHON_GIT_EXECUTABLE = cls.git_exec_name
  250. else:
  251. # after the first refresh (when GIT_PYTHON_GIT_EXECUTABLE
  252. # is no longer None) we raise an exception
  253. raise GitCommandNotFound("git", err)
  254. return has_git
  255. @classmethod
  256. def is_cygwin(cls):
  257. return is_cygwin_git(cls.GIT_PYTHON_GIT_EXECUTABLE)
  258. @classmethod
  259. def polish_url(cls, url, is_cygwin=None):
  260. if is_cygwin is None:
  261. is_cygwin = cls.is_cygwin()
  262. if is_cygwin:
  263. url = cygpath(url)
  264. else:
  265. """Remove any backslahes from urls to be written in config files.
  266. Windows might create config-files containing paths with backslashed,
  267. but git stops liking them as it will escape the backslashes.
  268. Hence we undo the escaping just to be sure.
  269. """
  270. url = url.replace("\\\\", "\\").replace("\\", "/")
  271. return url
  272. class AutoInterrupt(object):
  273. """Kill/Interrupt the stored process instance once this instance goes out of scope. It is
  274. used to prevent processes piling up in case iterators stop reading.
  275. Besides all attributes are wired through to the contained process object.
  276. The wait method was overridden to perform automatic status code checking
  277. and possibly raise."""
  278. __slots__ = ("proc", "args")
  279. def __init__(self, proc, args):
  280. self.proc = proc
  281. self.args = args
  282. def __del__(self):
  283. if self.proc is None:
  284. return
  285. proc = self.proc
  286. self.proc = None
  287. if proc.stdin:
  288. proc.stdin.close()
  289. if proc.stdout:
  290. proc.stdout.close()
  291. if proc.stderr:
  292. proc.stderr.close()
  293. # did the process finish already so we have a return code ?
  294. if proc.poll() is not None:
  295. return
  296. # can be that nothing really exists anymore ...
  297. if os is None or getattr(os, 'kill', None) is None:
  298. return
  299. # try to kill it
  300. try:
  301. proc.terminate()
  302. proc.wait() # ensure process goes away
  303. except OSError as ex:
  304. log.info("Ignored error after process had died: %r", ex)
  305. pass # ignore error when process already died
  306. except AttributeError:
  307. # try windows
  308. # for some reason, providing None for stdout/stderr still prints something. This is why
  309. # we simply use the shell and redirect to nul. Its slower than CreateProcess, question
  310. # is whether we really want to see all these messages. Its annoying no matter what.
  311. if is_win:
  312. call(("TASKKILL /F /T /PID %s 2>nul 1>nul" % str(proc.pid)), shell=True)
  313. # END exception handling
  314. def __getattr__(self, attr):
  315. return getattr(self.proc, attr)
  316. def wait(self, stderr=b''): # TODO: Bad choice to mimic `proc.wait()` but with different args.
  317. """Wait for the process and return its status code.
  318. :param stderr: Previously read value of stderr, in case stderr is already closed.
  319. :warn: may deadlock if output or error pipes are used and not handled separately.
  320. :raise GitCommandError: if the return status is not 0"""
  321. if stderr is None:
  322. stderr = b''
  323. stderr = force_bytes(stderr)
  324. status = self.proc.wait()
  325. def read_all_from_possibly_closed_stream(stream):
  326. try:
  327. return stderr + force_bytes(stream.read())
  328. except ValueError:
  329. return stderr or b''
  330. if status != 0:
  331. errstr = read_all_from_possibly_closed_stream(self.proc.stderr)
  332. log.debug('AutoInterrupt wait stderr: %r' % (errstr,))
  333. raise GitCommandError(self.args, status, errstr)
  334. # END status handling
  335. return status
  336. # END auto interrupt
  337. class CatFileContentStream(object):
  338. """Object representing a sized read-only stream returning the contents of
  339. an object.
  340. It behaves like a stream, but counts the data read and simulates an empty
  341. stream once our sized content region is empty.
  342. If not all data is read to the end of the objects's lifetime, we read the
  343. rest to assure the underlying stream continues to work"""
  344. __slots__ = ('_stream', '_nbr', '_size')
  345. def __init__(self, size, stream):
  346. self._stream = stream
  347. self._size = size
  348. self._nbr = 0 # num bytes read
  349. # special case: if the object is empty, has null bytes, get the
  350. # final newline right away.
  351. if size == 0:
  352. stream.read(1)
  353. # END handle empty streams
  354. def read(self, size=-1):
  355. bytes_left = self._size - self._nbr
  356. if bytes_left == 0:
  357. return b''
  358. if size > -1:
  359. # assure we don't try to read past our limit
  360. size = min(bytes_left, size)
  361. else:
  362. # they try to read all, make sure its not more than what remains
  363. size = bytes_left
  364. # END check early depletion
  365. data = self._stream.read(size)
  366. self._nbr += len(data)
  367. # check for depletion, read our final byte to make the stream usable by others
  368. if self._size - self._nbr == 0:
  369. self._stream.read(1) # final newline
  370. # END finish reading
  371. return data
  372. def readline(self, size=-1):
  373. if self._nbr == self._size:
  374. return b''
  375. # clamp size to lowest allowed value
  376. bytes_left = self._size - self._nbr
  377. if size > -1:
  378. size = min(bytes_left, size)
  379. else:
  380. size = bytes_left
  381. # END handle size
  382. data = self._stream.readline(size)
  383. self._nbr += len(data)
  384. # handle final byte
  385. if self._size - self._nbr == 0:
  386. self._stream.read(1)
  387. # END finish reading
  388. return data
  389. def readlines(self, size=-1):
  390. if self._nbr == self._size:
  391. return []
  392. # leave all additional logic to our readline method, we just check the size
  393. out = []
  394. nbr = 0
  395. while True:
  396. line = self.readline()
  397. if not line:
  398. break
  399. out.append(line)
  400. if size > -1:
  401. nbr += len(line)
  402. if nbr > size:
  403. break
  404. # END handle size constraint
  405. # END readline loop
  406. return out
  407. def __iter__(self):
  408. return self
  409. def next(self):
  410. line = self.readline()
  411. if not line:
  412. raise StopIteration
  413. return line
  414. def __del__(self):
  415. bytes_left = self._size - self._nbr
  416. if bytes_left:
  417. # read and discard - seeking is impossible within a stream
  418. # includes terminating newline
  419. self._stream.read(bytes_left + 1)
  420. # END handle incomplete read
  421. def __init__(self, working_dir=None):
  422. """Initialize this instance with:
  423. :param working_dir:
  424. Git directory we should work in. If None, we always work in the current
  425. directory as returned by os.getcwd().
  426. It is meant to be the working tree directory if available, or the
  427. .git directory in case of bare repositories."""
  428. super(Git, self).__init__()
  429. self._working_dir = expand_path(working_dir)
  430. self._git_options = ()
  431. self._persistent_git_options = []
  432. # Extra environment variables to pass to git commands
  433. self._environment = {}
  434. # cached command slots
  435. self.cat_file_header = None
  436. self.cat_file_all = None
  437. def __getattr__(self, name):
  438. """A convenience method as it allows to call the command as if it was
  439. an object.
  440. :return: Callable object that will execute call _call_process with your arguments."""
  441. if name[0] == '_':
  442. return LazyMixin.__getattr__(self, name)
  443. return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
  444. def set_persistent_git_options(self, **kwargs):
  445. """Specify command line options to the git executable
  446. for subsequent subcommand calls
  447. :param kwargs:
  448. is a dict of keyword arguments.
  449. these arguments are passed as in _call_process
  450. but will be passed to the git command rather than
  451. the subcommand.
  452. """
  453. self._persistent_git_options = self.transform_kwargs(
  454. split_single_char_options=True, **kwargs)
  455. def _set_cache_(self, attr):
  456. if attr == '_version_info':
  457. # We only use the first 4 numbers, as everything else could be strings in fact (on windows)
  458. version_numbers = self._call_process('version').split(' ')[2]
  459. self._version_info = tuple(int(n) for n in version_numbers.split('.')[:4] if n.isdigit())
  460. else:
  461. super(Git, self)._set_cache_(attr)
  462. # END handle version info
  463. @property
  464. def working_dir(self):
  465. """:return: Git directory we are working on"""
  466. return self._working_dir
  467. @property
  468. def version_info(self):
  469. """
  470. :return: tuple(int, int, int, int) tuple with integers representing the major, minor
  471. and additional version numbers as parsed from git version.
  472. This value is generated on demand and is cached"""
  473. return self._version_info
  474. def execute(self, command,
  475. istream=None,
  476. with_extended_output=False,
  477. with_exceptions=True,
  478. as_process=False,
  479. output_stream=None,
  480. stdout_as_string=True,
  481. kill_after_timeout=None,
  482. with_stdout=True,
  483. universal_newlines=False,
  484. shell=None,
  485. env=None,
  486. max_chunk_size=io.DEFAULT_BUFFER_SIZE,
  487. **subprocess_kwargs
  488. ):
  489. """Handles executing the command on the shell and consumes and returns
  490. the returned information (stdout)
  491. :param command:
  492. The command argument list to execute.
  493. It should be a string, or a sequence of program arguments. The
  494. program to execute is the first item in the args sequence or string.
  495. :param istream:
  496. Standard input filehandle passed to subprocess.Popen.
  497. :param with_extended_output:
  498. Whether to return a (status, stdout, stderr) tuple.
  499. :param with_exceptions:
  500. Whether to raise an exception when git returns a non-zero status.
  501. :param as_process:
  502. Whether to return the created process instance directly from which
  503. streams can be read on demand. This will render with_extended_output and
  504. with_exceptions ineffective - the caller will have
  505. to deal with the details himself.
  506. It is important to note that the process will be placed into an AutoInterrupt
  507. wrapper that will interrupt the process once it goes out of scope. If you
  508. use the command in iterators, you should pass the whole process instance
  509. instead of a single stream.
  510. :param output_stream:
  511. If set to a file-like object, data produced by the git command will be
  512. output to the given stream directly.
  513. This feature only has any effect if as_process is False. Processes will
  514. always be created with a pipe due to issues with subprocess.
  515. This merely is a workaround as data will be copied from the
  516. output pipe to the given output stream directly.
  517. Judging from the implementation, you shouldn't use this flag !
  518. :param stdout_as_string:
  519. if False, the commands standard output will be bytes. Otherwise, it will be
  520. decoded into a string using the default encoding (usually utf-8).
  521. The latter can fail, if the output contains binary data.
  522. :param env:
  523. A dictionary of environment variables to be passed to `subprocess.Popen`.
  524. :param max_chunk_size:
  525. Maximum number of bytes in one chunk of data passed to the output_stream in
  526. one invocation of write() method. If the given number is not positive then
  527. the default value is used.
  528. :param subprocess_kwargs:
  529. Keyword arguments to be passed to subprocess.Popen. Please note that
  530. some of the valid kwargs are already set by this method, the ones you
  531. specify may not be the same ones.
  532. :param with_stdout: If True, default True, we open stdout on the created process
  533. :param universal_newlines:
  534. if True, pipes will be opened as text, and lines are split at
  535. all known line endings.
  536. :param shell:
  537. Whether to invoke commands through a shell (see `Popen(..., shell=True)`).
  538. It overrides :attr:`USE_SHELL` if it is not `None`.
  539. :param kill_after_timeout:
  540. To specify a timeout in seconds for the git command, after which the process
  541. should be killed. This will have no effect if as_process is set to True. It is
  542. set to None by default and will let the process run until the timeout is
  543. explicitly specified. This feature is not supported on Windows. It's also worth
  544. noting that kill_after_timeout uses SIGKILL, which can have negative side
  545. effects on a repository. For example, stale locks in case of git gc could
  546. render the repository incapable of accepting changes until the lock is manually
  547. removed.
  548. :return:
  549. * str(output) if extended_output = False (Default)
  550. * tuple(int(status), str(stdout), str(stderr)) if extended_output = True
  551. if output_stream is True, the stdout value will be your output stream:
  552. * output_stream if extended_output = False
  553. * tuple(int(status), output_stream, str(stderr)) if extended_output = True
  554. Note git is executed with LC_MESSAGES="C" to ensure consistent
  555. output regardless of system language.
  556. :raise GitCommandError:
  557. :note:
  558. If you add additional keyword arguments to the signature of this method,
  559. you must update the execute_kwargs tuple housed in this module."""
  560. if self.GIT_PYTHON_TRACE and (self.GIT_PYTHON_TRACE != 'full' or as_process):
  561. log.info(' '.join(command))
  562. # Allow the user to have the command executed in their working dir.
  563. cwd = self._working_dir or os.getcwd()
  564. # Start the process
  565. inline_env = env
  566. env = os.environ.copy()
  567. # Attempt to force all output to plain ascii english, which is what some parsing code
  568. # may expect.
  569. # According to stackoverflow (http://goo.gl/l74GC8), we are setting LANGUAGE as well
  570. # just to be sure.
  571. env["LANGUAGE"] = "C"
  572. env["LC_ALL"] = "C"
  573. env.update(self._environment)
  574. if inline_env is not None:
  575. env.update(inline_env)
  576. if is_win:
  577. cmd_not_found_exception = OSError
  578. if kill_after_timeout:
  579. raise GitCommandError(command, '"kill_after_timeout" feature is not supported on Windows.')
  580. else:
  581. if sys.version_info[0] > 2:
  582. cmd_not_found_exception = FileNotFoundError # NOQA # exists, flake8 unknown @UndefinedVariable
  583. else:
  584. cmd_not_found_exception = OSError
  585. # end handle
  586. stdout_sink = (PIPE
  587. if with_stdout
  588. else getattr(subprocess, 'DEVNULL', None) or open(os.devnull, 'wb'))
  589. istream_ok = "None"
  590. if istream:
  591. istream_ok = "<valid stream>"
  592. log.debug("Popen(%s, cwd=%s, universal_newlines=%s, shell=%s, istream=%s)",
  593. command, cwd, universal_newlines, shell, istream_ok)
  594. try:
  595. proc = Popen(command,
  596. env=env,
  597. cwd=cwd,
  598. bufsize=-1,
  599. stdin=istream,
  600. stderr=PIPE,
  601. stdout=stdout_sink,
  602. shell=shell is not None and shell or self.USE_SHELL,
  603. close_fds=is_posix, # unsupported on windows
  604. universal_newlines=universal_newlines,
  605. creationflags=PROC_CREATIONFLAGS,
  606. **subprocess_kwargs
  607. )
  608. except cmd_not_found_exception as err:
  609. raise GitCommandNotFound(command, err)
  610. if as_process:
  611. return self.AutoInterrupt(proc, command)
  612. def _kill_process(pid):
  613. """ Callback method to kill a process. """
  614. p = Popen(['ps', '--ppid', str(pid)], stdout=PIPE,
  615. creationflags=PROC_CREATIONFLAGS)
  616. child_pids = []
  617. for line in p.stdout:
  618. if len(line.split()) > 0:
  619. local_pid = (line.split())[0]
  620. if local_pid.isdigit():
  621. child_pids.append(int(local_pid))
  622. try:
  623. # Windows does not have SIGKILL, so use SIGTERM instead
  624. sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
  625. os.kill(pid, sig)
  626. for child_pid in child_pids:
  627. try:
  628. os.kill(child_pid, sig)
  629. except OSError:
  630. pass
  631. kill_check.set() # tell the main routine that the process was killed
  632. except OSError:
  633. # It is possible that the process gets completed in the duration after timeout
  634. # happens and before we try to kill the process.
  635. pass
  636. return
  637. # end
  638. if kill_after_timeout:
  639. kill_check = threading.Event()
  640. watchdog = threading.Timer(kill_after_timeout, _kill_process, args=(proc.pid,))
  641. # Wait for the process to return
  642. status = 0
  643. stdout_value = b''
  644. stderr_value = b''
  645. try:
  646. if output_stream is None:
  647. if kill_after_timeout:
  648. watchdog.start()
  649. stdout_value, stderr_value = proc.communicate()
  650. if kill_after_timeout:
  651. watchdog.cancel()
  652. if kill_check.isSet():
  653. stderr_value = ('Timeout: the command "%s" did not complete in %d '
  654. 'secs.' % (" ".join(command), kill_after_timeout)).encode(defenc)
  655. # strip trailing "\n"
  656. if stdout_value.endswith(b"\n"):
  657. stdout_value = stdout_value[:-1]
  658. if stderr_value.endswith(b"\n"):
  659. stderr_value = stderr_value[:-1]
  660. status = proc.returncode
  661. else:
  662. max_chunk_size = max_chunk_size if max_chunk_size and max_chunk_size > 0 else io.DEFAULT_BUFFER_SIZE
  663. stream_copy(proc.stdout, output_stream, max_chunk_size)
  664. stdout_value = proc.stdout.read()
  665. stderr_value = proc.stderr.read()
  666. # strip trailing "\n"
  667. if stderr_value.endswith(b"\n"):
  668. stderr_value = stderr_value[:-1]
  669. status = proc.wait()
  670. # END stdout handling
  671. finally:
  672. proc.stdout.close()
  673. proc.stderr.close()
  674. if self.GIT_PYTHON_TRACE == 'full':
  675. cmdstr = " ".join(command)
  676. def as_text(stdout_value):
  677. return not output_stream and safe_decode(stdout_value) or '<OUTPUT_STREAM>'
  678. # end
  679. if stderr_value:
  680. log.info("%s -> %d; stdout: '%s'; stderr: '%s'",
  681. cmdstr, status, as_text(stdout_value), safe_decode(stderr_value))
  682. elif stdout_value:
  683. log.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value))
  684. else:
  685. log.info("%s -> %d", cmdstr, status)
  686. # END handle debug printing
  687. if with_exceptions and status != 0:
  688. raise GitCommandError(command, status, stderr_value, stdout_value)
  689. if isinstance(stdout_value, bytes) and stdout_as_string: # could also be output_stream
  690. stdout_value = safe_decode(stdout_value)
  691. # Allow access to the command's status code
  692. if with_extended_output:
  693. return (status, stdout_value, safe_decode(stderr_value))
  694. else:
  695. return stdout_value
  696. def environment(self):
  697. return self._environment
  698. def update_environment(self, **kwargs):
  699. """
  700. Set environment variables for future git invocations. Return all changed
  701. values in a format that can be passed back into this function to revert
  702. the changes:
  703. ``Examples``::
  704. old_env = self.update_environment(PWD='/tmp')
  705. self.update_environment(**old_env)
  706. :param kwargs: environment variables to use for git processes
  707. :return: dict that maps environment variables to their old values
  708. """
  709. old_env = {}
  710. for key, value in kwargs.items():
  711. # set value if it is None
  712. if value is not None:
  713. old_env[key] = self._environment.get(key)
  714. self._environment[key] = value
  715. # remove key from environment if its value is None
  716. elif key in self._environment:
  717. old_env[key] = self._environment[key]
  718. del self._environment[key]
  719. return old_env
  720. @contextmanager
  721. def custom_environment(self, **kwargs):
  722. """
  723. A context manager around the above ``update_environment`` method to restore the
  724. environment back to its previous state after operation.
  725. ``Examples``::
  726. with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'):
  727. repo.remotes.origin.fetch()
  728. :param kwargs: see update_environment
  729. """
  730. old_env = self.update_environment(**kwargs)
  731. try:
  732. yield
  733. finally:
  734. self.update_environment(**old_env)
  735. def transform_kwarg(self, name, value, split_single_char_options):
  736. if len(name) == 1:
  737. if value is True:
  738. return ["-%s" % name]
  739. elif value not in (False, None):
  740. if split_single_char_options:
  741. return ["-%s" % name, "%s" % value]
  742. else:
  743. return ["-%s%s" % (name, value)]
  744. else:
  745. if value is True:
  746. return ["--%s" % dashify(name)]
  747. elif value is not False and value is not None:
  748. return ["--%s=%s" % (dashify(name), value)]
  749. return []
  750. def transform_kwargs(self, split_single_char_options=True, **kwargs):
  751. """Transforms Python style kwargs into git command line options."""
  752. args = []
  753. kwargs = OrderedDict(sorted(kwargs.items(), key=lambda x: x[0]))
  754. for k, v in kwargs.items():
  755. if isinstance(v, (list, tuple)):
  756. for value in v:
  757. args += self.transform_kwarg(k, value, split_single_char_options)
  758. else:
  759. args += self.transform_kwarg(k, v, split_single_char_options)
  760. return args
  761. @classmethod
  762. def __unpack_args(cls, arg_list):
  763. if not isinstance(arg_list, (list, tuple)):
  764. # This is just required for unicode conversion, as subprocess can't handle it
  765. # However, in any other case, passing strings (usually utf-8 encoded) is totally fine
  766. if not PY3 and isinstance(arg_list, unicode):
  767. return [arg_list.encode(defenc)]
  768. return [str(arg_list)]
  769. outlist = []
  770. for arg in arg_list:
  771. if isinstance(arg_list, (list, tuple)):
  772. outlist.extend(cls.__unpack_args(arg))
  773. elif not PY3 and isinstance(arg_list, unicode):
  774. outlist.append(arg_list.encode(defenc))
  775. # END recursion
  776. else:
  777. outlist.append(str(arg))
  778. # END for each arg
  779. return outlist
  780. def __call__(self, **kwargs):
  781. """Specify command line options to the git executable
  782. for a subcommand call
  783. :param kwargs:
  784. is a dict of keyword arguments.
  785. these arguments are passed as in _call_process
  786. but will be passed to the git command rather than
  787. the subcommand.
  788. ``Examples``::
  789. git(work_tree='/tmp').difftool()"""
  790. self._git_options = self.transform_kwargs(
  791. split_single_char_options=True, **kwargs)
  792. return self
  793. def _call_process(self, method, *args, **kwargs):
  794. """Run the given git command with the specified arguments and return
  795. the result as a String
  796. :param method:
  797. is the command. Contained "_" characters will be converted to dashes,
  798. such as in 'ls_files' to call 'ls-files'.
  799. :param args:
  800. is the list of arguments. If None is included, it will be pruned.
  801. This allows your commands to call git more conveniently as None
  802. is realized as non-existent
  803. :param kwargs:
  804. It contains key-values for the following:
  805. - the :meth:`execute()` kwds, as listed in :var:`execute_kwargs`;
  806. - "command options" to be converted by :meth:`transform_kwargs()`;
  807. - the `'insert_kwargs_after'` key which its value must match one of ``*args``,
  808. and any cmd-options will be appended after the matched arg.
  809. Examples::
  810. git.rev_list('master', max_count=10, header=True)
  811. turns into::
  812. git rev-list max-count 10 --header master
  813. :return: Same as ``execute``"""
  814. # Handle optional arguments prior to calling transform_kwargs
  815. # otherwise these'll end up in args, which is bad.
  816. exec_kwargs = {k: v for k, v in kwargs.items() if k in execute_kwargs}
  817. opts_kwargs = {k: v for k, v in kwargs.items() if k not in execute_kwargs}
  818. insert_after_this_arg = opts_kwargs.pop('insert_kwargs_after', None)
  819. # Prepare the argument list
  820. opt_args = self.transform_kwargs(**opts_kwargs)
  821. ext_args = self.__unpack_args([a for a in args if a is not None])
  822. if insert_after_this_arg is None:
  823. args = opt_args + ext_args
  824. else:
  825. try:
  826. index = ext_args.index(insert_after_this_arg)
  827. except ValueError:
  828. raise ValueError("Couldn't find argument '%s' in args %s to insert cmd options after"
  829. % (insert_after_this_arg, str(ext_args)))
  830. # end handle error
  831. args = ext_args[:index + 1] + opt_args + ext_args[index + 1:]
  832. # end handle opts_kwargs
  833. call = [self.GIT_PYTHON_GIT_EXECUTABLE]
  834. # add persistent git options
  835. call.extend(self._persistent_git_options)
  836. # add the git options, then reset to empty
  837. # to avoid side_effects
  838. call.extend(self._git_options)
  839. self._git_options = ()
  840. call.append(dashify(method))
  841. call.extend(args)
  842. return self.execute(call, **exec_kwargs)
  843. def _parse_object_header(self, header_line):
  844. """
  845. :param header_line:
  846. <hex_sha> type_string size_as_int
  847. :return: (hex_sha, type_string, size_as_int)
  848. :raise ValueError: if the header contains indication for an error due to
  849. incorrect input sha"""
  850. tokens = header_line.split()
  851. if len(tokens) != 3:
  852. if not tokens:
  853. raise ValueError("SHA could not be resolved, git returned: %r" % (header_line.strip()))
  854. else:
  855. raise ValueError("SHA %s could not be resolved, git returned: %r" % (tokens[0], header_line.strip()))
  856. # END handle actual return value
  857. # END error handling
  858. if len(tokens[0]) != 40:
  859. raise ValueError("Failed to parse header: %r" % header_line)
  860. return (tokens[0], tokens[1], int(tokens[2]))
  861. def _prepare_ref(self, ref):
  862. # required for command to separate refs on stdin, as bytes
  863. refstr = ref
  864. if isinstance(ref, bytes):
  865. # Assume 40 bytes hexsha - bin-to-ascii for some reason returns bytes, not text
  866. refstr = ref.decode('ascii')
  867. elif not isinstance(ref, string_types):
  868. refstr = str(ref) # could be ref-object
  869. if not refstr.endswith("\n"):
  870. refstr += "\n"
  871. return refstr.encode(defenc)
  872. def _get_persistent_cmd(self, attr_name, cmd_name, *args, **kwargs):
  873. cur_val = getattr(self, attr_name)
  874. if cur_val is not None:
  875. return cur_val
  876. options = {"istream": PIPE, "as_process": True}
  877. options.update(kwargs)
  878. cmd = self._call_process(cmd_name, *args, **options)
  879. setattr(self, attr_name, cmd)
  880. return cmd
  881. def __get_object_header(self, cmd, ref):
  882. cmd.stdin.write(self._prepare_ref(ref))
  883. cmd.stdin.flush()
  884. return self._parse_object_header(cmd.stdout.readline())
  885. def get_object_header(self, ref):
  886. """ Use this method to quickly examine the type and size of the object behind
  887. the given ref.
  888. :note: The method will only suffer from the costs of command invocation
  889. once and reuses the command in subsequent calls.
  890. :return: (hexsha, type_string, size_as_int)"""
  891. cmd = self._get_persistent_cmd("cat_file_header", "cat_file", batch_check=True)
  892. return self.__get_object_header(cmd, ref)
  893. def get_object_data(self, ref):
  894. """ As get_object_header, but returns object data as well
  895. :return: (hexsha, type_string, size_as_int,data_string)
  896. :note: not threadsafe"""
  897. hexsha, typename, size, stream = self.stream_object_data(ref)
  898. data = stream.read(size)
  899. del(stream)
  900. return (hexsha, typename, size, data)
  901. def stream_object_data(self, ref):
  902. """ As get_object_header, but returns the data as a stream
  903. :return: (hexsha, type_string, size_as_int, stream)
  904. :note: This method is not threadsafe, you need one independent Command instance per thread to be safe !"""
  905. cmd = self._get_persistent_cmd("cat_file_all", "cat_file", batch=True)
  906. hexsha, typename, size = self.__get_object_header(cmd, ref)
  907. return (hexsha, typename, size, self.CatFileContentStream(size, cmd.stdout))
  908. def clear_cache(self):
  909. """Clear all kinds of internal caches to release resources.
  910. Currently persistent commands will be interrupted.
  911. :return: self"""
  912. for cmd in (self.cat_file_all, self.cat_file_header):
  913. if cmd:
  914. cmd.__del__()
  915. self.cat_file_all = None
  916. self.cat_file_header = None
  917. return self