feat(core): implement standalone isolated installation and clean uninstaller
This commit is contained in:
@@ -55,3 +55,28 @@ Git marks indexed pack files in `.git/objects/pack/*` with the Windows `FILE_ATT
|
|||||||
### Verification
|
### 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.
|
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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Issue #003: Core Isolation & Clean System-Wide Deregistration
|
||||||
|
|
||||||
|
- **Component:** `install.py`, `gravitiny.src.uninstaller.GravitinyUninstaller`, `gravitiny.src.cli`
|
||||||
|
- **Severity:** Architectural Requirement
|
||||||
|
- **Status:** Resolved
|
||||||
|
|
||||||
|
### Symptom
|
||||||
|
Previously, the master shim `gravitiny.cmd` referenced the cloned workspace folder directly (`c:\...\gravitiny\main.py`). If the user deleted or moved the cloned repository folder after running setup, the `gravitiny` command broke immediately. Furthermore, there was no automated mechanism to clean up `~/.gravitiny`, remove shims, and deregister system PATH upon uninstallation.
|
||||||
|
|
||||||
|
### Root Cause
|
||||||
|
A true zero-trace CLI package manager must be fully self-contained upon installation and provide a clean uninstallation pathway without leaving orphan PATH entries or dangling shim scripts.
|
||||||
|
|
||||||
|
### Solution
|
||||||
|
1. Built a standalone installer `install.py` that copies the Gravitiny core engine into `~/.gravitiny/core`, creates the master entrypoint shim `~/.gravitiny/bin/gravitiny.cmd`, and registers `~/.gravitiny/bin` in the user's PATH environment.
|
||||||
|
2. Built `GravitinyUninstaller` in `gravitiny.src.uninstaller` with `remove_from_path()` to clean Windows User Registry (`HKEY_CURRENT_USER\Environment\Path`) / shell rc profiles and broadcast `WM_SETTINGCHANGE`.
|
||||||
|
3. Implemented `gravitiny uninstall [-y]` command with confirmation safeguards and string catalog centralization.
|
||||||
|
|
||||||
|
### Verification
|
||||||
|
1. Ran `python install.py` and confirmed `~/.gravitiny/core` is populated and `~/.gravitiny/bin/gravitiny.cmd` points to the isolated runtime.
|
||||||
|
2. Verified applet discovery, installation, and execution (`lex`, `sec`) from an independent working directory outside the repository clone.
|
||||||
|
3. Verified `gravitiny --help` and `gravitiny uninstall` command workflow.
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -84,6 +84,16 @@
|
|||||||
"removing": "Removing applet '{applet_id}'...",
|
"removing": "Removing applet '{applet_id}'...",
|
||||||
"success": "{message}",
|
"success": "{message}",
|
||||||
"failed": "Removal failed: {error}"
|
"failed": "Removal failed: {error}"
|
||||||
|
},
|
||||||
|
"uninstall": {
|
||||||
|
"description": "Completely remove Gravitiny, all applets, shims, and system PATH registration",
|
||||||
|
"usage": "Usage: gravitiny uninstall [-y | --yes]",
|
||||||
|
"prompt_warning": "Warning: This will permanently remove ~/.gravitiny and deregister PATH.",
|
||||||
|
"prompt_confirm": "Are you sure you want to proceed? (y/N): ",
|
||||||
|
"aborted": "Uninstallation aborted.",
|
||||||
|
"uninstalling": "Removing Gravitiny and cleaning system configuration...",
|
||||||
|
"success": "{message}",
|
||||||
|
"failed": "Uninstallation failed: {error}"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"errors": {
|
"errors": {
|
||||||
|
|||||||
+11
-4
@@ -2,12 +2,19 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# Ensure package root is in sys.path
|
# Ensure package root and current directory are in sys.path
|
||||||
package_root = Path(__file__).resolve().parent.parent
|
current_dir = Path(__file__).resolve().parent
|
||||||
if str(package_root) not in sys.path:
|
parent_dir = current_dir.parent
|
||||||
sys.path.insert(0, str(package_root))
|
|
||||||
|
|
||||||
|
if str(current_dir) not in sys.path:
|
||||||
|
sys.path.insert(0, str(current_dir))
|
||||||
|
if str(parent_dir) not in sys.path:
|
||||||
|
sys.path.insert(0, str(parent_dir))
|
||||||
|
|
||||||
|
try:
|
||||||
from gravitiny.src.cli import run_cli
|
from gravitiny.src.cli import run_cli
|
||||||
|
except ImportError:
|
||||||
|
from src.cli import run_cli
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
sys.exit(run_cli())
|
sys.exit(run_cli())
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ try:
|
|||||||
from gravitiny.src.manifest import load_manager_manifest
|
from gravitiny.src.manifest import load_manager_manifest
|
||||||
from gravitiny.src.registry import RegistryClient
|
from gravitiny.src.registry import RegistryClient
|
||||||
from gravitiny.src.shims import ShimGenerator
|
from gravitiny.src.shims import ShimGenerator
|
||||||
|
from gravitiny.src.uninstaller import GravitinyUninstaller
|
||||||
except ImportError:
|
except ImportError:
|
||||||
from src.catalog import catalog
|
from src.catalog import catalog
|
||||||
from src.discovery import AppletDiscovery
|
from src.discovery import AppletDiscovery
|
||||||
@@ -19,6 +20,7 @@ except ImportError:
|
|||||||
from src.manifest import load_manager_manifest
|
from src.manifest import load_manager_manifest
|
||||||
from src.registry import RegistryClient
|
from src.registry import RegistryClient
|
||||||
from src.shims import ShimGenerator
|
from src.shims import ShimGenerator
|
||||||
|
from src.uninstaller import GravitinyUninstaller
|
||||||
|
|
||||||
|
|
||||||
def print_help() -> None:
|
def print_help() -> None:
|
||||||
@@ -34,6 +36,7 @@ def print_help() -> None:
|
|||||||
print(" gravitiny info <applet_id> " + catalog.get("commands.info.description"))
|
print(" gravitiny info <applet_id> " + catalog.get("commands.info.description"))
|
||||||
print(" gravitiny alias <applet> <alias> " + catalog.get("commands.alias.description"))
|
print(" gravitiny alias <applet> <alias> " + catalog.get("commands.alias.description"))
|
||||||
print(" gravitiny setup " + catalog.get("commands.setup.description"))
|
print(" gravitiny setup " + catalog.get("commands.setup.description"))
|
||||||
|
print(" gravitiny uninstall [-y] " + catalog.get("commands.uninstall.description"))
|
||||||
print()
|
print()
|
||||||
print("Shorthand execution:")
|
print("Shorthand execution:")
|
||||||
print(" gravitiny <applet_id> [args...]")
|
print(" gravitiny <applet_id> [args...]")
|
||||||
@@ -367,6 +370,32 @@ def cmd_setup() -> int:
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_uninstall(args: List[str]) -> int:
|
||||||
|
skip_confirm = "-y" in args or "--yes" in args
|
||||||
|
if not skip_confirm:
|
||||||
|
print(catalog.get("commands.uninstall.prompt_warning"))
|
||||||
|
try:
|
||||||
|
choice = input(catalog.get("commands.uninstall.prompt_confirm")).strip().lower()
|
||||||
|
except (KeyboardInterrupt, EOFError):
|
||||||
|
print("\n" + catalog.get("commands.uninstall.aborted"))
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if choice not in ["y", "yes"]:
|
||||||
|
print(catalog.get("commands.uninstall.aborted"))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
print(catalog.get("commands.uninstall.uninstalling"))
|
||||||
|
uninstaller = GravitinyUninstaller()
|
||||||
|
success, message = uninstaller.uninstall()
|
||||||
|
|
||||||
|
if success:
|
||||||
|
print(catalog.format("commands.uninstall.success", message=message))
|
||||||
|
return 0
|
||||||
|
else:
|
||||||
|
print(catalog.format("commands.uninstall.failed", error=message))
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
def run_cli(args: Optional[List[str]] = None) -> int:
|
def run_cli(args: Optional[List[str]] = None) -> int:
|
||||||
if hasattr(sys.stdout, "reconfigure"):
|
if hasattr(sys.stdout, "reconfigure"):
|
||||||
try:
|
try:
|
||||||
@@ -411,6 +440,8 @@ def run_cli(args: Optional[List[str]] = None) -> int:
|
|||||||
return cmd_alias(sub_args)
|
return cmd_alias(sub_args)
|
||||||
elif command == "setup":
|
elif command == "setup":
|
||||||
return cmd_setup()
|
return cmd_setup()
|
||||||
|
elif command == "uninstall":
|
||||||
|
return cmd_uninstall(sub_args)
|
||||||
|
|
||||||
# Shorthand: check if command matches an installed applet directly
|
# Shorthand: check if command matches an installed applet directly
|
||||||
discovery = AppletDiscovery()
|
discovery = AppletDiscovery()
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, List, Optional
|
from typing import Dict, List, Optional
|
||||||
|
try:
|
||||||
from gravitiny.src.manifest import AppletManifest, parse_applet_manifest
|
from gravitiny.src.manifest import AppletManifest, parse_applet_manifest
|
||||||
|
except ImportError:
|
||||||
|
from src.manifest import AppletManifest, parse_applet_manifest
|
||||||
|
|
||||||
|
|
||||||
class AppletDiscovery:
|
class AppletDiscovery:
|
||||||
|
|||||||
@@ -8,9 +8,14 @@ from pathlib import Path
|
|||||||
from typing import Optional, Tuple
|
from typing import Optional, Tuple
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
|
try:
|
||||||
from gravitiny.src.manifest import parse_applet_manifest
|
from gravitiny.src.manifest import parse_applet_manifest
|
||||||
from gravitiny.src.registry import RegistryClient
|
from gravitiny.src.registry import RegistryClient
|
||||||
from gravitiny.src.shims import ShimGenerator
|
from gravitiny.src.shims import ShimGenerator
|
||||||
|
except ImportError:
|
||||||
|
from src.manifest import parse_applet_manifest
|
||||||
|
from src.registry import RegistryClient
|
||||||
|
from src.shims import ShimGenerator
|
||||||
|
|
||||||
|
|
||||||
class AppletInstaller:
|
class AppletInstaller:
|
||||||
@@ -72,7 +77,7 @@ 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))
|
||||||
cls._safe_rmtree(nested_dir)
|
AppletInstaller._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."""
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ import subprocess
|
|||||||
import sys
|
import sys
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
|
try:
|
||||||
from gravitiny.src.manifest import AppletManifest
|
from gravitiny.src.manifest import AppletManifest
|
||||||
|
except ImportError:
|
||||||
|
from src.manifest import AppletManifest
|
||||||
|
|
||||||
|
|
||||||
class AppletLauncher:
|
class AppletLauncher:
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ import sys
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
|
try:
|
||||||
from gravitiny.src.manifest import AppletManifest
|
from gravitiny.src.manifest import AppletManifest
|
||||||
|
except ImportError:
|
||||||
|
from src.manifest import AppletManifest
|
||||||
|
|
||||||
|
|
||||||
class ShimGenerator:
|
class ShimGenerator:
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import ctypes
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
try:
|
||||||
|
from gravitiny.src.installer import AppletInstaller
|
||||||
|
except ImportError:
|
||||||
|
from src.installer import AppletInstaller
|
||||||
|
|
||||||
|
|
||||||
|
class GravitinyUninstaller:
|
||||||
|
"""Removes Gravitiny from system PATH and completely purges ~/.gravitiny directory."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
user_home = Path.home()
|
||||||
|
self.gravitiny_home = user_home / ".gravitiny"
|
||||||
|
self.bin_dir = self.gravitiny_home / "bin"
|
||||||
|
|
||||||
|
def remove_from_path(self) -> bool:
|
||||||
|
"""Removes ~/.gravitiny/bin from Windows User Registry or POSIX shell profiles."""
|
||||||
|
bin_str = str(self.bin_dir)
|
||||||
|
|
||||||
|
if os.name == "nt":
|
||||||
|
try:
|
||||||
|
import winreg
|
||||||
|
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_READ | winreg.KEY_WRITE) as key:
|
||||||
|
try:
|
||||||
|
current_val, val_type = winreg.QueryValueEx(key, "Path")
|
||||||
|
except FileNotFoundError:
|
||||||
|
return True
|
||||||
|
|
||||||
|
paths = [p for p in current_val.split(";") if p.strip()]
|
||||||
|
filtered_paths = [p for p in paths if p.strip().lower() != bin_str.lower()]
|
||||||
|
|
||||||
|
if len(filtered_paths) != len(paths):
|
||||||
|
new_val = ";".join(filtered_paths)
|
||||||
|
winreg.SetValueEx(key, "Path", 0, val_type, new_val)
|
||||||
|
try:
|
||||||
|
HWND_BROADCAST = 0xFFFF
|
||||||
|
WM_SETTINGCHANGE = 0x001A
|
||||||
|
SMTO_ABORTIFHUNG = 0x0002
|
||||||
|
res = ctypes.c_ulong()
|
||||||
|
ctypes.windll.user32.SendMessageTimeoutW(
|
||||||
|
HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 2000, ctypes.byref(res)
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
home = Path.home()
|
||||||
|
for rc in [".bashrc", ".zshrc", ".profile"]:
|
||||||
|
rc_file = home / rc
|
||||||
|
if rc_file.exists():
|
||||||
|
lines = rc_file.read_text(encoding="utf-8").splitlines()
|
||||||
|
filtered_lines = [l for l in lines if bin_str not in l and "# Gravitiny CLI PATH" not in l]
|
||||||
|
rc_file.write_text("\n".join(filtered_lines) + "\n", encoding="utf-8")
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def uninstall(self) -> Tuple[bool, str]:
|
||||||
|
"""Executes full uninstallation: cleans PATH and deletes ~/.gravitiny."""
|
||||||
|
path_cleaned = self.remove_from_path()
|
||||||
|
|
||||||
|
if self.gravitiny_home.exists():
|
||||||
|
try:
|
||||||
|
AppletInstaller._safe_rmtree(self.gravitiny_home)
|
||||||
|
except Exception as e:
|
||||||
|
return False, f"Removed from PATH, but failed to delete directory '{self.gravitiny_home}': {e}"
|
||||||
|
|
||||||
|
return True, "Gravitiny and all applets have been completely removed from your system."
|
||||||
+129
@@ -0,0 +1,129 @@
|
|||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# Ensure local package can be imported during installation
|
||||||
|
workspace_root = Path(__file__).resolve().parent
|
||||||
|
if str(workspace_root) not in sys.path:
|
||||||
|
sys.path.insert(0, str(workspace_root))
|
||||||
|
|
||||||
|
from gravitiny.src.installer import AppletInstaller
|
||||||
|
from gravitiny.src.manifest import load_manager_manifest
|
||||||
|
|
||||||
|
|
||||||
|
def install_gravitiny_core() -> int:
|
||||||
|
user_home = Path.home()
|
||||||
|
gravitiny_home = user_home / ".gravitiny"
|
||||||
|
core_dir = gravitiny_home / "core"
|
||||||
|
bin_dir = gravitiny_home / "bin"
|
||||||
|
applets_dir = gravitiny_home / "applets"
|
||||||
|
|
||||||
|
print("Installing Gravitiny Core...")
|
||||||
|
|
||||||
|
bin_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
applets_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# 1. Copy Core package into ~/.gravitiny/core
|
||||||
|
source_gravitiny = workspace_root / "gravitiny"
|
||||||
|
if core_dir.exists():
|
||||||
|
AppletInstaller._safe_rmtree(core_dir)
|
||||||
|
|
||||||
|
core_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
for item in source_gravitiny.iterdir():
|
||||||
|
if item.name in ["applets", "__pycache__", ".git"]:
|
||||||
|
continue
|
||||||
|
dest_item = core_dir / item.name
|
||||||
|
if item.is_dir():
|
||||||
|
shutil.copytree(item, dest_item)
|
||||||
|
else:
|
||||||
|
shutil.copy2(item, dest_item)
|
||||||
|
|
||||||
|
# 2. Generate Master Gravitiny Shim pointing to ~/.gravitiny/core/main.py
|
||||||
|
is_windows = os.name == "nt"
|
||||||
|
python_exe = sys.executable
|
||||||
|
core_main = core_dir / "main.py"
|
||||||
|
|
||||||
|
if is_windows:
|
||||||
|
master_shim = bin_dir / "gravitiny.cmd"
|
||||||
|
with open(master_shim, "w", encoding="utf-8") as f:
|
||||||
|
f.write(f"@echo off\nsetlocal\n\"{python_exe}\" \"{core_main}\" %*\n")
|
||||||
|
else:
|
||||||
|
master_shim = bin_dir / "gravitiny"
|
||||||
|
with open(master_shim, "w", encoding="utf-8") as f:
|
||||||
|
f.write(f"#!/usr/bin/env sh\nexec \"{python_exe}\" \"{core_main}\" \"$@\"\n")
|
||||||
|
try:
|
||||||
|
os.chmod(master_shim, 0o755)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 3. Configure PATH
|
||||||
|
bin_str = str(bin_dir)
|
||||||
|
already_in_path = False
|
||||||
|
|
||||||
|
if bin_str.lower() in os.environ.get("PATH", "").lower():
|
||||||
|
already_in_path = True
|
||||||
|
|
||||||
|
if not already_in_path and is_windows:
|
||||||
|
try:
|
||||||
|
import winreg
|
||||||
|
import ctypes
|
||||||
|
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_READ | winreg.KEY_WRITE) as key:
|
||||||
|
try:
|
||||||
|
current_val, val_type = winreg.QueryValueEx(key, "Path")
|
||||||
|
except FileNotFoundError:
|
||||||
|
current_val, val_type = "", winreg.REG_EXPAND_SZ
|
||||||
|
|
||||||
|
paths = [p for p in current_val.split(";") if p.strip()]
|
||||||
|
if bin_str.lower() not in [p.lower() for p in paths]:
|
||||||
|
paths.append(bin_str)
|
||||||
|
new_val = ";".join(paths)
|
||||||
|
winreg.SetValueEx(key, "Path", 0, val_type, new_val)
|
||||||
|
try:
|
||||||
|
HWND_BROADCAST = 0xFFFF
|
||||||
|
WM_SETTINGCHANGE = 0x001A
|
||||||
|
SMTO_ABORTIFHUNG = 0x0002
|
||||||
|
res = ctypes.c_ulong()
|
||||||
|
ctypes.windll.user32.SendMessageTimeoutW(
|
||||||
|
HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 2000, ctypes.byref(res)
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
already_in_path = True
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
elif not already_in_path and not is_windows:
|
||||||
|
try:
|
||||||
|
for rc in [".bashrc", ".zshrc", ".profile"]:
|
||||||
|
rc_file = user_home / rc
|
||||||
|
if rc_file.exists():
|
||||||
|
content = rc_file.read_text(encoding="utf-8")
|
||||||
|
if bin_str not in content:
|
||||||
|
with open(rc_file, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f'\n# Gravitiny CLI PATH\nexport PATH="{bin_str}:$PATH"\n')
|
||||||
|
already_in_path = True
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
manifest = load_manager_manifest()
|
||||||
|
print("=" * 65)
|
||||||
|
print(f" {manifest.get('name', 'Gravitiny')} Core v{manifest.get('version', '0.1.0')} installed successfully!")
|
||||||
|
print("=" * 65)
|
||||||
|
print(f" Core Location : {core_dir}")
|
||||||
|
print(f" Bin Location : {bin_dir} (Registered in PATH)")
|
||||||
|
print(f" Applets Root : {applets_dir}")
|
||||||
|
print()
|
||||||
|
print(" [IMPORTANT] Installation is completely self-contained.")
|
||||||
|
print(" You may now safely DELETE this cloned/downloaded repository folder.")
|
||||||
|
print()
|
||||||
|
print(" Next steps:")
|
||||||
|
print(" 1. Restart your terminal window.")
|
||||||
|
print(" 2. Run: gravitiny search dictionary")
|
||||||
|
print(" 3. Run: gravitiny install sec")
|
||||||
|
print("=" * 65)
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(install_gravitiny_core())
|
||||||
Reference in New Issue
Block a user