or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ast-visitor.mdbadge-generation.mdcli-interface.mdconfiguration.mdcoverage-analysis.mdindex.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Collection of general helper functions, constants, and formatting utilities used throughout interrogate. These utilities provide file handling, path manipulation, regex compilation, and output formatting capabilities.

3

4

## Capabilities

5

6

### Constants

7

8

Platform and configuration constants used across the package.

9

10

```python { .api }

11

IS_WINDOWS = sys.platform == "win32" # Windows platform detection

12

```

13

14

### Regex Utilities

15

16

Click callback function for compiling regular expression patterns from CLI options.

17

18

```python { .api }

19

def parse_regex(ctx, param, values):

20

"""

21

Compile regular expressions from CLI input.

22

23

Args:

24

ctx: Click command context

25

param: Click command parameter (ignore_regex or whitelist_regex)

26

values: List of regular expression strings to compile

27

28

Returns:

29

List of compiled regular expression objects, or None if no values

30

"""

31

```

32

33

### File Handling

34

35

Context manager for unified file and stdout handling.

36

37

```python { .api }

38

@contextlib.contextmanager

39

def smart_open(filename=None, fmode=None):

40

"""

41

Context manager to handle both stdout and files uniformly.

42

43

Args:

44

filename: Filename to open, or None/"-" for stdout

45

fmode: File mode for opening (e.g., "w", "r")

46

47

Yields:

48

File handle or sys.stdout

49

"""

50

```

51

52

### Path Utilities

53

54

Functions for path manipulation and common base directory calculation.

55

56

```python { .api }

57

def get_common_base(files):

58

"""

59

Find the common parent base path for a list of files.

60

61

Args:

62

files: Iterable of file paths

63

64

Returns:

65

Common parent path as string

66

"""

67

```

68

69

### Output Formatting

70

71

Complete output formatting class for terminal display with color support.

72

73

```python { .api }

74

class OutputFormatter:

75

"""Interrogate results formatter with terminal-aware output."""

76

77

# Class constants

78

TERMINAL_WIDTH: int # Computed terminal width

79

TABLE_SEPARATOR = ["---"]

80

81

def __init__(self, config, file=None):

82

"""

83

Initialize formatter with configuration.

84

85

Args:

86

config: InterrogateConfig instance

87

file: Optional file handle for output

88

"""

89

90

def should_markup(self):

91

"""

92

Determine if color markup should be applied to output.

93

94

Returns:

95

bool: True if colors should be used

96

"""

97

98

def set_detailed_markup(self, padded_cells):

99

"""

100

Add color markup to detailed output rows.

101

102

Args:

103

padded_cells: List of formatted table cells

104

105

Returns:

106

List of cells with color markup applied

107

"""

108

109

def set_summary_markup(self, padded_cells):

110

"""

111

Add color markup to summary output rows.

112

113

Args:

114

padded_cells: List of formatted table cells

115

116

Returns:

117

List of cells with color markup applied

118

"""

119

120

def get_table_formatter(self, table_type):

121

"""

122

Get tabulate table formatter for specified output type.

123

124

Args:

125

table_type: "detailed" or "summary"

126

127

Returns:

128

tabulate.TableFormat instance

129

"""

130

```

131

132

## Usage Examples

133

134

### Regex Pattern Compilation

135

136

```python

137

import click

138

from interrogate.utils import parse_regex

139

140

# Simulating CLI callback usage

141

@click.command()

142

@click.option('--ignore-regex', multiple=True, callback=parse_regex)

143

def analyze(ignore_regex):

144

# ignore_regex is now a list of compiled regex objects

145

for pattern in ignore_regex or []:

146

if pattern.match("some_function_name"):

147

print("Function matches ignore pattern")

148

```

149

150

### File Output Handling

151

152

```python

153

from interrogate.utils import smart_open

154

155

# Write to file or stdout uniformly

156

with smart_open("output.txt", "w") as f:

157

f.write("Coverage results\\n")

158

159

# Output to stdout when filename is None or "-"

160

with smart_open(None) as f:

161

f.write("Results to console\\n")

162

163

# stdout when using "-"

164

with smart_open("-") as f:

165

f.write("Also to console\\n")

166

```

167

168

### Path Utilities

169

170

```python

171

from interrogate.utils import get_common_base

172

173

# Find common base path

174

files = [

175

"/usr/src/myproject/main.py",

176

"/usr/src/myproject/utils.py",

177

"/usr/src/myproject/submodule/helper.py"

178

]

179

180

base_path = get_common_base(files)

181

print(base_path) # "/usr/src/myproject"

182

183

# Works with different depths

184

mixed_files = ["/usr/local/bin/script", "/usr/local/lib/module.py"]

185

base = get_common_base(mixed_files)

186

print(base) # "/usr/local"

187

```

188

189

### Output Formatting

190

191

```python

192

from interrogate.utils import OutputFormatter

193

from interrogate.config import InterrogateConfig

194

import sys

195

196

# Create formatter with configuration

197

config = InterrogateConfig(color=True, fail_under=80.0)

198

formatter = OutputFormatter(config, file=sys.stdout)

199

200

# Check if colors should be used

201

if formatter.should_markup():

202

print("Terminal supports color output")

203

204

# Get table formatter for different output types

205

detailed_formatter = formatter.get_table_formatter("detailed")

206

summary_formatter = formatter.get_table_formatter("summary")

207

208

# Use with tabulate for terminal-aware table formatting

209

import tabulate

210

211

data = [["file.py", "50", "25", "50%"]]

212

headers = ["File", "Total", "Missing", "Coverage"]

213

214

formatted_table = tabulate.tabulate(

215

data,

216

headers=headers,

217

tablefmt=detailed_formatter

218

)

219

print(formatted_table)

220

```

221

222

### Platform-Specific Handling

223

224

```python

225

from interrogate.utils import IS_WINDOWS

226

227

if IS_WINDOWS:

228

# Handle Windows-specific terminal behavior

229

print("Running on Windows - adjusting output formatting")

230

else:

231

print("Running on Unix-like system")

232

```

233

234

### Advanced Formatting with Markup

235

236

```python

237

from interrogate.utils import OutputFormatter

238

from interrogate.config import InterrogateConfig

239

240

config = InterrogateConfig(color=True, fail_under=75.0)

241

formatter = OutputFormatter(config)

242

243

# Example detailed row (filename, line, type, name, status)

244

detailed_row = ["src/main.py", "42", "function", "calculate", "MISSED"]

245

marked_row = formatter.set_detailed_markup(detailed_row)

246

# Row will be colored red for missed docstring

247

248

# Example summary row (file, total, missing, covered, percentage)

249

summary_row = ["src/main.py", "10", "3", "7", "70%"]

250

marked_summary = formatter.set_summary_markup(summary_row)

251

# Row will be colored red since 70% < 75% threshold

252

```