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

1"""Parent class for tasks whose output is text.""" 

2 

3from __future__ import annotations 

4 

5import re 

6 

7from pydantic import field_validator 

8 

9from collectra.tasks.base import Task 

10from collectra.types.texts import Text 

11 

12__all__ = ["TextOutputTask"] 

13 

14 

15class TextOutputTask(Task): 

16 """A task that produces Text artefacts, optionally saved as files. 

17 

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

22 

23 Subclasses build their outputs with ``self.text_output(...)``. 

24 """ 

25 

26 output_extension: str | None = None 

27 

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

42 

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. 

45 

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