Read the section a heading (or page) node opens. ``(section, "")`` or ``(None, reason)``.
(node: dict, root: Path,
max_chars: int = DEFAULT_MAX_CHARS)
| 110 | |
| 111 | |
| 112 | def read_section(node: dict, root: Path, |
| 113 | max_chars: int = DEFAULT_MAX_CHARS) -> "tuple[Section | None, str]": |
| 114 | """Read the section a heading (or page) node opens. ``(section, "")`` or ``(None, reason)``.""" |
| 115 | label = str(node.get("label") or "") |
| 116 | source_file = str(node.get("source_file") or "") |
| 117 | if not is_section_node(node): |
| 118 | return None, (f"'{label}' is not a Markdown heading or page. " |
| 119 | "get_section reads Markdown sections only.") |
| 120 | if node.get("repo"): |
| 121 | return None, (f"'{label}' comes from a merged multi-repo graph. " |
| 122 | "Read it from that repo's own graph.") |
| 123 | path = _resolve_inside(source_file, root) |
| 124 | if path is None: |
| 125 | return None, f"Refusing to read '{source_file}': it is outside the project." |
| 126 | try: |
| 127 | lines = _read_source_text(path, warn=False).splitlines() |
| 128 | except (OSError, UnicodeError) as exc: |
| 129 | return None, f"Could not read {source_file}: {exc}" |
| 130 | |
| 131 | moved = False |
| 132 | if node.get("node_kind") == "page": |
| 133 | _, body_start = _split_frontmatter(lines) |
| 134 | start, end = body_start + 1, len(lines) |
| 135 | else: |
| 136 | m = _LINE_RE.match(str(node.get("source_location") or "").strip()) |
| 137 | recorded = int(m.group(1)) if m else 0 |
| 138 | heads = _headings(lines) |
| 139 | same = [h for h in heads |
| 140 | if h[2] == label or sanitize_label(h[2]) == sanitize_label(label)] |
| 141 | exact = [h for h in same if h[0] == recorded] |
| 142 | # The recorded line wins. A heading that moved is followed only when its |
| 143 | # title is unique in the file; with several, guessing could return the |
| 144 | # wrong one. |
| 145 | hit = exact[0] if exact else same[0] if len(same) == 1 else None |
| 146 | if hit is None: |
| 147 | return None, (f"'{label}' is no longer at line {recorded} of {source_file}. " |
| 148 | "Run `graphify update .` to refresh the graph.") |
| 149 | moved = hit[0] != recorded |
| 150 | start, level = hit[0], hit[1] |
| 151 | end = next((ln - 1 for ln, lv, _ in heads if ln > start and lv <= level), len(lines)) |
| 152 | while end > start and not lines[end - 1].strip(): |
| 153 | end -= 1 |
| 154 | if end < start: |
| 155 | return None, f"{source_file} has no text for '{label}'." |
| 156 | body = "\n".join(_BODY_CONTROL_RE.sub("", ln) for ln in lines[start - 1:end]) |
| 157 | body = redact_secrets(body) |
| 158 | truncated = len(body) > max_chars |
| 159 | if truncated: |
| 160 | body = body[:max_chars] |
| 161 | return Section(sanitize_label(source_file), start, end, body, truncated, moved), "" |
| 162 | |
| 163 | |
| 164 | def format_section(section: Section, label: str) -> str: |