Coverage for harbor_cli/output/formatting/builtin.py: 100%

24 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-02-09 12:09 +0100

1"""Formatting functions for builtin types.""" 

2from __future__ import annotations 

3 

4from typing import Any 

5from typing import Optional 

6from typing import Sequence 

7 

8from .constants import NONE_STR 

9 

10 

11def str_str(value: Optional[str]) -> str: 

12 """Format an optional string value as a string.""" 

13 return str(value if value is not None else NONE_STR) 

14 

15 

16def bool_str(value: Optional[bool], none_is_false: bool = True) -> str: 

17 """Format a boolean value as a string.""" 

18 # Harbor API sometimes has None signify False 

19 # Why? I don't know. 

20 if value is None and none_is_false: 

21 value = False 

22 return str(value).lower() if value is not None else NONE_STR 

23 

24 

25def float_str(value: Optional[float], precision: int = 2) -> str: 

26 """Format a float value as a string.""" 

27 if value is None: 

28 return NONE_STR 

29 return f"{value:.{precision}f}" 

30 

31 

32def int_str(value: Optional[int]) -> str: 

33 """Format an integer value as a string.""" 

34 if value is None: 

35 return NONE_STR 

36 return str(value) 

37 

38 

39def plural_str(value: str, sequence: Sequence[Any]) -> str: 

40 """Format a string as a pluralized string if a given sequence is 

41 not of length 1.""" 

42 if value.endswith("y"): 

43 plural_value = value[:-1] + "ies" 

44 else: 

45 plural_value = value + "s" 

46 return value if len(sequence) == 1 else f"{plural_value}"