Prepend ``source_file`` to the inline ``sources:`` list in YAML frontmatter. Creates the frontmatter or the ``sources:`` line if missing. Returns the text unchanged if ``source_file`` is already present in the list, or if the frontmatter is malformed (no closing ``---``).
(text: str, source_file: str)
| 1097 | |
| 1098 | |
| 1099 | def _prepend_source_to_frontmatter(text: str, source_file: str) -> str: |
| 1100 | """Prepend ``source_file`` to the inline ``sources:`` list in YAML frontmatter. |
| 1101 | |
| 1102 | Creates the frontmatter or the ``sources:`` line if missing. Returns the |
| 1103 | text unchanged if ``source_file`` is already present in the list, or if |
| 1104 | the frontmatter is malformed (no closing ``---``). |
| 1105 | """ |
| 1106 | if not text.startswith("---"): |
| 1107 | return f"---\n{_yaml_list_line('sources', [source_file])}\n---\n\n" + text |
| 1108 | |
| 1109 | parts = frontmatter.split(text) |
| 1110 | if parts is None: |
| 1111 | return text |
| 1112 | |
| 1113 | fm_block, body = parts |
| 1114 | # Strip the trailing closing delimiter to get the prefix lines (opening |
| 1115 | # "---" + content lines), then re-append it. `frontmatter.split` leaves the |
| 1116 | # closing at the end of fm_block as either "\n---\n" or a bare "\n---" (when |
| 1117 | # the page ends at the delimiter with no trailing newline). Assuming only |
| 1118 | # "\n---\n" would, for the bare form, make the strip below collapse the |
| 1119 | # whole block and drop every existing frontmatter key. |
| 1120 | closing = "\n---\n" if fm_block.endswith("\n---\n") else "\n---" |
| 1121 | fm_prefix = fm_block[: -len(closing)] |
| 1122 | fm_lines = fm_prefix.split("\n") |
| 1123 | |
| 1124 | for i, line in enumerate(fm_lines): |
| 1125 | if not line.lstrip().startswith("sources:"): |
| 1126 | continue |
| 1127 | items = _parse_yaml_list_value(line) |
| 1128 | if items is None: |
| 1129 | return text |
| 1130 | if source_file in items: |
| 1131 | return text |
| 1132 | items.insert(0, source_file) |
| 1133 | fm_lines[i] = _yaml_list_line("sources", items) |
| 1134 | return "\n".join(fm_lines) + closing + body |
| 1135 | |
| 1136 | fm_lines.insert(1, _yaml_list_line("sources", [source_file])) |
| 1137 | return "\n".join(fm_lines) + closing + body |
| 1138 | |
| 1139 | |
| 1140 | def _remove_source_from_frontmatter(text: str, source_file: str) -> tuple[str, bool]: |
no outgoing calls