From 3dba422a6517130cf4a013864e32edd992f4f800 Mon Sep 17 00:00:00 2001 From: Yu-Ting Hsiung Date: Tue, 20 May 2025 00:06:03 +0800 Subject: [PATCH 1/2] refactor(git): extract _create_commit_cmd_string --- commitizen/git.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/commitizen/git.py b/commitizen/git.py index fa59e34d4..ab2866ac4 100644 --- a/commitizen/git.py +++ b/commitizen/git.py @@ -181,19 +181,22 @@ def commit( f.write(message.encode("utf-8")) f.close() - command = f'git commit {args} -F "{f.name}"' - - if committer_date and os.name == "nt": # pragma: no cover - # Using `cmd /v /c "{command}"` sets environment variables only for that command - command = f'cmd /v /c "set GIT_COMMITTER_DATE={committer_date}&& {command}"' - elif committer_date: - command = f"GIT_COMMITTER_DATE={committer_date} {command}" - + command = _create_commit_cmd_string(args, committer_date, f.name) c = cmd.run(command) os.unlink(f.name) return c +def _create_commit_cmd_string(args: str, committer_date: str | None, name: str) -> str: + command = f'git commit {args} -F "{name}"' + if not committer_date: + return command + if os.name != "nt": + return f"GIT_COMMITTER_DATE={committer_date} {command}" + # Using `cmd /v /c "{command}"` sets environment variables only for that command + return f'cmd /v /c "set GIT_COMMITTER_DATE={committer_date}&& {command}"' + + def get_commits( start: str | None = None, end: str = "HEAD", From 0842d377cfc66ce592af5534f7eb1b4448bd89be Mon Sep 17 00:00:00 2001 From: Yu-Ting Hsiung Date: Fri, 23 May 2025 16:24:05 +0800 Subject: [PATCH 2/2] test(test_git): mock os --- tests/test_git.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/test_git.py b/tests/test_git.py index de3130412..3fecaabaf 100644 --- a/tests/test_git.py +++ b/tests/test_git.py @@ -449,3 +449,27 @@ def test_git_commit_from_rev_and_commit(): assert commit.author == "John Doe" assert commit.author_email == "john@example.com" assert commit.parents == [] + + +@pytest.mark.parametrize( + "os_name,committer_date,expected_cmd", + [ + ( + "nt", + "2024-03-20", + 'cmd /v /c "set GIT_COMMITTER_DATE=2024-03-20&& git commit -F "temp.txt""', + ), + ( + "posix", + "2024-03-20", + 'GIT_COMMITTER_DATE=2024-03-20 git commit -F "temp.txt"', + ), + ("nt", None, 'git commit -F "temp.txt"'), + ("posix", None, 'git commit -F "temp.txt"'), + ], +) +def test_create_commit_cmd_string(mocker, os_name, committer_date, expected_cmd): + """Test the OS-specific behavior of _create_commit_cmd_string""" + mocker.patch("os.name", os_name) + result = git._create_commit_cmd_string("", committer_date, "temp.txt") + assert result == expected_cmd