1 2 3 4 5 6 7 8 9 10 11 12 13 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
|
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under the Apache license (see LICENSE)
from __future__ import annotations
import re
from typing import TYPE_CHECKING, Callable
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator
def replace_blocks(
lines: Iterable[str], title: str, replace: Callable[..., Iterable[str]]
) -> Iterator[str]:
"""
Find blocks of lines in the form of:
::: <title>
:<key1>: <value>
:<key2>:
...
And replace them with the lines returned by `replace(key1="<value1>", key2="", ...)`.
"""
options = {}
in_block_section = False
for line in lines:
if in_block_section:
match = re.search(r"^\s+:(?P<key>.+):(?:\s+(?P<value>.*\S))?", line)
if match is not None:
# New ':key:' or ':key: value' line, ingest it.
key = match.group("key")
value = match.group("value") or ""
if value.lower() in ["true", "false"]:
value = value.lower() == "true"
options[key] = value
continue
# Block is finished, flush it.
in_block_section = False
yield from replace(**options)
yield line
continue
match = re.search(rf"^::: {title}", line)
if match is not None:
# Block header, ingest it.
in_block_section = True
options = {}
else:
yield line
if in_block_section:
yield from replace(**options)
|