API Reference¶
Data Models¶
sawmill.models.message¶
Message and FileRef data models for sawmill.
These models represent the core data structures for log messages. Plugins create Message instances; the base app is just an orchestrator.
Both are plain @dataclass(slots=True) types. Pydantic validation overhead was removed in PR2 — at 1M messages it cost ~1 KB extra resident memory per object and gave no value, since plugins build messages from their own regex matches and don’t need runtime field coercion.
- class sawmill.models.message.FileRef(path, line=None)¶
Bases:
objectReference to a source file location extracted from a log message.
- class sawmill.models.message.Message(start_line, end_line, raw_text, content, severity=None, message_id=None, category=None, file_ref=None, metadata=dict(), log_path=None)¶
Bases:
objectA logical log message (single or multi-line).
Plugins handle grouping of multi-line messages and create Message instances. The base app operates on these as complete logical units.
- Variables:
start_line (
int) – First line number in the source log file (1-indexed).end_line (
int) – Last line number in the source log file (1-indexed).raw_text (
str) – Complete original text including all lines.content (
str) – Extracted/cleaned message content.severity (
str|None) – Severity level (e.g., “error”, “warning”, “info”, “critical_warning”).message_id (
str|None) – Tool-specific message ID (e.g., “Vivado 12-3523”).category (
str|None) – Optional category for grouping (e.g., “timing”, “drc”).file_ref (
FileRef|None) – Optional reference to source file mentioned in message.metadata (
dict[str,str]) – Plugin-specific metadata for custom grouping/filtering. Plugins can populate this with tool-specific fields like “hierarchy”, “phase”, “clock_domain”, etc.log_path (
str|None) – Project-relative POSIX path of the log this message came from (absolute POSIX path if outside the project root). Set by the target runner; None when unknown.
- Parameters:
- matches_filter(pattern, case_sensitive=True)¶
Check if this message matches the given regex pattern.
Matches are performed against the raw_text (full original message).
- get_field_value(field_id)¶
Get the value of a field by its ID.
This method supports both builtin fields and metadata fields, allowing plugins to define custom grouping dimensions.
sawmill.models.plugin_api¶
Data models for plugin API definitions.
This module provides structured models for plugin-defined metadata such as severity levels and grouping fields.
- class sawmill.models.plugin_api.SeverityLevel(*, id, name, level=0, style='')¶
Bases:
BaseModelDefinition of a severity level.
Plugins use this to declare their severity levels in order from most to least severe. This allows the base app to properly order and style messages regardless of the tool’s naming conventions.
- Level numbering contract:
Levels MUST be consecutive integers starting at 0. Level 0 is the lowest severity (informational/note). Higher numbers indicate more severe levels.
- Variables:
- Parameters:
- class sawmill.models.plugin_api.GroupingField(*, id, name, field_type='builtin', description='', sort_order=None)¶
Bases:
BaseModelDefinition of a field available for grouping messages.
Plugins use this to declare what dimensions are available for grouping and sorting messages.
- Variables:
id (
str) – Field identifier (used in CLI as –group-by value).name (
str) – Human-readable display name.field_type – How to extract the value from a Message: - “builtin”: Use Message.severity, Message.message_id, etc. - “metadata”: Use Message.metadata[id] - “file_ref”: Use Message.file_ref.path
description (
str) – Optional description for help text.sort_order (
list[str] |None) – Optional list of values for custom sort ordering.
- Parameters:
- sawmill.models.plugin_api.severity_levels_from_dicts(dicts)¶
Convert a list of dictionaries to SeverityLevel objects.
sawmill.models.rule¶
Rule models for the manifest and rules design.
A rule file targets one plugin and holds a list of rules. Each rule names
match keys (id, regex, file, logs, severity), optional
limits (max_count, per) and a required comment.
- class sawmill.models.rule.Rule(*, id=None, regex=None, file=None, logs=None, severity=None, max_count=None, per='log', comment, author=None, date=None, name=None, source=None, index=0, line=None)¶
Bases:
BaseModelA single rule from a rule file.
Identity is
(source, index).source,indexandlineare provenance fields filled in by the loader.- Parameters:
- class sawmill.models.rule.RuleFile(*, plugin, rules=[], path=None)¶
Bases:
BaseModelA parsed rule file: target plugin plus its rules.
sawmill.models.filter_def¶
FilterDefinition data model for sawmill.
This model represents filter patterns that can be applied to log messages.
- class sawmill.models.filter_def.FilterDefinition(*, id, name, pattern, source=None, description=None)¶
Bases:
BaseModelA filter pattern with metadata.
Plugins can provide filter definitions, and users can also create them. Filters are applied by the FilterEngine to select matching messages.
- Variables:
id (
str) – Unique identifier for the filter.name (
str) – Human-readable name for display.pattern (
str) – Regular expression pattern to match.source (
str|None) – Origin of the filter (e.g., “plugin:vivado”, “config”, “user”).description (
str|None) – Optional description of what this filter matches.
- Parameters:
- classmethod validate_regex(v)¶
Validate that the pattern is a valid regular expression.
Plugin Interface¶
sawmill.plugin.hookspec¶
Hook specifications for sawmill plugins.
This module defines the pluggy hook specification that plugins must implement. Plugins use the @hookimpl decorator to register their implementations.
- class sawmill.plugin.hookspec.SawmillHookSpec¶
Bases:
objectHook specification defining the plugin interface.
Plugins implement these hooks to provide log parsing capabilities. The base application calls these hooks through the pluggy PluginManager.
- can_handle(path)¶
Determine if this plugin can handle the given log file.
Plugins should examine the file (name, initial content, etc.) and return a confidence score indicating how well they can parse it.
- Parameters:
path (
Path) – Path to the log file to check.- Returns:
0.0: Cannot handle this file
0.5: Might be able to handle (ambiguous)
1.0: Definitely can handle this file
The plugin with the highest confidence score will be selected. If no plugin has confidence > 0.5, an error is raised.
- Return type:
- load_and_parse(path)¶
Load and parse the log file into messages.
This is the primary parsing hook. Plugins MUST be generators (or otherwise return an iterator) so the base app can stream large logs without holding every line in memory at once.
Implementations should:
Open the file and stream line-by-line (
for line in f, notf.readlines()) so memory is O(in-flight message), not O(file).Parse each line/section into logical messages.
Group multi-line messages into single Message objects.
Extract severity, message IDs, and other metadata.
yieldeach completed Message as soon as it is built.
- get_filters()¶
Get filter definitions provided by this plugin.
Plugins can provide pre-defined filters for common use cases, such as filtering by severity level or message category.
- Return type:
- Returns:
List of FilterDefinition objects that users can enable/disable.
- extract_file_reference(content)¶
Extract a file reference from message content.
Many log messages reference source files with line numbers. This hook extracts that information for navigation.
- get_severity_levels()¶
REQUIRED: Get severity levels supported by this plugin.
Plugins MUST implement this hook to define their severity levels. The base app uses these levels for:
Filtering messages by severity in the TUI
Sorting and grouping messages
Styling output (colours in the terminal)
Determining pass/fail in
sawmill check(fail_on)
Level numbering contract: plugins MUST use consecutive integers starting at 0. Level 0 is the lowest severity (informational/note). Higher numbers indicate more severe levels.
- Return type:
- Returns:
List of severity definitions with these fields:
[ { "id": "fatal", # Internal identifier (lowercase) "name": "Fatal", # Display name "style": "red bold", # Rich style for display "level": 3, # Numeric level (0 = lowest) }, {"id": "error", "name": "Error", "style": "red", "level": 2}, {"id": "warning", "name": "Warning", "style": "yellow", "level": 1}, {"id": "note", "name": "Note", "style": "cyan", "level": 0}, ]
The numeric
levelfield is used for threshold comparisons:sawmill checkdefaults to failing on the second-lowest level and above, andfail_onsets the threshold to that severity’s level.- Raises:
NotImplementedError – If not implemented by the plugin.
- get_grouping_fields()¶
Get fields available for grouping and sorting.
Plugins can declare what dimensions are available for grouping messages. This includes both standard fields (severity, id, file) and custom metadata fields populated by the plugin.
Standard field types:
"builtin": Uses Message attributes (severity, message_id, category)"metadata": UsesMessage.metadata[field_id]"file_ref": UsesMessage.file_ref.path
If not implemented, the base app provides default groupings: severity, id, file, category.
- Return type:
- Returns:
List of field definitions:
[ { "id": "severity", # Field identifier "name": "Severity", # Display name "type": "builtin", # "builtin", "metadata", or "file_ref" "description": "Group by message severity level", }, { "id": "hierarchy", "name": "Design Hierarchy", "type": "metadata", # Uses Message.metadata["hierarchy"] "description": "Group by RTL hierarchy path", }, ]
- configure(options)¶
Configure the plugin for one target before any log is parsed.
Optional hook. The base app calls it once per manifest target, before loading any log, with the target’s
plugin_optionstable from the manifest (an empty dict when the target gives none, so a plugin can reset state between targets).Plugins should validate the options and raise
ValueErrorwith a clear message for unknown keys or bad values.
Core Modules¶
sawmill.core.filter¶
FilterEngine for applying regex filters to log messages.
This module provides the core filtering logic that operates on plugin output. The FilterEngine applies regex filters to messages.
- class sawmill.core.filter.FilterEngine¶
Bases:
objectEngine for applying regex filters to log messages.
The FilterEngine operates on lists of Message objects provided by plugins. It supports single filter matching and multi-filter combinations (AND/OR modes).
- apply_filter(pattern, messages, case_sensitive=True)¶
Apply a single regex filter to messages.
- Parameters:
- Return type:
- Returns:
List of messages that match the pattern. Returns empty list if pattern is invalid regex.
- apply_filters(filters, messages, mode='AND', active_ids=None)¶
Apply multiple filters to messages with AND or OR logic.
- Parameters:
- Return type:
- Returns:
List of messages that match according to the mode. If no active filters, returns all messages.
- sawmill.core.filter.filter_by_severity_toggles(messages, toggles)¶
Filter messages by severity toggle state.
Messages with None severity are always included. Severity IDs not present in toggles default to True (visible).
- sawmill.core.filter.match_message_id(message_id, pattern)¶
Check if a message ID matches a pattern (supports wildcards).
Uses fnmatch for glob-style pattern matching:
*matches any sequence of characters?matches any single character
sawmill.core.aggregation¶
Aggregation and grouping utilities for messages.
This module provides classes for aggregating messages by severity, ID, file, or category - useful for summary views and grouped output.
The Aggregator class can be configured with plugin-provided severity levels and grouping fields for tool-specific customization.
- sawmill.core.aggregation.make_severity_sort_key(severity_levels)¶
Create a severity sort key function.
- Parameters:
severity_levels (
list[SeverityLevel]) – List of severity levels from plugin. Required.- Returns:
A function that returns a sort key for a severity string.
- Raises:
ValueError – If severity_levels is empty.
- class sawmill.core.aggregation.MessageStats(key, severity=None, count=0, messages=list(), files_affected=set(), by_log=dict())¶
Bases:
objectStatistics for messages grouped by a key.
- Variables:
key (
str) – The grouping key (ID, file, category, or severity).severity (
str|None) – The severity level for this group (if grouping by ID/file/category).count (
int) – Number of messages in this group.messages (
list) – List of messages in this group.files_affected (
set) – Set of unique files affected by messages in this group.by_log (
dict[str,int]) – Message counts per log path (messages without a log are not counted).
- Parameters:
- class sawmill.core.aggregation.SeverityStats(severity, total=0, by_id=dict())¶
Bases:
objectStatistics for a severity level with breakdown by message ID.
- Variables:
- Parameters:
- class sawmill.core.aggregation.Aggregator(severity_levels, grouping_fields=None)¶
Bases:
objectAggregate messages for summary and grouped views.
This class provides methods to group messages by various fields and compute statistics for display. It must be configured with plugin-provided severity levels for proper severity ordering and styling.
- Variables:
severity_levels – List of severity level definitions from plugin. Required.
grouping_fields – List of grouping field definitions from plugin.
- Parameters:
severity_levels (list[SeverityLevel])
grouping_fields (list[GroupingField] | None)
- get_available_groupings()¶
Get list of field IDs available for grouping.
- get_grouping_field(field_id)¶
Get a grouping field definition by ID.
- Parameters:
field_id (
str) – The field identifier.- Return type:
- Returns:
GroupingField if found, None otherwise.
- get_severity_style(severity)¶
Get the display style for a severity level.
- get_severity_name(severity)¶
Get the display name for a severity level.
- get_summary(messages)¶
Get summary statistics grouped by severity with ID breakdown.
- Parameters:
- Return type:
- Returns:
Dictionary mapping severity to SeverityStats.
- group_by_field(messages, field_id)¶
Group messages by any field (builtin or metadata).
This is the generic grouping method that uses Message.get_field_value() to support both builtin fields and plugin-defined metadata fields.
- group_by_severity(messages)¶
Group messages by severity level.
- Parameters:
- Return type:
- Returns:
Dictionary mapping severity to MessageStats.
- group_by_id(messages)¶
Group messages by message ID.
- Parameters:
- Return type:
- Returns:
Dictionary mapping message ID to MessageStats.
- group_by_file(messages)¶
Group messages by source file.
Messages without file references are grouped under “(no file)”.
- Parameters:
- Return type:
- Returns:
Dictionary mapping file path to MessageStats.
- group_by_category(messages)¶
Group messages by category.
Messages without categories are grouped under “(no category)”.
- Parameters:
- Return type:
- Returns:
Dictionary mapping category to MessageStats.
- group_by(messages, field)¶
Group messages by the specified field.
This method supports both builtin fields and plugin-defined metadata fields. For builtin fields, it uses optimized methods. For metadata fields, it uses the generic group_by_field() method.
- Parameters:
- Return type:
- Returns:
Dictionary mapping field value to MessageStats.
- Raises:
ValueError – If the field is not a builtin field and not in the plugin-provided grouping fields.
- sorted_groups(groups, by_count=True)¶
Sort groups for display.
- Parameters:
groups (
dict[str,MessageStats]) – Dictionary of groups to sort.by_count (
bool) – If True, sort by count descending. If False, sort by key.
- Return type:
list[tuple[str,MessageStats]]- Returns:
List of (key, stats) tuples in sorted order.
- sorted_summary(summary)¶
Sort summary by severity order.
Uses plugin-provided severity levels if available, otherwise uses default ordering.
- Parameters:
summary (
dict[str,SeverityStats]) – Summary dictionary to sort.- Return type:
- Returns:
List of (severity, stats) tuples in severity order.
sawmill.core.rules¶
Rule file loading and validation.
Rule files are TOML with a [rules] header table and [[rule]] entries.
Every error is reported as RuleValidationError with the file path,
line number and rule index where they are known.
- exception sawmill.core.rules.RuleValidationError(message, line=None, path=None, rule_index=None)¶
Bases:
ExceptionException raised for rule file validation errors.
- class sawmill.core.rules.RuleLoader¶
Bases:
objectLoads and validates rule files.
- load(path)¶
Load rules from a TOML file.
- Parameters:
path (
Path) – Path to the rule file- Return type:
- Returns:
RuleFile with parsed rules
- Raises:
FileNotFoundError – If the file does not exist
RuleValidationError – If the file is invalid
- sawmill.core.rules.append_rule(path, rule, plugin)¶
Append one
[[rule]]block to a rule file, preserving its content.The file is created with a
[rules]header when missing. Existing content and comments are kept, the write is atomic, and the result is reloaded to validate it.- Parameters:
- Raises:
RuleValidationError – If the file belongs to another plugin, is not valid TOML, or is invalid after the append.
- Return type:
sawmill.core.config¶
Configuration loading and parsing for sawmill.
This module provides the ConfigLoader class for reading TOML configuration files and the Config dataclass for storing configuration values.
- exception sawmill.core.config.ConfigError(message, line=None, path=None)¶
Bases:
ExceptionException raised for configuration parsing errors.
- class sawmill.core.config.GeneralConfig(default_plugin=None, roots=list())¶
Bases:
objectGeneral configuration settings.
- classmethod from_dict(data)¶
Create GeneralConfig from a dictionary.
- Raises:
ConfigError – If
rootsis not a list of strings.- Return type:
- Parameters:
data (dict)
- class sawmill.core.config.OutputConfig(color=True, format='text')¶
Bases:
objectOutput configuration settings.
- class sawmill.core.config.Config(general=GeneralConfig(), output=OutputConfig())¶
Bases:
objectComplete sawmill configuration.
- Variables:
general (
GeneralConfig) – General settings like default_pluginoutput (
OutputConfig) – Output settings like color and format
- Parameters:
general (GeneralConfig)
output (OutputConfig)
- general: GeneralConfig¶
- output: OutputConfig¶
- class sawmill.core.config.ConfigLoader¶
Bases:
objectLoader for sawmill TOML configuration files.
- Example usage:
loader = ConfigLoader() config = loader.load(Path(“sawmill.toml”))
# Or load defaults when no file exists config = loader.load(None)
# Or load the user config (~/.config/sawmill/config.toml) config = loader.load_resolved()
- load(path)¶
Load configuration from a TOML file.
- Parameters:
path (
Path|None) – Path to the TOML configuration file, or None to use defaults- Return type:
- Returns:
Config instance with values from file or defaults
- Raises:
ConfigError – If the file exists but contains invalid TOML
FileNotFoundError – If the path is specified but file doesn’t exist
- load_resolved()¶
Load the user configuration (~/.config/sawmill/config.toml).
Project-level configuration lives in the manifest, not here.
- Return type:
- Returns:
Config instance from the user config, or defaults if absent.
- Raises:
ConfigError – If the user config contains invalid TOML.
sawmill.core.manifest¶
Manifest loading and validation.
Manifests are TOML with a [manifest] table and [[target]] entries.
Every error is reported as ManifestError with the file path, line
number and target index where they are known.
- exception sawmill.core.manifest.ManifestError(message, line=None, path=None, target_index=None)¶
Bases:
ExceptionException raised for manifest validation errors.
- class sawmill.core.manifest.ManifestLoader¶
Bases:
objectLoads and validates manifest files.
- load(path)¶
Load a manifest from a TOML file.
- Parameters:
path (
Path) – Path to the manifest- Return type:
Manifest- Returns:
Manifest with
pathset to the resolved file path- Raises:
FileNotFoundError – If the file does not exist
ManifestError – If the file is invalid
- load_from_string(content, path=None)¶
Load a manifest from a TOML string.
- Parameters:
- Return type:
Manifest- Returns:
Parsed Manifest
- Raises:
ManifestError – If the content is invalid
sawmill.core.plugin¶
Plugin management for sawmill.
This module provides the PluginManager class that handles plugin discovery via Python entry points and registration with pluggy.
- sawmill.core.plugin.load_messages(plugin, path)¶
Call
plugin.load_and_parse(path)and return an iterator.Plugin API 2 returns an iterator; legacy (API 1) plugins return a list. Wrapping in
iter()lets both work and passes iterators through unchanged.
- sawmill.core.plugin.plugin_implements_configure(plugin)¶
Return True when
pluginoverridesSawmillPlugin.configure().
- exception sawmill.core.plugin.PluginError¶
Bases:
ExceptionBase exception for plugin-related errors.
- exception sawmill.core.plugin.PluginConflictError¶
Bases:
PluginErrorRaised when multiple plugins both claim high confidence for a file.
- exception sawmill.core.plugin.NoPluginFoundError¶
Bases:
PluginErrorRaised when no plugin can handle a file.
- class sawmill.core.plugin.PluginManager¶
Bases:
objectManages plugin discovery and registration.
This class handles:
Discovering plugins via Python entry points
Registering plugins with pluggy
Listing available plugins
Calling plugin hooks
Example:
manager = PluginManager() manager.discover() # Find and register entry point plugins manager.register(MyPlugin()) # Manually register a plugin # List available plugins for name in manager.list_plugins(): print(name) # Call hooks results = manager.pm.hook.can_handle(path=Path("test.log"))
- register(plugin)¶
Register a plugin instance.
- Parameters:
plugin (
SawmillPlugin) – The plugin instance to register.- Return type:
- unregister(name)¶
Unregister a plugin by name.
- discover()¶
Discover and register plugins from entry points.
Scans the ‘sawmill.plugins’ entry point group and registers any plugins found.
- list_plugins()¶
List all registered plugin names.
- get_plugin(name)¶
Get a plugin by name.
- get_plugin_info(name)¶
Get information about a plugin.
- auto_detect(path)¶
Automatically detect the appropriate plugin for a file.
Calls the can_handle hook on all registered plugins and selects the one with the highest confidence score.
- Parameters:
path (
Path) – Path to the log file to analyze.- Return type:
- Returns:
Name of the plugin with highest confidence (>= 0.5).
- Raises:
NoPluginFoundError – If no plugin has confidence >= 0.5.
PluginConflictError – If multiple plugins have confidence >= 0.5.
- sawmill.core.plugin.select_plugin(manager, plugin_name, path)¶
Select the appropriate plugin for a log file.
If plugin_name is given, looks it up by name. Otherwise, auto-detects from the file.
- Parameters:
manager (
PluginManager) – The plugin manager with registered plugins.plugin_name (
str|None) – Explicit plugin name, or None for auto-detect.path (
Path) – Path to the log file.
- Return type:
SawmillPlugin- Returns:
The selected plugin instance.
- Raises:
NoPluginFoundError – If the named plugin doesn’t exist or no plugin can handle the file.
PluginConflictError – If multiple plugins claim the file.
- sawmill.core.plugin.get_plugin_manager()¶
Create and configure the plugin manager.
Discovers plugins via entry points (including built-in plugins registered in pyproject.toml).
- Return type:
- Returns:
Configured PluginManager instance.
sawmill.core.severity¶
Severity-level helpers for sawmill.
Provides functions to query and compare severity levels from plugins. These are used by both the CLI and TUI layers.
- sawmill.core.severity.get_severity_levels(plugin)¶
Get severity levels from plugin.
- Parameters:
plugin – The plugin instance to get levels from.
- Returns:
List of SeverityLevel objects.
- Raises:
RuntimeError – If plugin doesn’t implement get_severity_levels().
- sawmill.core.severity.get_severity_style_map(plugin)¶
Build a severity style map from plugin’s severity levels.
- sawmill.core.severity.get_severity_style(severity, style_map)¶
Get the Rich style for a given severity level.
- sawmill.core.severity.get_severity_level_map(plugin)¶
Build a severity level map from plugin’s severity levels.
- sawmill.core.severity.severity_at_or_above(message_severity, min_severity, level_map)¶
Check if message severity is at or above the minimum level.
- sawmill.core.severity.resolve_fail_on_level(fail_on, severity_levels)¶
Resolve a fail-on severity name to its numeric level.
- Parameters:
fail_on (
str|None) – Severity id, or None for the default.severity_levels (
list[SeverityLevel]) – Severity levels defined by the plugin.
- Return type:
- Returns:
Numeric level threshold. The default is the second-lowest level, or the only level if the plugin defines just one.
- Raises:
ValueError – If
fail_onis not a severity id defined by the plugin.