Replace permalinks in the given text with the permalinks from the original document. Fail if the number or level of headers does not match the original.
(
text: list[str],
header_permalinks: list[HeaderPermalinkInfo],
original_header_permalinks: list[HeaderPermalinkInfo],
)
| 207 | |
| 208 | |
| 209 | def replace_header_permalinks( |
| 210 | text: list[str], |
| 211 | header_permalinks: list[HeaderPermalinkInfo], |
| 212 | original_header_permalinks: list[HeaderPermalinkInfo], |
| 213 | ) -> list[str]: |
| 214 | """ |
| 215 | Replace permalinks in the given text with the permalinks from the original document. |
| 216 | |
| 217 | Fail if the number or level of headers does not match the original. |
| 218 | """ |
| 219 | |
| 220 | modified_text: list[str] = text.copy() |
| 221 | |
| 222 | if len(header_permalinks) != len(original_header_permalinks): |
| 223 | raise ValueError( |
| 224 | "Number of headers with permalinks does not match the number in the " |
| 225 | "original document " |
| 226 | f"({len(header_permalinks)} vs {len(original_header_permalinks)})" |
| 227 | ) |
| 228 | |
| 229 | for header_no in range(len(header_permalinks)): |
| 230 | header_info = header_permalinks[header_no] |
| 231 | original_header_info = original_header_permalinks[header_no] |
| 232 | |
| 233 | if header_info["hashes"] != original_header_info["hashes"]: |
| 234 | raise ValueError( |
| 235 | "Header levels do not match between document and original document" |
| 236 | f" (found {header_info['hashes']}, expected {original_header_info['hashes']})" |
| 237 | f" for header №{header_no + 1} in line {header_info['line_no']}" |
| 238 | ) |
| 239 | line_no = header_info["line_no"] - 1 |
| 240 | hashes = header_info["hashes"] |
| 241 | title = header_info["title"] |
| 242 | permalink = original_header_info["permalink"] |
| 243 | modified_text[line_no] = f"{hashes} {title}{permalink}" |
| 244 | |
| 245 | return modified_text |
| 246 | |
| 247 | |
| 248 | # Markdown links |