libvcs icon indicating copy to clipboard operation
libvcs copied to clipboard

`git init` compatibility, `Git.version()`

Open tony opened this issue 9 months ago • 2 comments

Problem

  • git init compatibility issues
  • no uniform way to check and compare git --version

Details

  Issue Summary

  The libvcs test suite is failing with newer Git versions (2.43.0 and later) due to changes in how Git handles repository initialization. Specifically, tests fail with:

  libvcs.exc.CommandError: Command failed with code 1: git init empty_git_repo

  What Changed in Git Init

  Git has progressively evolved its git init command behavior across versions:

  1. Git 2.28.0 (July 2020) introduced the ability to configure the default branch name with the init.defaultBranch config option.
  2. Git 2.30.0 (December 2020) added the -b/--initial-branch option to explicitly specify the initial branch name.
  3. Newer releases have tightened the behavior around initialization, with Git 2.43.0 potentially being more strict about directory existence or permissions.

  The error occurs in libvcs's _create_git_remote_repo function, which uses:

  run(
      ["git", "init", remote_repo_path.stem, *init_cmd_args],
      cwd=remote_repo_path.parent,
  )

  Without specifying an initial branch name, this command now fails on newer Git versions.

  Recommended Patch for libvcs

  Here's the fix needed in src/libvcs/pytest_plugin.py:

  def _create_git_remote_repo(
      remote_repo_path: pathlib.Path,
      remote_repo_post_init: CreateRepoPostInitFn | None = None,
      init_cmd_args: InitCmdArgs = DEFAULT_GIT_REMOTE_REPO_CMD_ARGS,
      env: _ENV | None = None,
  ) -> pathlib.Path:
      if init_cmd_args is None:
          init_cmd_args = []

      # Create the command with initial branch explicitly set to 'main'
      # This works with all Git versions
      git_cmd = ["git", "init"]

      # Add -b option for initial branch name (compatible with Git 2.30.0+)
      git_version_output = run(["git", "--version"], check_returncode=False)
      try:
          if git_version_output and git_version_output.output:
              # Add -b option only for Git versions that support it
              git_cmd.extend(["-b", "main"])
      except Exception:
          # If version check fails, try without -b option
          pass

      # Add repository path and any additional arguments
      git_cmd.extend([remote_repo_path.stem, *init_cmd_args])

      # Run the git init command
      run(
          git_cmd,
          cwd=remote_repo_path.parent,
          env=env,
      )

      if remote_repo_post_init is not None and callable(remote_repo_post_init):
          remote_repo_post_init(remote_repo_path=remote_repo_path, env=env)

      return remote_repo_path

  Alternative Simpler Patch

  If backward compatibility with very old Git versions isn't required, a simpler fix is:

  def _create_git_remote_repo(
      remote_repo_path: pathlib.Path,
      remote_repo_post_init: CreateRepoPostInitFn | None = None,
      init_cmd_args: InitCmdArgs = DEFAULT_GIT_REMOTE_REPO_CMD_ARGS,
      env: _ENV | None = None,
  ) -> pathlib.Path:
      if init_cmd_args is None:
          init_cmd_args = []

      # Always use -b option to specify initial branch explicitly
      run(
          ["git", "init", "-b", "main", remote_repo_path.stem, *init_cmd_args],
          cwd=remote_repo_path.parent,
          env=env,
      )

      if remote_repo_post_init is not None and callable(remote_repo_post_init):
          remote_repo_post_init(remote_repo_path=remote_repo_path, env=env)

      return remote_repo_path

  Explanation for Maintainers

  This patch addresses compatibility issues with modern Git versions while maintaining backward compatibility with older versions. The problem occurs because newer Git versions are more particular about branch naming conventions
  and initialization parameters.

  The test suite may pass when running individual test files but fail when running the entire suite because of how fixture caching works in pytest - when running single files, tests might use already-created repositories, but the
  full suite likely tries to create fresh repositories, triggering the Git init failure.

Summary by Sourcery

Improve git compatibility by introducing internal version parsing utilities and updating documentation with project standards and workflows.

New Features:

  • Add internal version parsing and comparison utilities for consistent handling of git version strings.

Enhancements:

  • Introduce vendored modules for version and structure handling to improve compatibility and version checks.

Documentation:

  • Add CLAUDE.md with detailed project guidelines, development workflow, and coding standards.

tony avatar May 11 '25 11:05 tony

Reviewer's Guide

This pull request introduces a vendorized version parsing module to enable uniform Git version comparison and improve git init compatibility, and adds a CLAUDE.md file with detailed project and contribution guidelines.

Class Diagram for Structure Types (_structures.py)

classDiagram
    class InfinityType {
        +__repr__() str
        +__hash__() int
        +__lt__(other: object) bool
        +__le__(other: object) bool
        +__eq__(other: object) bool
        +__gt__(other: object) bool
        +__ge__(other: object) bool
        +__neg__() NegativeInfinityType
    }
    class NegativeInfinityType {
        +__repr__() str
        +__hash__() int
        +__lt__(other: object) bool
        +__le__(other: object) bool
        +__eq__(other: object) bool
        +__gt__(other: object) bool
        +__ge__(other: object) bool
        +__neg__() InfinityType
    }
    note "Defines Infinity and NegativeInfinity types and instances (Infinity, NegativeInfinity) used in version comparison logic."

File-Level Changes

Change Details Files
Vendorized version parsing and comparison utilities were added to support uniform handling of Git versions.
  • Added src/libvcs/_vendor/version.py, a backport of packaging.version for version parsing and comparison.
  • Added src/libvcs/_vendor/_structures.py, providing Infinity and NegativeInfinity types for version sorting logic.
src/libvcs/_vendor/version.py
src/libvcs/_vendor/_structures.py
Project documentation and contribution guidelines for Claude were introduced.
  • Added CLAUDE.md with critical requirements, development workflow, architecture overview, testing strategy, coding standards, and debugging tips.
CLAUDE.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an issue from a review comment by replying to it. You can also reply to a review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull request title to generate a title at any time. You can also comment @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in the pull request body to generate a PR summary at any time exactly where you want it. You can also comment @sourcery-ai summary on the pull request to (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the pull request to resolve all Sourcery comments. Useful if you've already addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull request to dismiss all existing Sourcery reviews. Especially useful if you want to start fresh with a new review - don't forget to comment @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

  • Contact our support team for questions or feedback.
  • Visit our documentation for detailed guides and information.
  • Keep in touch with the Sourcery team by following us on X/Twitter, LinkedIn or GitHub.

sourcery-ai[bot] avatar May 11 '25 11:05 sourcery-ai[bot]

Codecov Report

Attention: Patch coverage is 79.22705% with 86 lines in your changes missing coverage. Please review.

Project coverage is 56.80%. Comparing base (0cf3504) to head (46bad96).

Files with missing lines Patch % Lines
src/libvcs/_vendor/version.py 60.50% 48 Missing and 14 partials :warning:
src/libvcs/_vendor/_structures.py 56.25% 14 Missing :warning:
src/libvcs/cmd/git.py 91.07% 2 Missing and 3 partials :warning:
tests/test_pytest_plugin.py 95.09% 3 Missing and 2 partials :warning:
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #491      +/-   ##
==========================================
+ Coverage   54.05%   56.80%   +2.75%     
==========================================
  Files          40       42       +2     
  Lines        3637     4040     +403     
  Branches      794      825      +31     
==========================================
+ Hits         1966     2295     +329     
- Misses       1319     1370      +51     
- Partials      352      375      +23     

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

:rocket: New features to boost your workflow:
  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

codecov[bot] avatar May 11 '25 11:05 codecov[bot]