clan-cli: add git.commit_file() to auto commit files if inside a git

- commit only if inside a git repo
- commit only the specified file and nothing else
- auto-generate commit message if not specified
This commit is contained in:
DavHau
2023-09-21 14:07:54 +02:00
parent 8e157f891f
commit 6a359c0a2f
8 changed files with 131 additions and 5 deletions

View File

@@ -1,5 +1,11 @@
import os
import subprocess
import sys
from pathlib import Path
import pytest
from clan_cli.nix import nix_shell
sys.path.append(os.path.join(os.path.dirname(__file__), "helpers"))
@@ -14,3 +20,18 @@ pytest_plugins = [
"host_group",
"test_flake",
]
# fixture for git_repo
@pytest.fixture
def git_repo(tmp_path: Path) -> Path:
# initialize a git repository
cmd = nix_shell(["git"], ["git", "init"])
subprocess.run(cmd, cwd=tmp_path, check=True)
# set user.name and user.email
cmd = nix_shell(["git"], ["git", "config", "user.name", "test"])
subprocess.run(cmd, cwd=tmp_path, check=True)
cmd = nix_shell(["git"], ["git", "config", "user.email", "test@test.test"])
subprocess.run(cmd, cwd=tmp_path, check=True)
# return the path to the git repository
return tmp_path

View File

@@ -28,6 +28,7 @@ example_options = f"{Path(config.__file__).parent}/jsonschema/options.json"
def test_set_some_option(
args: list[str],
expected: dict[str, Any],
test_flake: Path,
) -> None:
# create temporary file for out_file
with tempfile.NamedTemporaryFile() as out_file:

View File

@@ -0,0 +1,40 @@
import subprocess
import tempfile
from pathlib import Path
import pytest
from clan_cli import git
from clan_cli.errors import ClanError
def test_commit_file(git_repo: Path) -> None:
# create a file in the git repo
(git_repo / "test.txt").touch()
# commit the file
git.commit_file((git_repo / "test.txt"), git_repo, "test commit")
# check that the repo directory does in fact contain the file
assert (git_repo / "test.txt").exists()
# check that the working tree is clean
assert not subprocess.check_output(["git", "status", "--porcelain"], cwd=git_repo)
# check that the latest commit message is correct
assert (
subprocess.check_output(
["git", "log", "-1", "--pretty=%B"], cwd=git_repo
).decode("utf-8")
== "test commit\n\n"
)
def test_commit_file_outside_git_raises_error(git_repo: Path) -> None:
# create a file outside the git (a temporary file)
with tempfile.NamedTemporaryFile() as tmp:
# commit the file
with pytest.raises(ClanError):
git.commit_file(Path(tmp.name), git_repo, "test commit")
def test_commit_file_not_existing_raises_error(git_repo: Path) -> None:
# commit a file that does not exist
with pytest.raises(ClanError):
git.commit_file(Path("test.txt"), git_repo, "test commit")