Coverage for src/local_deep_research/utilities/formatting.py: 100%

8 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-22 21:20 +0000

1"""Shared formatting utilities.""" 

2 

3 

4def human_size(size_bytes: float) -> str: 

5 """Convert bytes to human-readable size string. 

6 

7 Args: 

8 size_bytes: Size in bytes. 

9 

10 Returns: 

11 Human-readable string like "247.0 MB" or "1.5 GB". 

12 """ 

13 for unit in ("B", "KB", "MB", "GB", "TB", "PB"): 

14 if abs(size_bytes) < 1024: 

15 return f"{size_bytes:.1f} {unit}" 

16 size_bytes /= 1024 

17 return f"{size_bytes:.1f} EB" 

18 

19 

20def short_id(value: str, n: int = 8) -> str: 

21 """Render an id for log messages without a misleading ellipsis. 

22 

23 An id longer than ``n`` characters shortens to its first ``n`` 

24 characters followed by ``...``. An id that is already at most ``n`` 

25 characters (for example a short test fixture id) renders as-is, so an 

26 operator can trust that ``...`` really means truncation (#5583). 

27 

28 Use this instead of an inline ``f"{some_id[:8]}..."``: the slice alone 

29 cannot tell a truncated id from one that was never truncated. 

30 

31 Args: 

32 value: The id to render; it must be a ``str``. 

33 n: How many leading characters to keep. 

34 

35 Returns: 

36 ``value`` itself when it has at most ``n`` characters, otherwise its 

37 first ``n`` characters followed by ``...``. 

38 """ 

39 return value[:n] + ("..." if len(value) > n else "")