pre-commit-hooks/pre_commit_hooks/util.py

33 lines
846 B
Python
Raw Normal View History

from __future__ import annotations
2015-03-21 04:52:21 +08:00
import subprocess
from typing import Any
2015-03-21 04:52:21 +08:00
class CalledProcessError(RuntimeError):
pass
2015-01-08 06:07:32 +08:00
def added_files() -> set[str]:
2020-02-04 00:41:48 +08:00
cmd = ('git', 'diff', '--staged', '--name-only', '--diff-filter=A')
return set(cmd_output(*cmd).splitlines())
2015-03-21 04:52:21 +08:00
def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str:
kwargs.setdefault('stdout', subprocess.PIPE)
kwargs.setdefault('stderr', subprocess.PIPE)
proc = subprocess.Popen(cmd, **kwargs)
2015-03-21 04:52:21 +08:00
stdout, stderr = proc.communicate()
2020-02-06 03:10:42 +08:00
stdout = stdout.decode()
2015-03-21 04:52:21 +08:00
if retcode is not None and proc.returncode != retcode:
raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)
return stdout
def zsplit(s: str) -> list[str]:
s = s.strip('\0')
if s:
return s.split('\0')
else:
return []