main_query_file.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. """``--query-file``: the single-query transport that never passes through a shell.
  2. Split out of ``hermes_cli/main.py``.
  3. """
  4. import sys
  5. def _read_query_file(args) -> None:
  6. """--query-file: read the single query from a file (or stdin via '-').
  7. Callers never have to shell-quote message bodies — this is the transport
  8. the Bot Mode DM protocol uses; interpolating arbitrary text into a
  9. double-quoted shell argument truncates on quotes and executes $(...)
  10. (see tools/bot_mode_probe.py).
  11. """
  12. _qfile = getattr(args, "query_file", None)
  13. if not _qfile:
  14. return
  15. if args.query:
  16. # argparse's mutually-exclusive group catches the normal CLI path;
  17. # this guards programmatic callers that fill the namespace directly.
  18. print("Error: -q/--query and --query-file are mutually exclusive", file=sys.stderr)
  19. sys.exit(2)
  20. try:
  21. if _qfile == "-":
  22. args.query = sys.stdin.read()
  23. else:
  24. with open(_qfile, "r", encoding="utf-8-sig", errors="replace") as _fh:
  25. args.query = _fh.read()
  26. except OSError as _e:
  27. print(f"Error: cannot read --query-file {_qfile}: {_e}", file=sys.stderr)
  28. sys.exit(2)
  29. if not (args.query or "").strip():
  30. print(f"Error: --query-file {_qfile} is empty", file=sys.stderr)
  31. sys.exit(2)