sizefmt.py 719 B

1234567891011121314151617181920
  1. """Small shared size-formatting helpers for CLI/agent output (sibling of ``hermes_cli.timefmt``:
  2. a tiny purpose-named module lightweight consumers can import without the CLI surface)."""
  3. from __future__ import annotations
  4. def format_bytes(n) -> str:
  5. """1234567 -> '1.2 MB' (B/KB/MB/GB/TB; integer bytes, one decimal above). Returns ``"?"`` for
  6. None or unparseable input so display call sites never raise."""
  7. try:
  8. size = float(n)
  9. except (TypeError, ValueError):
  10. return "?"
  11. if size < 1024:
  12. return f"{int(size)} B"
  13. for unit in ("KB", "MB", "GB"):
  14. size /= 1024.0
  15. if size < 1024:
  16. return f"{size:.1f} {unit}"
  17. return f"{size / 1024.0:.1f} TB"