Coverage for collectra/tasks/text_output.py: 100.00%
25 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Parent class for tasks whose output is text."""
3from __future__ import annotations
5import re
7from pydantic import field_validator
9from collectra.tasks.base import Task
10from collectra.types.texts import Text
12__all__ = ["TextOutputTask"]
15class TextOutputTask(Task):
16 """A task that produces Text artefacts, optionally saved as files.
18 With ``output_extension`` set (for example ``md``, ``txt`` or ``xml``), each output
19 is written to ``{node}/{artefact_id}.{extension}`` in the results folder and
20 recorded there by path instead of inline. Later tasks still read the text as
21 usual. Leave it unset to keep the text inline in ``results.yaml``.
23 Subclasses build their outputs with ``self.text_output(...)``.
24 """
26 output_extension: str | None = None
28 @field_validator("output_extension", mode="before")
29 @classmethod
30 def _plain_suffix(cls, value):
31 if value is None:
32 return None
33 suffix = str(value).strip()
34 suffix = suffix[1:] if suffix.startswith(".") else suffix
35 if not suffix:
36 return None
37 if not re.fullmatch(r"[A-Za-z0-9]+", suffix):
38 raise ValueError(
39 f"output_extension must be a plain file suffix such as 'md', got {value!r}"
40 )
41 return suffix.lower()
43 def text_output(self, data: str, name: str | None = None) -> Text:
44 """Make this task's output Text, marked for saving if ``output_extension`` is set.
46 ``name`` is the output node the text belongs to; it defaults to the
47 task's first (or only) output.
48 """
49 text = Text(name=name or self.get_output_name(), data=data)
50 if self.output_extension:
51 text._file_extension = self.output_extension
52 return text