Anthony Sottile | 8f61529 | 2022-01-15 19:24:05 -0500 | [diff] [blame] | 1 | from __future__ import annotations |
| 2 | |
Anthony Sottile | 713fab4 | 2015-03-20 13:52:21 -0700 | [diff] [blame] | 3 | import subprocess |
Anthony Sottile | 030bfac | 2019-01-31 19:19:10 -0800 | [diff] [blame] | 4 | from typing import Any |
Anthony Sottile | 713fab4 | 2015-03-20 13:52:21 -0700 | [diff] [blame] | 5 | |
| 6 | |
| 7 | class CalledProcessError(RuntimeError): |
| 8 | pass |
gkisel | c682b50 | 2015-01-07 14:07:32 -0800 | [diff] [blame] | 9 | |
| 10 | |
Anthony Sottile | 8f61529 | 2022-01-15 19:24:05 -0500 | [diff] [blame] | 11 | def added_files() -> set[str]: |
Anthony Sottile | fea76b9 | 2020-02-03 08:41:48 -0800 | [diff] [blame] | 12 | cmd = ('git', 'diff', '--staged', '--name-only', '--diff-filter=A') |
| 13 | return set(cmd_output(*cmd).splitlines()) |
Anthony Sottile | 713fab4 | 2015-03-20 13:52:21 -0700 | [diff] [blame] | 14 | |
| 15 | |
Anthony Sottile | 8f61529 | 2022-01-15 19:24:05 -0500 | [diff] [blame] | 16 | def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: |
Anthony Sottile | 030bfac | 2019-01-31 19:19:10 -0800 | [diff] [blame] | 17 | kwargs.setdefault('stdout', subprocess.PIPE) |
| 18 | kwargs.setdefault('stderr', subprocess.PIPE) |
| 19 | proc = subprocess.Popen(cmd, **kwargs) |
Anthony Sottile | 713fab4 | 2015-03-20 13:52:21 -0700 | [diff] [blame] | 20 | stdout, stderr = proc.communicate() |
Anthony Sottile | f5c42a0 | 2020-02-05 11:10:42 -0800 | [diff] [blame] | 21 | stdout = stdout.decode() |
Anthony Sottile | 713fab4 | 2015-03-20 13:52:21 -0700 | [diff] [blame] | 22 | if retcode is not None and proc.returncode != retcode: |
| 23 | raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) |
| 24 | return stdout |
Mikhail Khvoinitsky | 1e87d59 | 2020-08-02 21:25:07 +0300 | [diff] [blame] | 25 | |
| 26 | |
Anthony Sottile | 8f61529 | 2022-01-15 19:24:05 -0500 | [diff] [blame] | 27 | def zsplit(s: str) -> list[str]: |
Mikhail Khvoinitsky | 1e87d59 | 2020-08-02 21:25:07 +0300 | [diff] [blame] | 28 | s = s.strip('\0') |
| 29 | if s: |
| 30 | return s.split('\0') |
| 31 | else: |
| 32 | return [] |