fix(installer): implement _safe_rmtree to handle Windows read-only git pack files cleanly
This commit is contained in:
@@ -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.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import io
|
import io
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
|
import stat
|
||||||
import subprocess
|
import subprocess
|
||||||
import zipfile
|
import zipfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -24,6 +25,33 @@ class AppletInstaller:
|
|||||||
self.registry = RegistryClient()
|
self.registry = RegistryClient()
|
||||||
self.shim_gen = ShimGenerator(bin_dir=self.bin_dir)
|
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
|
@staticmethod
|
||||||
def _flatten_if_nested(target_dir: Path) -> None:
|
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."""
|
"""Unwraps any single nested subfolder so that manifest.json and entrypoint live directly in target_dir root."""
|
||||||
@@ -44,12 +72,12 @@ class AppletInstaller:
|
|||||||
else:
|
else:
|
||||||
target_item.unlink(missing_ok=True)
|
target_item.unlink(missing_ok=True)
|
||||||
shutil.move(str(item), str(target_dir))
|
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:
|
def _clone_git_repo(self, git_url: str, dest_dir: Path) -> bool:
|
||||||
"""Clones a git repository into destination directory."""
|
"""Clones a git repository into destination directory."""
|
||||||
if dest_dir.exists():
|
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)
|
dest_dir.parent.mkdir(parents=True, exist_ok=True)
|
||||||
try:
|
try:
|
||||||
res = subprocess.run(["git", "clone", "--depth", "1", git_url, str(dest_dir)], capture_output=True)
|
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:
|
def _download_and_extract_zip(self, zip_url: str, dest_dir: Path) -> bool:
|
||||||
"""Downloads a zip archive and extracts it into destination directory."""
|
"""Downloads a zip archive and extracts it into destination directory."""
|
||||||
if dest_dir.exists():
|
if dest_dir.exists():
|
||||||
shutil.rmtree(dest_dir, ignore_errors=True)
|
self._safe_rmtree(dest_dir)
|
||||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||||
try:
|
try:
|
||||||
resp = requests.get(zip_url, timeout=10)
|
resp = requests.get(zip_url, timeout=10)
|
||||||
@@ -91,12 +119,11 @@ class AppletInstaller:
|
|||||||
applet_id = manifest.id
|
applet_id = manifest.id
|
||||||
target_dir = self.applets_dir / applet_id
|
target_dir = self.applets_dir / applet_id
|
||||||
if target_dir.exists():
|
if target_dir.exists():
|
||||||
shutil.rmtree(target_dir, ignore_errors=True)
|
self._safe_rmtree(target_dir)
|
||||||
shutil.copytree(local_path, target_dir)
|
shutil.copytree(local_path, target_dir)
|
||||||
|
|
||||||
# 2. Remote Git URL source
|
# 2. Remote Git URL source
|
||||||
elif clean_source.startswith(("http://", "https://", "git@")) and clean_source.endswith(".git"):
|
elif clean_source.startswith(("http://", "https://", "git@")) and clean_source.endswith(".git"):
|
||||||
# Derive name
|
|
||||||
repo_name = clean_source.rstrip("/").split("/")[-1][:-4].lower()
|
repo_name = clean_source.rstrip("/").split("/")[-1][:-4].lower()
|
||||||
target_dir = self.applets_dir / repo_name
|
target_dir = self.applets_dir / repo_name
|
||||||
success = self._clone_git_repo(clean_source, target_dir)
|
success = self._clone_git_repo(clean_source, target_dir)
|
||||||
@@ -151,7 +178,7 @@ class AppletInstaller:
|
|||||||
self.shim_gen.remove_shim(shim)
|
self.shim_gen.remove_shim(shim)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
shutil.rmtree(target_dir)
|
self._safe_rmtree(target_dir)
|
||||||
return True, f"Successfully removed applet '{clean_id}' and all associated shims."
|
return True, f"Successfully removed applet '{clean_id}' and all associated shims."
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return False, f"Failed to remove applet directory: {e}"
|
return False, f"Failed to remove applet directory: {e}"
|
||||||
|
|||||||
Reference in New Issue
Block a user