Coverage for /builds/svesch/cikit/src/cikit/badge.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-10-09 14:17 +0000

1# SPDX-License-Identifier: GPL-3.0-or-later 

2"""Badge utilities for cikit. 

3 

4Author: 

5 Sven Schlender 

6License: 

7 SPDX-License-Identifier: GPL-3.0-or-later 

8Date: 

9 2026-02-18 

10""" 

11 

12import logging 

13from pathlib import Path 

14from tempfile import TemporaryDirectory 

15 

16import anybadge 

17 

18from cikit.errors import CiToolsError 

19from cikit.artifacts import Artifact, ArtifactType 

20 

21 

22LOGGER = logging.getLogger(__name__) 

23BADGE_FILE_PATTERN = "%s.svg" 

24 

25def write_badge(env: object, name: str, *, label: str, value: str, # pylint: disable=too-many-arguments 

26 color: str = None, thresholds: dict = None) -> Artifact: 

27 """Create and register a badge SVG artifact. 

28 

29 The badge is created in a temporary working directory and then copied to 

30 the public badge artifact directory through the CI run environment. The 

31 badge producer therefore does not depend on the public directory layout. 

32 

33 Args: 

34 env: CiRunEnvironment used to copy and register the badge artifact. 

35 name: Badge file base name without extension. 

36 label: Left part of the badge. 

37 value: Right part of the badge. 

38 color: Fixed badge background color, mutually exclusive with thresholds. 

39 thresholds: Mapping of numeric threshold to color, mutually exclusive 

40 with color. 

41 

42 Returns: 

43 Created and registered badge artifact. 

44 

45 Raises: 

46 CiToolsError: If the badge configuration is invalid or the badge file 

47 cannot be created or registered. 

48 """ 

49 if color and thresholds: 

50 raise CiToolsError("Specify either 'color' or 'thresholds', not both.") 

51 

52 filename = BADGE_FILE_PATTERN % name 

53 

54 kwargs: dict = {"label": label, "value": value} 

55 if thresholds is not None: 

56 kwargs["thresholds"] = thresholds 

57 elif color is not None: 

58 kwargs["default_color"] = color 

59 

60 try: 

61 badge = anybadge.Badge(**kwargs) 

62 except (TypeError, ValueError) as exp: 

63 raise CiToolsError("Invalid badge configuration " 

64 f"(label={label!r}, value={value!r}).") from exp 

65 

66 with TemporaryDirectory() as temp_dir: 

67 filepath = Path(temp_dir) / filename 

68 

69 try: 

70 badge.write_badge(filepath, overwrite=True) 

71 except OSError as exp: 

72 raise CiToolsError(f"Failed to write badge file to '{filepath}'.") from exp 

73 

74 return env.copy_artifact(filepath, ArtifactType.BADGE)