Skip to content

File

File

Bases: BaseModel

File Task content class

Source code in src/task2md/template/file.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
class File(BaseModel):
    """File Task content class"""

    path: str = ""
    content: str = ""
    yaml: dict[str, Any] = {}
    header: Header = Header()
    global_variables: list[Variable] = []
    tasks: list[Task] = []
    parsed: bool = False

    def get_filename(self) -> str:
        """Get filename without extension

        Returns:
            str: The filename
        """
        return Path(self.path).stem

    def generate(self, out_dir: Dir) -> None:
        """Generate markdown file in output directory

        Args:
            out_dir (Dir): The dir object
        """
        self.load()
        self.parse()

        output_file = Path(out_dir.path) / f"{self.get_filename()}.md"
        output_file.write_text(self.to_md())

    def load(self) -> None:
        """Load file content from path"""
        self.content = Path(self.path).read_text()

    def parse(self) -> None:
        """Parse yaml content. Parsing twice is a no-op.

        Raises:
            ValueError: When the content is not valid YAML.
        """
        if self.parsed:
            return

        # yaml.YAMLError derives from Exception, not ValueError, so it would
        # escape the CLI error handling. Translate it at the boundary.
        try:
            yaml_content = yaml.safe_load(self.content)
        except yaml.YAMLError as error:
            raise ValueError(f"Invalid YAML: {error}") from error

        if (yaml_content is not None) and isinstance(yaml_content, dict):
            self.yaml = yaml_content

        # The header lives in comments, which YAML drops: it is read from the
        # raw text, unlike vars and tasks which come from the parsed mapping.
        header_lines = re.findall(r"# @.*", self.content, flags=re.MULTILINE)
        self.header.parse(header_lines)

        self._parse_vars()
        self._parse_tasks()

        self.parsed = True

    def _parse_vars(self) -> None:
        """Collect the global variables declared under `vars:`.

        A Taskfile may declare `vars:` as anything YAML accepts; only a mapping
        is meaningful here, anything else is ignored rather than crashing.
        """
        yaml_vars = self.yaml.get("vars")
        if not isinstance(yaml_vars, dict):
            return

        for name in sorted(yaml_vars.keys()):
            v = Variable(name=name)
            if isinstance(yaml_vars[name], str):
                v.value = yaml_vars[name]

            # The description is the trailing `# comment`, which YAML drops:
            # it has to be recovered from the raw line.
            line_var = re.findall(
                r"^  " + v.name + ": .*$", self.content, flags=re.MULTILINE
            )
            if len(line_var) > 0:
                desc = line_var[0].replace("  " + v.name + ": " + v.value, "")
                if "#" in desc:
                    v.description = desc.split("#", 1)[1].strip()

            self.global_variables.append(v)

    def _parse_tasks(self) -> None:
        """Collect the documented tasks declared under `tasks:`.

        Same tolerance as for `vars:`, extended to each task body: a task left
        as a placeholder (`build:` with nothing under it) parses to None and is
        skipped. A task without a non-empty `desc` is not documented.
        """
        yaml_tasks = self.yaml.get("tasks")
        if not isinstance(yaml_tasks, dict):
            return

        for name in sorted(yaml_tasks.keys()):
            body = yaml_tasks[name]
            if not isinstance(body, dict):
                continue

            desc = body.get("desc")
            if not (isinstance(desc, str) and (len(desc) > 0)):
                continue

            t = Task(name=name, desc=desc)
            summary = body.get("summary")
            if isinstance(summary, str) and (len(summary) > 0):
                t.summary = summary

            self.tasks.append(t)

    def to_md(self) -> str:
        """Return the content of the file in markdown

        Returns:
            str: Markdown content
        """
        output = ""
        # Tag
        output += self.tags_to_md()

        # Top
        output += f"---\n\n# {self.get_filename()}\n\n"
        output += self.header.description + "\n\n"
        output += f'!!! info "{self.get_filename()} template details"\n\n'
        output += self.header_to_md()

        # Tasks list
        output += "## :material-list-box: List of tasks\n"
        output += self.tasks_list_to_md() + "\n"

        # Global variables
        output += "## :material-variable: global variables\n"
        output += self.global_variables_to_md() + "\n"

        # Tasks details
        output += self.tasks_details_to_md()

        return output

    def tags_to_md(self) -> str:
        """Return the tags list

        Returns:
            str: markdown content
        """
        output = ""
        if len(self.header.tags) > 0:
            output += "---\ntags:\n"
            for tag in self.header.tags:
                output += f"  - {tag}\n"

        return output

    def header_to_md(self) -> str:
        """Return the header data

        Returns:
            str: markdown content
        """
        match self.header.status:
            case "stable":
                status_icon = "material-check-circle"
                status_label = "stable"
            case "deprecated":
                status_icon = "material-delete"
                status_label = "deprecated"
            case "beta":
                status_icon = "material-beta"
                status_label = "beta"
            case _:
                status_icon = "material-draw"
                status_label = "draft"

        output = ""
        output += f"    * :{status_icon}: Status: {status_label}\n"
        output += (
            "    * :material-bookmark-check: File: ["
            + self.header.file_raw
            + "]("
            + self.header.file_ui
            + ")\n"
        )
        output += (
            "    * :material-home: Home: ["
            + self.header.home
            + "]("
            + self.header.home
            + ")\n"
        )
        output += f"    * :material-license: License: {self.header.license}\n\n"

        return output

    def tasks_list_to_md(self) -> str:
        """Return the Tasks list to a markdown table

        Returns:
            str: markdown table
        """
        output = """
| Tasks | Description |
| ----- | ----------- |
"""
        for task in self.tasks:
            file_name = self.get_filename()
            escape_task_desc = task.desc.replace("|", r"\|")
            output += (
                f"| [`{file_name}:{task.name}`](#{file_name}{task.name})"
                f" | {escape_task_desc} |\n"
            )

        return output

    def global_variables_to_md(self) -> str:
        """Return the global variables to a markdown table

        Returns:
            str: markdown table
        """
        output = """
| Variables | Description | Default value |
| --------- | ----------- | ------------- |
"""

        if len(self.global_variables) == 0:
            # Empty variable to generate a line with no value
            v = Variable()
            output += v.to_md() + "\n"
        else:
            for var in self.global_variables:
                output += var.to_md() + "\n"

        return output

    def tasks_details_to_md(self) -> str:
        """Return the Tasks details

        Returns:
            str: List of tasks details
        """
        output = ""

        for task in self.tasks:
            output += task.to_md(self.get_filename())

        return output

    def __lt__(self, other: File) -> bool:
        """A custom comparison function for sorting by name

        Returns:
            str: True if object is lower than other
        """
        return bool(self.get_filename() < other.get_filename())

__lt__(other)

A custom comparison function for sorting by name

Returns:

Name Type Description
str bool

True if object is lower than other

Source code in src/task2md/template/file.py
269
270
271
272
273
274
275
def __lt__(self, other: File) -> bool:
    """A custom comparison function for sorting by name

    Returns:
        str: True if object is lower than other
    """
    return bool(self.get_filename() < other.get_filename())

generate(out_dir)

Generate markdown file in output directory

Parameters:

Name Type Description Default
out_dir Dir

The dir object

required
Source code in src/task2md/template/file.py
33
34
35
36
37
38
39
40
41
42
43
def generate(self, out_dir: Dir) -> None:
    """Generate markdown file in output directory

    Args:
        out_dir (Dir): The dir object
    """
    self.load()
    self.parse()

    output_file = Path(out_dir.path) / f"{self.get_filename()}.md"
    output_file.write_text(self.to_md())

get_filename()

Get filename without extension

Returns:

Name Type Description
str str

The filename

Source code in src/task2md/template/file.py
25
26
27
28
29
30
31
def get_filename(self) -> str:
    """Get filename without extension

    Returns:
        str: The filename
    """
    return Path(self.path).stem

global_variables_to_md()

Return the global variables to a markdown table

Returns:

Name Type Description
str str

markdown table

Source code in src/task2md/template/file.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    def global_variables_to_md(self) -> str:
        """Return the global variables to a markdown table

        Returns:
            str: markdown table
        """
        output = """
| Variables | Description | Default value |
| --------- | ----------- | ------------- |
"""

        if len(self.global_variables) == 0:
            # Empty variable to generate a line with no value
            v = Variable()
            output += v.to_md() + "\n"
        else:
            for var in self.global_variables:
                output += var.to_md() + "\n"

        return output

header_to_md()

Return the header data

Returns:

Name Type Description
str str

markdown content

Source code in src/task2md/template/file.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def header_to_md(self) -> str:
    """Return the header data

    Returns:
        str: markdown content
    """
    match self.header.status:
        case "stable":
            status_icon = "material-check-circle"
            status_label = "stable"
        case "deprecated":
            status_icon = "material-delete"
            status_label = "deprecated"
        case "beta":
            status_icon = "material-beta"
            status_label = "beta"
        case _:
            status_icon = "material-draw"
            status_label = "draft"

    output = ""
    output += f"    * :{status_icon}: Status: {status_label}\n"
    output += (
        "    * :material-bookmark-check: File: ["
        + self.header.file_raw
        + "]("
        + self.header.file_ui
        + ")\n"
    )
    output += (
        "    * :material-home: Home: ["
        + self.header.home
        + "]("
        + self.header.home
        + ")\n"
    )
    output += f"    * :material-license: License: {self.header.license}\n\n"

    return output

load()

Load file content from path

Source code in src/task2md/template/file.py
45
46
47
def load(self) -> None:
    """Load file content from path"""
    self.content = Path(self.path).read_text()

parse()

Parse yaml content. Parsing twice is a no-op.

Raises:

Type Description
ValueError

When the content is not valid YAML.

Source code in src/task2md/template/file.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def parse(self) -> None:
    """Parse yaml content. Parsing twice is a no-op.

    Raises:
        ValueError: When the content is not valid YAML.
    """
    if self.parsed:
        return

    # yaml.YAMLError derives from Exception, not ValueError, so it would
    # escape the CLI error handling. Translate it at the boundary.
    try:
        yaml_content = yaml.safe_load(self.content)
    except yaml.YAMLError as error:
        raise ValueError(f"Invalid YAML: {error}") from error

    if (yaml_content is not None) and isinstance(yaml_content, dict):
        self.yaml = yaml_content

    # The header lives in comments, which YAML drops: it is read from the
    # raw text, unlike vars and tasks which come from the parsed mapping.
    header_lines = re.findall(r"# @.*", self.content, flags=re.MULTILINE)
    self.header.parse(header_lines)

    self._parse_vars()
    self._parse_tasks()

    self.parsed = True

tags_to_md()

Return the tags list

Returns:

Name Type Description
str str

markdown content

Source code in src/task2md/template/file.py
161
162
163
164
165
166
167
168
169
170
171
172
173
def tags_to_md(self) -> str:
    """Return the tags list

    Returns:
        str: markdown content
    """
    output = ""
    if len(self.header.tags) > 0:
        output += "---\ntags:\n"
        for tag in self.header.tags:
            output += f"  - {tag}\n"

    return output

tasks_details_to_md()

Return the Tasks details

Returns:

Name Type Description
str str

List of tasks details

Source code in src/task2md/template/file.py
256
257
258
259
260
261
262
263
264
265
266
267
def tasks_details_to_md(self) -> str:
    """Return the Tasks details

    Returns:
        str: List of tasks details
    """
    output = ""

    for task in self.tasks:
        output += task.to_md(self.get_filename())

    return output

tasks_list_to_md()

Return the Tasks list to a markdown table

Returns:

Name Type Description
str str

markdown table

Source code in src/task2md/template/file.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    def tasks_list_to_md(self) -> str:
        """Return the Tasks list to a markdown table

        Returns:
            str: markdown table
        """
        output = """
| Tasks | Description |
| ----- | ----------- |
"""
        for task in self.tasks:
            file_name = self.get_filename()
            escape_task_desc = task.desc.replace("|", r"\|")
            output += (
                f"| [`{file_name}:{task.name}`](#{file_name}{task.name})"
                f" | {escape_task_desc} |\n"
            )

        return output

to_md()

Return the content of the file in markdown

Returns:

Name Type Description
str str

Markdown content

Source code in src/task2md/template/file.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def to_md(self) -> str:
    """Return the content of the file in markdown

    Returns:
        str: Markdown content
    """
    output = ""
    # Tag
    output += self.tags_to_md()

    # Top
    output += f"---\n\n# {self.get_filename()}\n\n"
    output += self.header.description + "\n\n"
    output += f'!!! info "{self.get_filename()} template details"\n\n'
    output += self.header_to_md()

    # Tasks list
    output += "## :material-list-box: List of tasks\n"
    output += self.tasks_list_to_md() + "\n"

    # Global variables
    output += "## :material-variable: global variables\n"
    output += self.global_variables_to_md() + "\n"

    # Tasks details
    output += self.tasks_details_to_md()

    return output