fix(installer): implement _safe_rmtree to handle Windows read-only git pack files cleanly

This commit is contained in:
Gravitiny Team
2026-10-03 04:12:30 +03:00
parent d8f956f007
commit 66b763dd0c
2 changed files with 57 additions and 6 deletions
+24
View File
@@ -31,3 +31,27 @@ Additionally, Python's `shutil.move(src, dst)` moves the source folder *inside*
Re-ran `python main.py install lex` and `python main.py install sec`. Confirmed that `main.py` is extracted directly to `C:\Users\al3ph\.gravitiny\applets\lex\main.py`. Verified that direct shim execution `lex books` runs cleanly and instantly.
---
## Issue #002: Windows Access Denied (`[WinError 5]`) on Read-Only Git Pack Objects during Applet Removal
- **Component:** `gravitiny.src.installer.AppletInstaller`
- **Severity:** Medium (Applet Removal Failure)
- **Status:** Resolved
### Symptom
When executing `gravitiny remove <applet>` on Windows, the removal aborted with:
```text
Removal failed: Failed to remove applet directory: [WinError 5] Access is denied: 'C:\Users\al3ph\.gravitiny\applets\lex\.git\objects\pack\pack-c669ff02246bf9d7f1e23b15797c9d1bb6d22827.idx'
```
### Root Cause
Git marks indexed pack files in `.git/objects/pack/*` with the Windows `FILE_ATTRIBUTE_READONLY` flag to prevent accidental modification. Python's default `shutil.rmtree(path)` fails on Windows when encountering read-only files without a custom error handler.
### Solution
1. Implemented a robust `_safe_rmtree(target_dir: Path)` helper in `AppletInstaller`.
2. Attached an error callback (`onexc` in Python 3.12+ and `onerror` in legacy versions) that dynamically clears the read-only attribute (`os.chmod(path, stat.S_IWRITE)`) and retries file unlinking.
3. Replaced all raw `shutil.rmtree` invocations with `_safe_rmtree`.
### Verification
Executed full install, remove, and re-install cycles for `lex` and `sec`. The removal process deleted the `.git` directory and all associated shims cleanly with zero permission errors.
+33 -6
View File
@@ -1,6 +1,7 @@
import io
import os
import shutil
import stat
import subprocess
import zipfile
from pathlib import Path
@@ -24,6 +25,33 @@ class AppletInstaller:
self.registry = RegistryClient()
self.shim_gen = ShimGenerator(bin_dir=self.bin_dir)
@staticmethod
def _safe_rmtree(target_dir: Path) -> None:
"""Robustly removes a directory tree, clearing Windows read-only flags on .git objects."""
if not target_dir.exists():
return
def _force_remove_legacy(func, path, exc_info):
try:
os.chmod(path, stat.S_IWRITE)
func(path)
except Exception:
pass
def _force_remove_modern(func, path, exc):
try:
os.chmod(path, stat.S_IWRITE)
func(path)
except Exception:
pass
try:
shutil.rmtree(target_dir, onexc=_force_remove_modern)
except TypeError:
shutil.rmtree(target_dir, onerror=_force_remove_legacy)
except Exception:
pass
@staticmethod
def _flatten_if_nested(target_dir: Path) -> None:
"""Unwraps any single nested subfolder so that manifest.json and entrypoint live directly in target_dir root."""
@@ -44,12 +72,12 @@ class AppletInstaller:
else:
target_item.unlink(missing_ok=True)
shutil.move(str(item), str(target_dir))
shutil.rmtree(nested_dir, ignore_errors=True)
cls._safe_rmtree(nested_dir)
def _clone_git_repo(self, git_url: str, dest_dir: Path) -> bool:
"""Clones a git repository into destination directory."""
if dest_dir.exists():
shutil.rmtree(dest_dir, ignore_errors=True)
self._safe_rmtree(dest_dir)
dest_dir.parent.mkdir(parents=True, exist_ok=True)
try:
res = subprocess.run(["git", "clone", "--depth", "1", git_url, str(dest_dir)], capture_output=True)
@@ -63,7 +91,7 @@ class AppletInstaller:
def _download_and_extract_zip(self, zip_url: str, dest_dir: Path) -> bool:
"""Downloads a zip archive and extracts it into destination directory."""
if dest_dir.exists():
shutil.rmtree(dest_dir, ignore_errors=True)
self._safe_rmtree(dest_dir)
dest_dir.mkdir(parents=True, exist_ok=True)
try:
resp = requests.get(zip_url, timeout=10)
@@ -91,12 +119,11 @@ class AppletInstaller:
applet_id = manifest.id
target_dir = self.applets_dir / applet_id
if target_dir.exists():
shutil.rmtree(target_dir, ignore_errors=True)
self._safe_rmtree(target_dir)
shutil.copytree(local_path, target_dir)
# 2. Remote Git URL source
elif clean_source.startswith(("http://", "https://", "git@")) and clean_source.endswith(".git"):
# Derive name
repo_name = clean_source.rstrip("/").split("/")[-1][:-4].lower()
target_dir = self.applets_dir / repo_name
success = self._clone_git_repo(clean_source, target_dir)
@@ -151,7 +178,7 @@ class AppletInstaller:
self.shim_gen.remove_shim(shim)
try:
shutil.rmtree(target_dir)
self._safe_rmtree(target_dir)
return True, f"Successfully removed applet '{clean_id}' and all associated shims."
except Exception as e:
return False, f"Failed to remove applet directory: {e}"