Context manager to temporarily set HOME (and Windows equivalents). Saves original environment variables and restores them on exit, even if an exception occurs. Args: home_path: Path to use as temporary home directory
(home_path)
| 31 | |
| 32 | @contextmanager |
| 33 | def temporary_home(home_path): |
| 34 | """ |
| 35 | Context manager to temporarily set HOME (and Windows equivalents). |
| 36 | |
| 37 | Saves original environment variables and restores them on exit, |
| 38 | even if an exception occurs. |
| 39 | |
| 40 | Args: |
| 41 | home_path: Path to use as temporary home directory |
| 42 | """ |
| 43 | # Save original values for Unix and Windows |
| 44 | saved_env = { |
| 45 | "HOME": os.environ.get("HOME"), |
| 46 | "USERPROFILE": os.environ.get("USERPROFILE"), |
| 47 | "HOMEDRIVE": os.environ.get("HOMEDRIVE"), |
| 48 | "HOMEPATH": os.environ.get("HOMEPATH"), |
| 49 | } |
| 50 | |
| 51 | try: |
| 52 | # Set new home directory for both Unix and Windows |
| 53 | os.environ["HOME"] = str(home_path) |
| 54 | if sys.platform == "win32": |
| 55 | os.environ["USERPROFILE"] = str(home_path) |
| 56 | # Note: HOMEDRIVE and HOMEPATH are typically set by Windows |
| 57 | # but we update them for consistency |
| 58 | drive, path = os.path.splitdrive(str(home_path)) |
| 59 | if drive: |
| 60 | os.environ["HOMEDRIVE"] = drive |
| 61 | os.environ["HOMEPATH"] = path |
| 62 | |
| 63 | yield |
| 64 | |
| 65 | finally: |
| 66 | # Restore original values |
| 67 | for key, value in saved_env.items(): |
| 68 | if value is None: |
| 69 | os.environ.pop(key, None) |
| 70 | else: |
| 71 | os.environ[key] = value |
| 72 | |
| 73 | |
| 74 | def check_hook(command: str, should_block: bool) -> bool: |
no outgoing calls
no test coverage detected