|
| 1 | +import os |
| 2 | +import re |
| 3 | + |
| 4 | +import tomllib |
| 5 | +import yaml |
| 6 | + |
| 7 | + |
| 8 | +class SectionExtractor: |
| 9 | + """ |
| 10 | + Extracts relevant sections from file content based on file format and governance keywords. |
| 11 | + Returns None when no relevant sections are found or format is unsupported (caller falls back to full content). |
| 12 | + """ |
| 13 | + |
| 14 | + def extract(self, filename: str, content: str, keywords: set[str]) -> str | None: |
| 15 | + """ |
| 16 | + Returns extracted relevant section text, or None if no sections found. |
| 17 | + filename should be the basename (lowercased). |
| 18 | + """ |
| 19 | + ext = os.path.splitext(filename)[1] |
| 20 | + if ext in (".md", ".markdown"): |
| 21 | + return self._extract_markdown_sections(content, keywords) |
| 22 | + elif ext in (".yaml", ".yml"): |
| 23 | + return self._extract_yaml_sections(content, keywords) |
| 24 | + elif ext == ".toml": |
| 25 | + return self._extract_toml_sections(content, keywords) |
| 26 | + return None |
| 27 | + |
| 28 | + def _extract_markdown_sections(self, content: str, keywords: set[str]) -> str | None: |
| 29 | + """ |
| 30 | + Splits content on `#`-style heading lines only (# / ## / ###...). |
| 31 | + Includes a section if its heading text contains any keyword. |
| 32 | + Returns joined matching sections, or None if none match. |
| 33 | + """ |
| 34 | + heading_pattern = re.compile(r"^#{1,6}\s+", re.MULTILINE) |
| 35 | + # Split into (heading_line, body) pairs; first element may be pre-heading content |
| 36 | + parts = heading_pattern.split(content) |
| 37 | + headings = heading_pattern.findall(content) |
| 38 | + |
| 39 | + # parts[0] is text before the first heading (skip it) |
| 40 | + # parts[1..] correspond to headings[0..] |
| 41 | + matching_sections = [] |
| 42 | + for i, heading_marker in enumerate(headings): |
| 43 | + block = parts[i + 1] # block starts right after the heading marker |
| 44 | + # The first line of block is the heading text |
| 45 | + first_newline = block.find("\n") |
| 46 | + heading_text = block[:first_newline].strip() if first_newline != -1 else block.strip() |
| 47 | + if any(kw in heading_text.lower() for kw in keywords): |
| 48 | + matching_sections.append(f"{heading_marker}{block}") |
| 49 | + |
| 50 | + return "".join(matching_sections) if matching_sections else None |
| 51 | + |
| 52 | + def _extract_yaml_sections(self, content: str, keywords: set[str]) -> str | None: |
| 53 | + """ |
| 54 | + Parses YAML and returns top-level keys whose name contains any keyword, serialized back to YAML. |
| 55 | + Returns None if no keys match or parsing fails. |
| 56 | + """ |
| 57 | + try: |
| 58 | + data = yaml.safe_load(content) |
| 59 | + except yaml.YAMLError: |
| 60 | + return None |
| 61 | + |
| 62 | + if not isinstance(data, dict): |
| 63 | + return None |
| 64 | + |
| 65 | + matching = {k: v for k, v in data.items() if any(kw in str(k).lower() for kw in keywords)} |
| 66 | + if not matching: |
| 67 | + return None |
| 68 | + |
| 69 | + return yaml.dump(matching, default_flow_style=False, allow_unicode=True) |
| 70 | + |
| 71 | + def _extract_toml_sections(self, content: str, keywords: set[str]) -> str | None: |
| 72 | + """ |
| 73 | + Parses TOML and returns top-level keys whose name contains any keyword, |
| 74 | + serialized as Python repr key=value lines (not valid TOML syntax). |
| 75 | + Returns None if no keys match or parsing fails. |
| 76 | + """ |
| 77 | + try: |
| 78 | + data = tomllib.loads(content) |
| 79 | + except tomllib.TOMLDecodeError: |
| 80 | + return None |
| 81 | + |
| 82 | + matching = {k: v for k, v in data.items() if any(kw in k.lower() for kw in keywords)} |
| 83 | + if not matching: |
| 84 | + return None |
| 85 | + |
| 86 | + # Serialize matching keys back as simple TOML representation |
| 87 | + lines = [] |
| 88 | + for k, v in matching.items(): |
| 89 | + lines.append(f"{k} = {repr(v)}") |
| 90 | + return "\n".join(lines) |
0 commit comments