Skip to content

The agent that grows with you

fix(profiles): remove Git metadata from distributions

liuzinann7cdbd5be4869
diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.py
index 16e77d80a54..9cf1a5166de 100644
--- a/hermes_cli/profile_distribution.py
+++ b/hermes_cli/profile_distribution.py
@@ -11,6 +11,7 @@ import operator
import os
import re
import shutil
+import stat
import subprocess
import tempfile
from dataclasses import dataclass, field
@@ -243,6 +244,28 @@ def _git_clone(url: str, dest: Path) -> None:
raise DistributionError(f"git clone failed: {(result.stderr or '').strip()}")
+def _rmtree_make_writable(func, path, exc_info) -> None:
+ """Retry a failed tree removal after clearing Windows read-only attributes."""
+ exc = exc_info[1] if isinstance(exc_info, tuple) else exc_info
+ if not isinstance(exc, PermissionError):
+ raise exc
+ for target in (path, os.path.dirname(path)):
+ if target:
+ try:
+ os.chmod(target, os.stat(target).st_mode | stat.S_IWUSR)
+ except OSError:
+ pass
+ func(path)
+
+
+def _remove_git_metadata(path: Path) -> None:
+ """Remove cloned Git metadata completely, including read-only objects on Windows."""
+ try:
+ shutil.rmtree(path, onexc=_rmtree_make_writable)
+ except TypeError: # Python 3.11 uses the legacy ``onerror`` callback name.
+ shutil.rmtree(path, onerror=_rmtree_make_writable)
+
+
def _stage_source(source: str, workdir: Path) -> Tuple[Path, str]:
"""Resolve *source* to ``(staged_dir, provenance)``: git URLs are shallow-cloned into
*workdir* (``.git`` removed); a local directory is used in place."""
@@ -250,7 +273,7 @@ def _stage_source(source: str, workdir: Path) -> Tuple[Path, str]:
if _looks_like_git_url(src_str):
staged, provenance = workdir / "clone", src_str
_git_clone(src_str, staged)
- shutil.rmtree(staged / ".git", ignore_errors=True)
+ _remove_git_metadata(staged / ".git")
missing = (
f"No {MANIFEST_FILENAME} at the root of {src_str!r}. "
"This repository is not a Hermes profile distribution."
diff --git a/tests/hermes_cli/test_profile_distribution.py b/tests/hermes_cli/test_profile_distribution.py
index e0129d936e9..a2cee719952 100644
--- a/tests/hermes_cli/test_profile_distribution.py
+++ b/tests/hermes_cli/test_profile_distribution.py
@@ -11,6 +11,8 @@ mocking git would just test the mock.
from __future__ import annotations
import shutil
+import stat
+import subprocess
import sys
from pathlib import Path
@@ -26,6 +28,7 @@ from hermes_cli.profile_distribution import (
_env_template_from_manifest,
_looks_like_git_url,
_parse_semver,
+ _stage_source,
check_hermes_requires,
describe_distribution,
install_distribution,
@@ -211,6 +214,36 @@ class TestLooksLikeGitUrl:
def test_accepts_git_sources(self, src):
assert _looks_like_git_url(src)
+ @pytest.mark.windows_only
+ def test_git_source_removes_read_only_git_metadata(self, tmp_path, monkeypatch):
+ origin = tmp_path / "origin"
+ subprocess.run(["git", "init", "--quiet", str(origin)], check=True)
+ (origin / MANIFEST_FILENAME).write_text("name: demo\nversion: 1.0.0\n", encoding="utf-8")
+ subprocess.run(["git", "-C", str(origin), "add", "."], check=True)
+ subprocess.run([
+ "git", "-C", str(origin), "-c", "user.name=Test", "-c",
+ "[email protected]", "commit", "--quiet", "-m", "init",
+ ], check=True)
+ saw_read_only_objects = []
+
+ def clone_local(_url, dest):
+ subprocess.run(["git", "clone", "--quiet", str(origin), str(dest)], check=True)
+ objects = [path for path in (dest / ".git" / "objects").rglob("*") if path.is_file()]
+ saw_read_only_objects.append(
+ bool(objects) and any(
+ path.stat().st_file_attributes & stat.FILE_ATTRIBUTE_READONLY for path in objects
+ )
+ )
+
+ monkeypatch.setattr("hermes_cli.profile_distribution._git_clone", clone_local)
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ staged, _provenance = _stage_source("https://example.invalid/demo.git", workdir)
+
+ assert saw_read_only_objects == [True]
+ assert not (staged / ".git").exists()
+
# ===========================================================================
# Install — fresh and force (from a local-directory source)