Skip to content

Helpers

psengine.detection.helpers.save_rule

save_rule(
    rule: DetectionRule,
    output_directory: Optional[Union[str, Path]] = None,
)

Write detection rule content to file.

If more than one detection rule is attached to the rule, all will be saved.

PARAMETER DESCRIPTION
rule

Single detection rule to write.

TYPE: DetectionRule

output_directory

Path to write to. If not provided, the current working directory will be used.

TYPE: Optional[Union[str, Path]] DEFAULT: None

RAISES DESCRIPTION
WriteFileError

In one of those cases:

  • If the path provided is not a directory.
  • If the path cannot be created.
  • If the write operations fail.
Source code in psengine/detection/helpers.py
@debug_call
@validate_call
def save_rule(
    rule: Annotated[DetectionRule, Doc('Single detection rule to write.')],
    output_directory: Annotated[
        Optional[Union[str, Path]],
        Doc('Path to write to. If not provided, the current working directory will be used.'),
    ] = None,
):
    """Write detection rule content to file.

    If more than one detection rule is attached to the rule, all will be saved.

    Raises:
        WriteFileError: In one of those cases:

            - If the path provided is not a directory.
            - If the path cannot be created.
            - If the write operations fail.
    """
    if not rule.rules:
        LOG.info(f'No rules to write for {rule.id_}')
        return

    output_directory = Path(output_directory).absolute() if output_directory else Path().cwd()
    OSHelpers.mkdir(output_directory)

    for i, data in enumerate(rule.rules):
        try:
            full_path = output_directory / (data.file_name or f'{rule.id_.replace(":", "_")}_{i}')
            full_path.write_text(data.content)
            LOG.info(f'Wrote: {full_path}')
        except (FileNotFoundError, IsADirectoryError, PermissionError, OSError) as err:  # noqa: PERF203
            raise WriteFileError(f"Could not write file '{data.file_name}': {err}") from err