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: object

Reference to a source file location extracted from a log message.

Parameters:
  • path (str)

  • line (int | None)

path: str
line: int | None
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: object

A 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:
start_line: int
end_line: int
raw_text: str
content: str
severity: str | None
message_id: str | None
category: str | None
file_ref: FileRef | None
metadata: dict[str, str]
log_path: str | None
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).

Parameters:
  • pattern (str) – Regular expression pattern to match.

  • case_sensitive (bool) – Whether to perform case-sensitive matching.

Return type:

bool

Returns:

True if the pattern matches, False otherwise.

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.

Parameters:

field_id (str) – The field identifier. Can be: - “severity”, “message_id”, “category” (builtin) - “file” (uses file_ref.path) - Any key in the metadata dict

Return type:

str | None

Returns:

The field value as a string, or None if not set.

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: BaseModel

Definition 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:
  • id (str) – Internal identifier (lowercase, e.g., “error”, “warning”).

  • name (str) – Human-readable display name (e.g., “Error”, “Warning”).

  • level (int) – Numeric level for comparison (0 = lowest, higher = more severe).

  • style (str) – Rich style string for terminal display.

Parameters:
model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
name: str
level: int
style: str
class sawmill.models.plugin_api.GroupingField(*, id, name, field_type='builtin', description='', sort_order=None)

Bases: BaseModel

Definition 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:
  • id (str)

  • name (str)

  • field_type (Literal['builtin', 'metadata', 'file_ref'])

  • description (str)

  • sort_order (list[str] | None)

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: str
name: str
field_type: Literal['builtin', 'metadata', 'file_ref']
description: str
sort_order: list[str] | None
sawmill.models.plugin_api.severity_levels_from_dicts(dicts)

Convert a list of dictionaries to SeverityLevel objects.

Parameters:

dicts (list[dict]) – List of dictionaries with severity level data.

Return type:

list[SeverityLevel]

Returns:

List of SeverityLevel objects.

sawmill.models.plugin_api.grouping_fields_from_dicts(dicts)

Convert a list of dictionaries to GroupingField objects.

Parameters:

dicts (list[dict]) – List of dictionaries with grouping field data.

Return type:

list[GroupingField]

Returns:

List of GroupingField 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: BaseModel

A single rule from a rule file.

Identity is (source, index). source, index and line are provenance fields filled in by the loader.

Parameters:
model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

id: Optional[str]
regex: Optional[str]
file: Optional[str]
logs: list[str] | None
severity: Optional[str]
max_count: Optional[int]
per: Literal['log', 'target']
comment: str
author: Optional[str]
date: Optional[str]
name: Optional[str]
source: Path | None
index: int
line: int | None
property display: str

<basename>#<n> or <basename>:<name>.

Type:

Short display form

match_keys()

Return the match keys present on this rule, for listing.

Return type:

dict[str, str | list[str]]

class sawmill.models.rule.RuleFile(*, plugin, rules=[], path=None)

Bases: BaseModel

A parsed rule file: target plugin plus its rules.

Parameters:
plugin: str
rules: list[Rule]
path: Path | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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: BaseModel

A 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:
  • id (str)

  • name (str)

  • pattern (str)

  • source (str | None)

  • description (str | None)

id: str
name: str
pattern: str
source: str | None
description: str | None
classmethod validate_regex(v)

Validate that the pattern is a valid regular expression.

Return type:

str

Parameters:

v (str)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

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: object

Hook 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:

float

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:

  1. Open the file and stream line-by-line (for line in f, not f.readlines()) so memory is O(in-flight message), not O(file).

  2. Parse each line/section into logical messages.

  3. Group multi-line messages into single Message objects.

  4. Extract severity, message IDs, and other metadata.

  5. yield each completed Message as soon as it is built.

Parameters:

path (Path) – Path to the log file to parse.

Yields:

Message – Message objects, each representing a complete logical message (single or multi-line). Messages should have start_line and end_line set correctly for multi-line messages.

Return type:

Iterator[Message]

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:

list[FilterDefinition]

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.

Parameters:

content (str) – The message content to search for file references.

Return type:

FileRef | None

Returns:

FileRef if a reference is found, None otherwise.

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:

list[dict]

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 level field is used for threshold comparisons: sawmill check defaults to failing on the second-lowest level and above, and fail_on sets 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": Uses Message.metadata[field_id]

  • "file_ref": Uses Message.file_ref.path

If not implemented, the base app provides default groupings: severity, id, file, category.

Return type:

list[dict]

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_options table 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 ValueError with a clear message for unknown keys or bad values.

Parameters:

options (dict) – The target’s plugin_options table.

Return type:

None

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: object

Engine 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:
  • pattern (str) – Regular expression pattern to match against message raw_text.

  • messages (list[Message]) – List of messages to filter.

  • case_sensitive (bool) – Whether to perform case-sensitive matching.

Return type:

list[Message]

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:
  • filters (list[FilterDefinition]) – List of filter definitions to apply.

  • messages (list[Message]) – List of messages to filter.

  • mode (Literal['AND', 'OR']) – “AND” requires all active filters to match, “OR” requires any active filter to match.

  • active_ids (set[str] | None) – Set of filter IDs to apply. If None, all filters are applied.

Return type:

list[Message]

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).

Parameters:
  • messages (list[Message]) – List of messages to filter.

  • toggles (dict[str, bool]) – Dict mapping severity ID to enabled state.

Return type:

list[Message]

Returns:

List of messages whose severity is enabled.

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

Parameters:
  • message_id (str | None) – The message ID to check (may be None).

  • pattern (str) – The pattern to match against (e.g. "Synth 8-*").

Return type:

bool

Returns:

True if the message ID matches the pattern.

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: object

Statistics 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:
key: str
severity: str | None = None
count: int = 0
messages: list
files_affected: set
by_log: dict[str, int]
add_message(message)

Add a message to this group.

Parameters:

message (Message) – The message to add.

Return type:

None

class sawmill.core.aggregation.SeverityStats(severity, total=0, by_id=dict())

Bases: object

Statistics for a severity level with breakdown by message ID.

Variables:
  • severity (str) – The severity level.

  • total (int) – Total count of messages at this severity.

  • by_id (dict) – Breakdown of counts by message ID.

Parameters:
severity: str
total: int = 0
by_id: dict
class sawmill.core.aggregation.Aggregator(severity_levels, grouping_fields=None)

Bases: object

Aggregate 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:
get_available_groupings()

Get list of field IDs available for grouping.

Return type:

list[str]

Returns:

List of field IDs that can be used with group_by().

get_grouping_field(field_id)

Get a grouping field definition by ID.

Parameters:

field_id (str) – The field identifier.

Return type:

GroupingField | None

Returns:

GroupingField if found, None otherwise.

get_severity_style(severity)

Get the display style for a severity level.

Parameters:

severity (str) – The severity level.

Return type:

str

Returns:

Rich style string from plugin, or empty string if not found.

get_severity_name(severity)

Get the display name for a severity level.

Parameters:

severity (str) – The severity level.

Return type:

str

Returns:

Display name, or title-cased severity if not found.

get_summary(messages)

Get summary statistics grouped by severity with ID breakdown.

Parameters:

messages (list[Message]) – List of messages to summarize.

Return type:

dict[str, SeverityStats]

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.

Parameters:
  • messages (list[Message]) – List of messages to group.

  • field_id (str) – The field to group by.

Return type:

dict[str, MessageStats]

Returns:

Dictionary mapping field value to MessageStats.

group_by_severity(messages)

Group messages by severity level.

Parameters:

messages (list[Message]) – List of messages to group.

Return type:

dict[str, MessageStats]

Returns:

Dictionary mapping severity to MessageStats.

group_by_id(messages)

Group messages by message ID.

Parameters:

messages (list[Message]) – List of messages to group.

Return type:

dict[str, MessageStats]

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:

messages (list[Message]) – List of messages to group.

Return type:

dict[str, MessageStats]

Returns:

Dictionary mapping file path to MessageStats.

group_by_category(messages)

Group messages by category.

Messages without categories are grouped under “(no category)”.

Parameters:

messages (list[Message]) – List of messages to group.

Return type:

dict[str, MessageStats]

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:
  • messages (list[Message]) – List of messages to group.

  • field (str) – The field to group by.

Return type:

dict[str, MessageStats]

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:

list[tuple[str, SeverityStats]]

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: Exception

Exception raised for rule file validation errors.

Variables:
  • message – Error description

  • line – Line number where error occurred (if available)

  • path – Path to the rule file (if available)

  • rule_index – 0-based index of the rule with the error (if available)

Parameters:
  • message (str)

  • line (int | None)

  • path (Path | None)

  • rule_index (int | None)

class sawmill.core.rules.RuleLoader

Bases: object

Loads and validates rule files.

load(path)

Load rules from a TOML file.

Parameters:

path (Path) – Path to the rule file

Return type:

RuleFile

Returns:

RuleFile with parsed rules

Raises:
load_from_string(content, path=None)

Load rules from a TOML string.

Parameters:
  • content (str) – TOML content

  • path (Path | None) – Optional path for provenance and error reporting

Return type:

RuleFile

Returns:

RuleFile with parsed rules

Raises:

RuleValidationError – If the content 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:
  • path (Path) – Rule file to append to.

  • rule (Rule) – The rule to append; provenance fields are not written.

  • plugin (str) – Plugin the file must belong to.

Raises:

RuleValidationError – If the file belongs to another plugin, is not valid TOML, or is invalid after the append.

Return type:

None

sawmill.core.rules.ensure_rule_file(path, plugin)

Create path with a [rules] header for plugin if it is missing.

An existing file is left untouched.

Parameters:
  • path (Path) – Rule file to create.

  • plugin (str) – Plugin the new file belongs to.

Return type:

None

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: Exception

Exception raised for configuration parsing errors.

Variables:
  • message – Error description

  • line – Line number where error occurred (if available)

  • path – Path to the config file (if available)

Parameters:
  • message (str)

  • line (int | None)

  • path (Path | None)

class sawmill.core.config.GeneralConfig(default_plugin=None, roots=list())

Bases: object

General configuration settings.

Parameters:
default_plugin: str | None = None
roots: list[str]
classmethod from_dict(data)

Create GeneralConfig from a dictionary.

Raises:

ConfigError – If roots is not a list of strings.

Return type:

GeneralConfig

Parameters:

data (dict)

class sawmill.core.config.OutputConfig(color=True, format='text')

Bases: object

Output configuration settings.

Parameters:
color: bool = True
format: str = 'text'
classmethod from_dict(data)

Create OutputConfig from a dictionary.

Return type:

OutputConfig

Parameters:

data (dict)

class sawmill.core.config.Config(general=GeneralConfig(), output=OutputConfig())

Bases: object

Complete sawmill configuration.

Variables:
  • general (GeneralConfig) – General settings like default_plugin

  • output (OutputConfig) – Output settings like color and format

Parameters:
general: GeneralConfig
output: OutputConfig
classmethod from_dict(data)

Create Config from a dictionary.

Parameters:

data (dict) – Dictionary parsed from TOML file

Return type:

Config

Returns:

Config instance with values from dictionary

class sawmill.core.config.ConfigLoader

Bases: object

Loader 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:

Config

Returns:

Config instance with values from file or defaults

Raises:
load_resolved()

Load the user configuration (~/.config/sawmill/config.toml).

Project-level configuration lives in the manifest, not here.

Return type:

Config

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: Exception

Exception raised for manifest validation errors.

Variables:
  • message – Error description

  • line – Line number where error occurred (if available)

  • path – Path to the manifest (if available)

  • target_index – 0-based index of the target with the error (if available)

Parameters:
  • message (str)

  • line (int | None)

  • path (Path | None)

  • target_index (int | None)

class sawmill.core.manifest.ManifestLoader

Bases: object

Loads 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 path set to the resolved file path

Raises:
load_from_string(content, path=None)

Load a manifest from a TOML string.

Parameters:
  • content (str) – TOML content

  • path (Path | None) – Optional manifest path for provenance and error reporting

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.

Return type:

Iterator[Message]

Parameters:
  • plugin (Any)

  • path (Path)

sawmill.core.plugin.plugin_implements_configure(plugin)

Return True when plugin overrides SawmillPlugin.configure().

Return type:

bool

Parameters:

plugin (Any)

exception sawmill.core.plugin.PluginError

Bases: Exception

Base exception for plugin-related errors.

exception sawmill.core.plugin.PluginConflictError

Bases: PluginError

Raised when multiple plugins both claim high confidence for a file.

exception sawmill.core.plugin.NoPluginFoundError

Bases: PluginError

Raised when no plugin can handle a file.

class sawmill.core.plugin.PluginManager

Bases: object

Manages 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:

None

unregister(name)

Unregister a plugin by name.

Parameters:

name (str) – The name of the plugin to unregister.

Return type:

None

discover()

Discover and register plugins from entry points.

Scans the ‘sawmill.plugins’ entry point group and registers any plugins found.

Return type:

list[str]

Returns:

List of discovered plugin names.

list_plugins()

List all registered plugin names.

Return type:

list[str]

Returns:

List of plugin names.

get_plugin(name)

Get a plugin by name.

Parameters:

name (str) – The name of the plugin.

Return type:

SawmillPlugin | None

Returns:

The plugin instance, or None if not found.

get_plugin_info(name)

Get information about a plugin.

Parameters:

name (str) – The name of the plugin.

Return type:

dict[str, str] | None

Returns:

Dictionary with plugin info (name, version, description), or None if not found.

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:

str

Returns:

Name of the plugin with highest confidence (>= 0.5).

Raises:
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:
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:

PluginManager

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.

Parameters:

plugin – The plugin instance to get levels from.

Return type:

dict[str, str]

Returns:

Dictionary mapping severity ID to Rich style string.

sawmill.core.severity.get_severity_style(severity, style_map)

Get the Rich style for a given severity level.

Parameters:
  • severity (str | None) – The severity level.

  • style_map (dict[str, str]) – Dictionary mapping severity ID to style string.

Return type:

str

Returns:

Rich style string for the severity.

sawmill.core.severity.get_severity_level_map(plugin)

Build a severity level map from plugin’s severity levels.

Parameters:

plugin – The plugin instance to get levels from.

Return type:

dict[str, int]

Returns:

Dictionary mapping severity ID to level number.

sawmill.core.severity.severity_at_or_above(message_severity, min_severity, level_map)

Check if message severity is at or above the minimum level.

Parameters:
  • message_severity (str | None) – The message’s severity (may be None).

  • min_severity (str) – The minimum severity level to show.

  • level_map (dict[str, int]) – Dictionary mapping severity ID to level number.

Return type:

bool

Returns:

True if the message should be shown.

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:

int

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_on is not a severity id defined by the plugin.