From ef638716cb6e4d61dbf111d52aca6ce8b6a4a2d1 Mon Sep 17 00:00:00 2001 From: Jared Koontz Date: Mon, 31 Mar 2025 17:23:33 -0600 Subject: [PATCH] feat: make better error message if try-repo fails because there are no commits on the repo. --- pre_commit/git.py | 14 +++++++++++++- testing/fixtures.py | 7 ++++--- tests/commands/try_repo_test.py | 17 +++++++++++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/pre_commit/git.py b/pre_commit/git.py index 2f424f89..2dee8543 100644 --- a/pre_commit/git.py +++ b/pre_commit/git.py @@ -168,7 +168,19 @@ def get_changed_files(old: str, new: str) -> list[str]: def head_rev(remote: str) -> str: - _, out, _ = cmd_output('git', 'ls-remote', '--exit-code', remote, 'HEAD') + try: + _, out, _ = cmd_output( + 'git', 'ls-remote', '--exit-code', + remote, 'HEAD', + ) + except CalledProcessError as e: + if e.returncode == 2: + raise FatalError( + f'repo {remote} found but appears to have no commits. ' + f'Make a commit in {remote} to use it', + ) + raise e + return out.split()[0] diff --git a/testing/fixtures.py b/testing/fixtures.py index 79a11605..fa67bf2f 100644 --- a/testing/fixtures.py +++ b/testing/fixtures.py @@ -42,11 +42,12 @@ def git_dir(tempdir_factory): return path -def make_repo(tempdir_factory, repo_source): +def make_repo(tempdir_factory, repo_source, commits=True): path = git_dir(tempdir_factory) copy_tree_to_path(get_resource_path(repo_source), path) - cmd_output('git', 'add', '.', cwd=path) - git_commit(msg=make_repo.__name__, cwd=path) + if commits: + cmd_output('git', 'add', '.', cwd=path) + git_commit(msg=make_repo.__name__, cwd=path) return path diff --git a/tests/commands/try_repo_test.py b/tests/commands/try_repo_test.py index c5f891ea..0199c233 100644 --- a/tests/commands/try_repo_test.py +++ b/tests/commands/try_repo_test.py @@ -5,10 +5,12 @@ import re import time from unittest import mock +import pytest import re_assert from pre_commit import git from pre_commit.commands.try_repo import try_repo +from pre_commit.errors import FatalError from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple from testing.fixtures import git_dir @@ -98,6 +100,21 @@ def test_try_repo_relative_path(cap_out, tempdir_factory): assert not try_repo(try_repo_opts(relative_repo, hook='bash_hook')) +def test_try_repo_no_commits(cap_out, tempdir_factory): + repo = make_repo( + tempdir_factory, + 'modified_file_returns_zero_repo', + commits=False, + ) + + with cwd(git_dir(tempdir_factory)): + bare_repo = os.path.join(repo, '.git') + # previously crashed attempting modification changes + with pytest.raises(FatalError) as e: + try_repo(try_repo_opts(bare_repo, hook='bash_hook')) + assert 'appears to have no commits' in e.value + + def test_try_repo_bare_repo(cap_out, tempdir_factory): repo = make_repo(tempdir_factory, 'modified_file_returns_zero_repo') with cwd(git_dir(tempdir_factory)):