Skip to content

Commit

Permalink
Check whether in shallow repo. If so, do not trust git.
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasmarwitz committed Jan 25, 2024
1 parent 685c934 commit aca20cf
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
22 changes: 22 additions & 0 deletions insert_license_header/insert_license.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
21 changes: 14 additions & 7 deletions tests/insert_license_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit aca20cf

Please sign in to comment.