Merge pull request 'cmd.py part 3 refactor' (#706) from Qubasa-main into main

This commit is contained in:
clan-bot
2024-01-10 17:57:51 +00:00
5 changed files with 37 additions and 33 deletions

View File

@@ -54,6 +54,7 @@ def run(
env: dict[str, str] | None = None, env: dict[str, str] | None = None,
cwd: Path = Path.cwd(), cwd: Path = Path.cwd(),
log: Log = Log.STDERR, log: Log = Log.STDERR,
check: bool = True,
) -> CmdOut: ) -> CmdOut:
# Start the subprocess # Start the subprocess
process = subprocess.Popen( process = subprocess.Popen(
@@ -70,14 +71,14 @@ def run(
# Wait for the subprocess to finish # Wait for the subprocess to finish
rc = process.wait() rc = process.wait()
cmd_out = CmdOut( cmd_out = CmdOut(
stdout_buf, stdout=stdout_buf,
stderr_buf, stderr=stderr_buf,
cwd=cwd, cwd=cwd,
command=shlex.join(cmd), command=shlex.join(cmd),
returncode=process.returncode, returncode=process.returncode,
) )
if rc != 0: if check and rc != 0:
raise ClanCmdError(cmd_out) raise ClanCmdError(cmd_out)
return cmd_out return cmd_out

View File

@@ -1,10 +1,10 @@
import json import json
import os import os
import re import re
import subprocess
from pathlib import Path from pathlib import Path
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
from clan_cli.cmd import run
from clan_cli.dirs import machine_settings_file, nixpkgs_source, specific_machine_dir from clan_cli.dirs import machine_settings_file, nixpkgs_source, specific_machine_dir
from clan_cli.errors import ClanError, ClanHttpError from clan_cli.errors import ClanError, ClanHttpError
from clan_cli.git import commit_file from clan_cli.git import commit_file
@@ -60,11 +60,9 @@ def verify_machine_config(
""", """,
], ],
) )
# repro_env_break(work_dir=flake, env=env, cmd=cmd)
proc = subprocess.run( proc = run(
cmd, cmd,
capture_output=True,
text=True,
cwd=flake, cwd=flake,
env=env, env=env,
) )

View File

@@ -9,6 +9,18 @@ class CmdOut(NamedTuple):
command: str command: str
returncode: int returncode: int
def __str__(self) -> str:
return f"""
Working Directory: '{self.cwd}'
Return Code: {self.returncode}
=================== Command ===================
{self.command}
=================== STDERR ===================
{self.stderr}
=================== STDOUT ===================
{self.stdout}
"""
class ClanError(Exception): class ClanError(Exception):
"""Base class for exceptions in this module.""" """Base class for exceptions in this module."""
@@ -32,3 +44,9 @@ class ClanCmdError(ClanError):
def __init__(self, cmd: CmdOut) -> None: def __init__(self, cmd: CmdOut) -> None:
self.cmd = cmd self.cmd = cmd
super().__init__() super().__init__()
def __str__(self) -> str:
return str(self.cmd)
def __repr__(self) -> str:
return f"ClanCmdError({self.cmd})"

View File

@@ -1,9 +1,8 @@
import argparse import argparse
import shlex
import subprocess
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from ..cmd import run
from ..dirs import specific_groot_dir from ..dirs import specific_groot_dir
from ..errors import ClanError from ..errors import ClanError
from ..machines.list import list_machines from ..machines.list import list_machines
@@ -26,18 +25,7 @@ class FlakeConfig:
def run_cmd(cmd: list[str]) -> str: def run_cmd(cmd: list[str]) -> str:
proc = subprocess.run(cmd, text=True, stdout=subprocess.PIPE) proc = run(cmd)
assert proc.stdout is not None
if proc.returncode != 0:
raise ClanError(
f"""
command: {shlex.join(cmd)}
exit code: {proc.returncode}
stdout:
{proc.stdout}
"""
)
return proc.stdout.strip() return proc.stdout.strip()

View File

@@ -1,11 +1,11 @@
import shlex
import subprocess
from pathlib import Path from pathlib import Path
# from clan_cli.dirs import find_git_repo_root # from clan_cli.dirs import find_git_repo_root
from clan_cli.errors import ClanError from clan_cli.errors import ClanCmdError, ClanError
from clan_cli.nix import nix_shell from clan_cli.nix import nix_shell
from .cmd import run
# generic vcs agnostic commit function # generic vcs agnostic commit function
def commit_file( def commit_file(
@@ -43,10 +43,10 @@ def _commit_file_to_git(repo_dir: Path, file_path: Path, commit_message: str) ->
) )
# add the file to the git index # add the file to the git index
try: try:
subprocess.run(cmd, check=True) run(cmd)
except subprocess.CalledProcessError as e: except ClanCmdError as e:
raise ClanError( raise ClanError(
f"Failed to add {file_path} to git repository {repo_dir}:\n{shlex.join(cmd)}\n exited with {e.returncode}" f"Failed to add {file_path} to git repository {repo_dir}:\n{e.cmd.command}\n exited with {e.cmd.returncode}"
) from e ) from e
# check if there is a diff # check if there is a diff
@@ -54,7 +54,7 @@ def _commit_file_to_git(repo_dir: Path, file_path: Path, commit_message: str) ->
["nixpkgs#git"], ["nixpkgs#git"],
["git", "-C", str(repo_dir), "diff", "--cached", "--exit-code", str(file_path)], ["git", "-C", str(repo_dir), "diff", "--cached", "--exit-code", str(file_path)],
) )
result = subprocess.run(cmd, cwd=repo_dir) result = run(cmd, check=False, cwd=repo_dir)
# if there is no diff, return # if there is no diff, return
if result.returncode == 0: if result.returncode == 0:
return return
@@ -73,11 +73,10 @@ def _commit_file_to_git(repo_dir: Path, file_path: Path, commit_message: str) ->
], ],
) )
try: try:
subprocess.run( run(
cmd, cmd,
check=True,
) )
except subprocess.CalledProcessError as e: except ClanCmdError as e:
raise ClanError( raise ClanError(
f"Failed to commit {file_path} to git repository {repo_dir}:\n{shlex.join(cmd)}\n exited with {e.returncode}" f"Failed to commit {file_path} to git repository {repo_dir}:\n{e.cmd.command}\n exited with {e.cmd.returncode}"
) from e ) from e