-
-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathcmd.py
More file actions
48 lines (37 loc) · 1.1 KB
/
cmd.py
File metadata and controls
48 lines (37 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from __future__ import annotations
import os
import subprocess
from typing import TYPE_CHECKING, NamedTuple
from charset_normalizer import from_bytes
from commitizen.exceptions import CharacterSetDecodeError
if TYPE_CHECKING:
from collections.abc import Mapping
class Command(NamedTuple):
out: str
err: str
stdout: bytes
stderr: bytes
return_code: int
def _try_decode(bytes_: bytes) -> str:
try:
return bytes_.decode("utf-8")
except UnicodeDecodeError:
pass
charset_match = from_bytes(bytes_).best()
if charset_match is None:
raise CharacterSetDecodeError()
try:
return bytes_.decode(charset_match.encoding)
except UnicodeDecodeError as e:
raise CharacterSetDecodeError() from e
def run(cmd: str, env: Mapping[str, str] | None = None) -> Command:
if env is not None:
env = {**os.environ, **env}
c = subprocess.run([cmd], shell=True, capture_output=True, env=env)
return Command(
_try_decode(c.stdout),
_try_decode(c.stderr),
c.stdout,
c.stderr,
c.returncode,
)