Skip to content
  • Sponsor commitizen-tools/commitizen

  • Notifications You must be signed in to change notification settings
  • Fork 290

refactor(git): extract _create_commit_cmd_string, better test coverage #1442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 26, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions commitizen/git.py
Original file line number Diff line number Diff line change
@@ -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",
24 changes: 24 additions & 0 deletions tests/test_git.py
Original file line number Diff line number Diff line change
@@ -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