| 166 | #------------------------------------------------------------------------------ |
| 167 | |
| 168 | class Cmd: |
| 169 | executable = None |
| 170 | |
| 171 | def __init__(self, executable): |
| 172 | self.executable = executable |
| 173 | |
| 174 | def _call(self, command, args, kw, repository=None, call=False): |
| 175 | cmd = [self.executable, command] + list(args) |
| 176 | cwd = None |
| 177 | |
| 178 | if repository is not None: |
| 179 | cwd = os.getcwd() |
| 180 | os.chdir(repository) |
| 181 | |
| 182 | try: |
| 183 | if call: |
| 184 | return subprocess.call(cmd, **kw) |
| 185 | else: |
| 186 | return subprocess.Popen(cmd, **kw) |
| 187 | finally: |
| 188 | if cwd is not None: |
| 189 | os.chdir(cwd) |
| 190 | |
| 191 | def __call__(self, command, *a, **kw): |
| 192 | ret = self._call(command, a, {}, call=True, **kw) |
| 193 | if ret != 0: |
| 194 | raise RuntimeError(f"{self.executable} failed") |
| 195 | |
| 196 | def pipe(self, command, *a, **kw): |
| 197 | stdin = kw.pop('stdin', None) |
| 198 | p = self._call(command, a, {"stdin": stdin, "stdout": subprocess.PIPE}, |
| 199 | call=False, **kw) |
| 200 | return p.stdout |
| 201 | |
| 202 | def read(self, command, *a, **kw): |
| 203 | p = self._call(command, a, {"stdout": subprocess.PIPE}, |
| 204 | call=False, **kw) |
| 205 | out, err = p.communicate() |
| 206 | if p.returncode != 0: |
| 207 | raise RuntimeError(f"{self.executable} failed") |
| 208 | return out |
| 209 | |
| 210 | def readlines(self, command, *a, **kw): |
| 211 | out = self.read(command, *a, **kw) |
| 212 | return out.rstrip("\n").split("\n") |
| 213 | |
| 214 | def test(self, command, *a, **kw): |
| 215 | ret = self._call(command, a, {"stdout": subprocess.PIPE, |
| 216 | "stderr": subprocess.PIPE}, |
| 217 | call=True, **kw) |
| 218 | return (ret == 0) |
| 219 | |
| 220 | |
| 221 | git = Cmd("git") |