|
| 1 | +""" |
| 2 | +Start freeing disk space on Windows in the background by launching |
| 3 | +the PowerShell cleanup script, and recording the PID in a file, |
| 4 | +so later steps can wait for completion. |
| 5 | +""" |
| 6 | + |
| 7 | +import subprocess |
| 8 | +from pathlib import Path |
| 9 | +from free_disk_space_windows_util import get_pid_file, get_log_file, run_main |
| 10 | + |
| 11 | + |
| 12 | +def get_cleanup_script() -> Path: |
| 13 | + script_dir = Path(__file__).resolve().parent |
| 14 | + cleanup_script = script_dir / "free-disk-space-windows.ps1" |
| 15 | + if not cleanup_script.exists(): |
| 16 | + raise Exception(f"Cleanup script '{cleanup_script}' not found") |
| 17 | + return cleanup_script |
| 18 | + |
| 19 | + |
| 20 | +def write_pid(pid: int): |
| 21 | + pid_file = get_pid_file() |
| 22 | + if pid_file.exists(): |
| 23 | + raise Exception(f"Pid file '{pid_file}' already exists") |
| 24 | + pid_file.write_text(str(pid)) |
| 25 | + print(f"wrote pid {pid} in file {pid_file}") |
| 26 | + |
| 27 | + |
| 28 | +def launch_cleanup_process(): |
| 29 | + cleanup_script = get_cleanup_script() |
| 30 | + log_file_path = get_log_file() |
| 31 | + # Launch the PowerShell cleanup in the background and redirect logs. |
| 32 | + try: |
| 33 | + with open(log_file_path, "w", encoding="utf-8") as log_file: |
| 34 | + proc = subprocess.Popen( |
| 35 | + [ |
| 36 | + "pwsh", |
| 37 | + # Suppress PowerShell startup banner/logo for cleaner logs. |
| 38 | + "-NoLogo", |
| 39 | + # Don't load user/system profiles. Ensures a clean, predictable environment. |
| 40 | + "-NoProfile", |
| 41 | + # Disable interactive prompts. Required for CI to avoid hangs. |
| 42 | + "-NonInteractive", |
| 43 | + # Execute the specified script file (next argument). |
| 44 | + "-File", |
| 45 | + str(cleanup_script), |
| 46 | + ], |
| 47 | + # Write child stdout to the log file. |
| 48 | + stdout=log_file, |
| 49 | + # Merge stderr into stdout for a single, ordered log stream. |
| 50 | + stderr=subprocess.STDOUT, |
| 51 | + ) |
| 52 | + print( |
| 53 | + f"Started free-disk-space cleanup in background. " |
| 54 | + f"pid={proc.pid}; log_file={log_file_path}" |
| 55 | + ) |
| 56 | + return proc |
| 57 | + except FileNotFoundError as e: |
| 58 | + raise Exception("pwsh not found on PATH; cannot start disk cleanup.") from e |
| 59 | + |
| 60 | + |
| 61 | +def main() -> int: |
| 62 | + proc = launch_cleanup_process() |
| 63 | + |
| 64 | + # Write pid of the process to a file, so that later steps can read it and wait |
| 65 | + # until the process completes. |
| 66 | + write_pid(proc.pid) |
| 67 | + |
| 68 | + return 0 |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + run_main(main) |
0 commit comments