feat: make better error message if try-repo fails because there are no commits on the repo.

This commit is contained in:
Jared Koontz 2025-03-31 17:23:33 -06:00
parent d2b61d0ef2
commit ef638716cb
3 changed files with 34 additions and 4 deletions

View file

@ -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]

View file

@ -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

View file

@ -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)):