Debian Codegraph @

qa/shell.py

raw symbols SCIP
1 # This code is mostly duplicated from the `gitlint.shell` module. We consciously duplicate this code as to not depend
2 # on gitlint internals for our integration testing framework.
3
4 import subprocess
5
6 from qa.utils import TERMINAL_ENCODING, USE_SH_LIB
7
8 if USE_SH_LIB:
9 from sh import (
10 echo,
11 git,
12 gitlint,
13 )
14
15 gitlint = gitlint.bake(_unify_ttys=True, _tty_in=True)
16
17 # import exceptions separately, this makes it a little easier to mock them out in the unit tests
18 from sh import (
19 CommandNotFound,
20 ErrorReturnCode,
21 RunningCommand,
22 )
23 else:
24
25 class CommandNotFound(Exception):
26 """Exception indicating a command was not found during execution"""
27
28 class RunningCommand:
29 ...
30
31 class ShResult(RunningCommand):
32 """Result wrapper class. We use this to more easily migrate from using https://amoffat.github.io/sh/ to using
33 the builtin subprocess module."""
34
35 def __init__(self, full_cmd, stdout, stderr="", exitcode=0):
36 self.full_cmd = full_cmd
37 # TODO(jorisroovers): The 'sh' library by default will merge stdout and stderr. We mimic this behavior
38 # for now until we fully remove the 'sh' library.
39 self._stdout = stdout + stderr
40 self._stderr = stderr
41 self.exit_code = exitcode
42
43 def __str__(self):
44 return self.stdout.decode(TERMINAL_ENCODING)
45
46 def __unicode__(self):
47 return self.stdout
48
49 @property
50 def stdout(self):
51 return self._stdout
52
53 @property
54 def stderr(self):
55 return self._stderr
56
57 def __getattr__(self, p):
58 # https://github.com/amoffat/sh/blob/e0ed8e244e9d973ef4e0749b2b3c2695e7b5255b/sh.py#L952=
59 _unicode_methods = set(dir(str())) # noqa
60 if p in _unicode_methods:
61 return getattr(str(self), p)
62
63 raise AttributeError
64
65 class ErrorReturnCode(ShResult, Exception):
66 """ShResult subclass for unexpected results (acts as an exception)."""
67
68 def git(*command_parts, **kwargs):
69 return run_command("git", *command_parts, **kwargs)
70
71 def echo(*command_parts, **kwargs):
72 return run_command("echo", *command_parts, **kwargs)
73
74 def gitlint(*command_parts, **kwargs):
75 return run_command("gitlint", *command_parts, **kwargs)
76
77 def run_command(command, *args, **kwargs):
78 args = [command, *list(args)]
79 return _exec(*args, **kwargs)
80
81 def _exec(*args, **kwargs):
82 popen_kwargs = {
83 "stdout": subprocess.PIPE,
84 "stderr": subprocess.PIPE,
85 "stdin": subprocess.PIPE,
86 "shell": kwargs.get("_tty_out", False),
87 "cwd": kwargs.get("_cwd", None),
88 "env": kwargs.get("_env", None),
89 }
90
91 stdin_input = None
92 if len(args) > 1 and isinstance(args[1], ShResult):
93 stdin_input = args[1].stdout
94 # pop args[1] from the array and use it as stdin
95 args = list(args)
96 args.pop(1)
97 popen_kwargs["stdin"] = subprocess.PIPE
98
99 try:
100 with subprocess.Popen(args, **popen_kwargs) as p:
101 result = p.communicate(stdin_input)
102
103 except FileNotFoundError as exc:
104 raise CommandNotFound from exc
105
106 exit_code = p.returncode
107 stdout = result[0]
108 stderr = result[1] # 'sh' does not decode the stderr bytes to unicode
109 full_cmd = "" if args is None else " ".join(args)
110
111 # If not _ok_code is specified, then only a 0 exit code is allowed
112 ok_exit_codes = kwargs.get("_ok_code", [0])
113
114 if exit_code in ok_exit_codes:
115 return ShResult(full_cmd, stdout, stderr, exit_code)
116
117 # Unexpected error code => raise ErrorReturnCode
118 raise ErrorReturnCode(full_cmd, stdout, stderr, p.returncode)