0
# Badge Generation
1
2
Creates SVG and PNG badges displaying docstring coverage percentages. Supports multiple badge styles and automatic color coding based on coverage thresholds, ideal for displaying in README files and documentation.
3
4
## Capabilities
5
6
### Main Badge Creation
7
8
Primary function for creating coverage badges with automatic formatting and color selection.
9
10
```python { .api }
11
def create(
12
output: str,
13
result: BaseInterrogateResult,
14
output_format: Optional[str] = None,
15
output_style: Optional[str] = None
16
) -> str:
17
"""
18
Create a coverage badge and save to file.
19
20
Args:
21
output: Output file path or directory
22
result: Coverage results to display
23
output_format: Badge format ("svg" or "png", auto-detected from extension)
24
output_style: Badge style ("flat", "flat-square", "for-the-badge", "plastic")
25
26
Returns:
27
str: Path to created badge file
28
29
Raises:
30
OSError: If output directory is not writable
31
ValueError: If invalid format or style specified
32
"""
33
```
34
35
### Badge Content Generation
36
37
Functions for generating badge SVG content and determining appropriate colors.
38
39
```python { .api }
40
def get_badge(result, color, style=None):
41
"""
42
Generate SVG badge content.
43
44
Args:
45
result: Coverage percentage as float
46
color: Badge color (hex code or CSS color name)
47
style: Badge style ("flat", "flat-square", "flat-square-modified", "for-the-badge", "plastic", "social")
48
49
Returns:
50
str: SVG badge content as string
51
"""
52
53
def get_color(result):
54
"""
55
Get appropriate color for coverage percentage.
56
57
Args:
58
result: Coverage percentage as float
59
60
Returns:
61
str: Color hex code based on coverage threshold
62
"""
63
```
64
65
### Badge File Operations
66
67
Functions for saving badges and determining generation requirements.
68
69
```python { .api }
70
def save_badge(badge, output, output_format=None):
71
"""
72
Save badge content to file.
73
74
Args:
75
badge: SVG badge content
76
output: Output file path
77
output_format: Force format ("svg" or "png", auto-detected if None)
78
79
Raises:
80
ImportError: If PNG format requested but cairosvg not installed
81
OSError: If file cannot be written
82
"""
83
84
def should_generate_badge(output, color, result):
85
"""
86
Determine if badge should be generated based on output and results.
87
88
Args:
89
output: Output path or directory
90
color: Badge color
91
result: Coverage percentage as float
92
93
Returns:
94
bool: True if badge should be generated
95
"""
96
```
97
98
## Constants
99
100
```python { .api }
101
DEFAULT_FILENAME = "interrogate_badge"
102
103
COLORS = {
104
"brightgreen": "#4c1",
105
"green": "#97CA00",
106
"yellowgreen": "#a4a61d",
107
"yellow": "#dfb317",
108
"orange": "#fe7d37",
109
"red": "#e05d44",
110
"lightgrey": "#9f9f9f"
111
}
112
113
COLOR_RANGES = [
114
(95, "brightgreen"),
115
(90, "green"),
116
(75, "yellowgreen"),
117
(60, "yellow"),
118
(40, "orange"),
119
(0, "red")
120
]
121
122
SUPPORTED_OUTPUT_FORMATS = ["svg", "png"]
123
```
124
125
## Usage Examples
126
127
### Basic Badge Generation
128
129
```python
130
from interrogate.badge_gen import create
131
from interrogate.coverage import InterrogateCoverage
132
from interrogate.config import InterrogateConfig
133
134
# Run coverage analysis
135
config = InterrogateConfig(paths=["src/"])
136
coverage = InterrogateCoverage(config.paths, config)
137
results = coverage.get_coverage()
138
139
# Create SVG badge
140
badge_path = create("docs/coverage.svg", results)
141
print(f"Badge created: {badge_path}")
142
143
# Create PNG badge (requires cairosvg)
144
badge_path = create("docs/coverage.png", results, output_format="png")
145
print(f"PNG badge created: {badge_path}")
146
```
147
148
### Styled Badge Creation
149
150
```python
151
from interrogate.badge_gen import create
152
from interrogate.coverage import InterrogateCoverage
153
from interrogate.config import InterrogateConfig
154
155
config = InterrogateConfig(paths=["src/"])
156
coverage = InterrogateCoverage(config.paths, config)
157
results = coverage.get_coverage()
158
159
# Create badges with different styles
160
styles = ["flat", "flat-square", "for-the-badge", "plastic"]
161
for style in styles:
162
badge_path = create(f"docs/badge_{style}.svg", results, output_style=style)
163
print(f"Created {style} badge: {badge_path}")
164
```
165
166
### Custom Badge Content
167
168
```python
169
from interrogate.badge_gen import get_badge, get_color, save_badge
170
from interrogate.coverage import BaseInterrogateResult
171
172
# Create mock results
173
class MockResults(BaseInterrogateResult):
174
def __init__(self, percentage):
175
self.total = 100
176
self.covered = int(percentage)
177
self.missing = 100 - int(percentage)
178
self.perc_covered = percentage
179
180
# Generate custom badge
181
results = MockResults(87.5)
182
color = get_color(results) # Auto-select color based on percentage
183
badge_svg = get_badge(results, color, style="flat-square")
184
185
# Save to file
186
save_badge(badge_svg, "custom_badge.svg")
187
print(f"Custom badge created with {results.perc_covered}% coverage")
188
```
189
190
### Badge Generation with Color Override
191
192
```python
193
from interrogate.badge_gen import create, get_badge
194
from interrogate.coverage import InterrogateCoverage
195
from interrogate.config import InterrogateConfig
196
197
config = InterrogateConfig(paths=["src/"])
198
coverage = InterrogateCoverage(config.paths, config)
199
results = coverage.get_coverage()
200
201
# Create badge with custom color
202
badge_svg = get_badge(results, "#ff6b35", style="for-the-badge") # Custom orange
203
with open("docs/custom_color_badge.svg", "w") as f:
204
f.write(badge_svg)
205
206
# Available predefined colors
207
predefined_colors = ["brightgreen", "green", "yellowgreen", "yellow", "orange", "red", "lightgrey"]
208
for color in predefined_colors:
209
badge_svg = get_badge(results, color)
210
with open(f"docs/badge_{color}.svg", "w") as f:
211
f.write(badge_svg)
212
```
213
214
### Conditional Badge Generation
215
216
```python
217
from interrogate.badge_gen import should_generate_badge, create
218
from interrogate.coverage import InterrogateCoverage
219
from interrogate.config import InterrogateConfig
220
221
config = InterrogateConfig(paths=["src/"])
222
coverage = InterrogateCoverage(config.paths, config)
223
results = coverage.get_coverage()
224
225
# Only generate badge if needed
226
output_path = "docs/coverage.svg"
227
if should_generate_badge(output_path, "auto", results):
228
badge_path = create(output_path, results)
229
print(f"Badge generated: {badge_path}")
230
else:
231
print("Badge generation skipped")
232
```
233
234
### Integration with CI/CD
235
236
```python
237
import os
238
from interrogate.badge_gen import create
239
from interrogate.coverage import InterrogateCoverage
240
from interrogate.config import InterrogateConfig
241
242
def generate_coverage_badge():
243
"""Generate coverage badge for CI/CD pipeline."""
244
245
# Configure for CI environment
246
config = InterrogateConfig(
247
paths=["src/"],
248
ignore_init_method=True,
249
ignore_private=True,
250
fail_under=80.0
251
)
252
253
# Run analysis
254
coverage = InterrogateCoverage(config.paths, config)
255
results = coverage.get_coverage()
256
257
# Generate badge
258
badge_path = create("docs/coverage.svg", results, output_style="flat")
259
260
# Print results for CI logs
261
print(f"Coverage: {results.perc_covered:.1f}%")
262
print(f"Badge created: {badge_path}")
263
264
# Exit with error code if below threshold
265
if results.ret_code != 0:
266
print(f"Coverage {results.perc_covered:.1f}% below required {config.fail_under}%")
267
return results.ret_code
268
269
return 0
270
271
if __name__ == "__main__":
272
exit_code = generate_coverage_badge()
273
exit(exit_code)
274
```
275
276
### PNG Badge Generation
277
278
```python
279
from interrogate.badge_gen import create
280
from interrogate.coverage import InterrogateCoverage
281
from interrogate.config import InterrogateConfig
282
283
# Note: PNG generation requires cairosvg package
284
# Install with: pip install interrogate[png]
285
286
config = InterrogateConfig(paths=["src/"])
287
coverage = InterrogateCoverage(config.paths, config)
288
results = coverage.get_coverage()
289
290
try:
291
# Create PNG badge
292
badge_path = create("docs/coverage.png", results, output_format="png")
293
print(f"PNG badge created: {badge_path}")
294
except ImportError:
295
print("PNG generation requires cairosvg. Install with: pip install interrogate[png]")
296
# Fallback to SVG
297
badge_path = create("docs/coverage.svg", results)
298
print(f"SVG badge created instead: {badge_path}")
299
```