main_profile_recovery.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """Which commands may run in the default home when the sticky ``active_profile`` is gone.
  2. ``_apply_profile_override`` fails closed when ``active_profile`` names a deleted profile:
  3. running an ordinary command in the default profile would read or write the wrong profile's
  4. state. The commands here are the way out of that state, so they must still reach their handler.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import contextlib
  9. import io
  10. def _uninstall_keeps_data(args: list[str]) -> bool:
  11. """True when ``uninstall <args>`` removes no user data.
  12. Parsed with the real ``uninstall`` subparser so abbreviations (``--dat``, ``--fu``) resolve
  13. exactly as they will for the handler. ``--full`` wipes the default root, which also holds
  14. every other profile under ``profiles/``, without asking, so it is refused like ``--data``.
  15. The plain interactive menu still offers a full wipe, but only behind its own confirmations.
  16. """
  17. from hermes_cli.subcommands.uninstall import build_uninstall_parser
  18. parser = argparse.ArgumentParser(add_help=False)
  19. build_uninstall_parser(parser.add_subparsers(dest="command"), cmd_uninstall=lambda _args: None)
  20. # The real parser prints help/usage errors once the handler runs; this probe stays silent.
  21. # --help exits 0 (harmless, let it through); an unparseable argv fails closed.
  22. with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
  23. try:
  24. ns, _ = parser.parse_known_args(["uninstall", *args])
  25. except SystemExit as exit_:
  26. return exit_.code == 0
  27. return not (ns.data or ns.full)
  28. def is_stale_profile_recovery_command(argv: list[str]) -> bool:
  29. """``profile list``, ``profile use default``, or an ``uninstall`` that keeps user data."""
  30. from hermes_cli._parser import command_argv
  31. command = command_argv(argv)
  32. if command[:2] == ["profile", "list"]:
  33. return True
  34. if command[:2] == ["profile", "use"]:
  35. return len(command) > 2 and command[2].casefold() == "default"
  36. return command[:1] == ["uninstall"] and _uninstall_keeps_data(command[1:])