diff --git a/insert_license_header/insert_license.py b/insert_license_header/insert_license.py index ef177f8..a63b09c 100644 --- a/insert_license_header/insert_license.py +++ b/insert_license_header/insert_license.py @@ -832,6 +832,22 @@ def _get_existing_year_range(filepath: str) -> tuple[int, int] | None: return None # File exists but no license header found +def _is_shallow_git_repo() -> bool: + """Check if the current directory is a shallow git repo. + If it is, we cannot use git log to get the year range of the file. + """ + command = "git rev-parse --is-shallow-repository" + + try: + result = subprocess.run( + command, shell=True, text=True, capture_output=True, check=True + ) + except subprocess.CalledProcessError: + return False + + return result.stdout.strip() == "true" + + def _get_git_file_year_range(filepath: str) -> tuple[datetime, datetime] | None: """Uses git log formatting to extract start and end year from the commits. Take the start year from the first commit and the end year from the last. @@ -844,6 +860,12 @@ def _get_git_file_year_range(filepath: str) -> tuple[datetime, datetime] | None: """ command = f'git log --follow --format="%aI" -- "{filepath}"' + if _is_shallow_git_repo(): + # Shallow git repo, don't trust git log as the life cycle of a file + # may not be fully captured. In this case, just pretend the file + # is not tracked with Git. + return None + try: result = subprocess.run( command, shell=True, text=True, capture_output=True, check=True diff --git a/tests/insert_license_test.py b/tests/insert_license_test.py index bc264ca..cc1abe0 100644 --- a/tests/insert_license_test.py +++ b/tests/insert_license_test.py @@ -806,14 +806,21 @@ def test_dynamic_years_with_existing_license_header( assert updated_content == expected_content -# TESTCASES: -# File's last_year is now 2024 (prev 2023) -# File's last_year is still 2023 (current year = 2024) -# File's start_year +def test_git_ignored_in_shallow_repo(monkeypatch, tmp_path): + """Mock subprocess.run to throw an exception. Expect the returned datetime to have this year!""" + + def mock_shallow_test(cmd, **kwargs): + assert "git rev-parse --is-shallow-repository" in cmd + return type("mock", (), {"stdout": "true"}) -# 1. File has no license header: -# - Git tracked: take from git -# - Not Git tracked: take current-current + monkeypatch.setattr( + subprocess, + "run", + mock_shallow_test, + ) + + result = _get_git_file_year_range("some-non-existant-file.py") + assert result is None def test_git_file_creation_date(monkeypatch):