feat: add source parsing and linking #8

Open
jaredhowland wants to merge 9 commits from jaredhowland/add-source-parsing into main
pull from: jaredhowland/add-source-parsing
4 changed files with 586 additions and 36 deletions
Showing only changes of commit 6259bfffd6 - Show all commits

No files matched your search

+101 -33
View File
@@ -366,44 +366,112 @@ class Individual:
copilot-pull-request-reviewer[bot] commented 2026-04-17 21:49:54 +02:00 (Migrated from github.com)
Review

Pointer detection for SOUR @X@ should match the stricter pattern used elsewhere (startswith('@') and endswith('@')). Using only startswith('@') can misclassify inline values that happen to begin with '@', and can lead to failed lookups in the element dictionary.

            if src_ref and src_ref.startswith("@") and src_ref.endswith("@"):
Pointer detection for `SOUR @X@` should match the stricter pattern used elsewhere (`startswith('@') and endswith('@')`). Using only `startswith('@')` can misclassify inline values that happen to begin with '@', and can lead to failed lookups in the element dictionary. ```suggestion if src_ref and src_ref.startswith("@") and src_ref.endswith("@"): ```
return images return images
def _collapse_preserve_lines(self, text: str) -> str:
"""Collapse whitespace within each line but preserve line breaks."""
if not text:
return ""
return "\n".join(" ".join(line.split()) for line in text.splitlines()).strip()
def _resolve_gedcom_text(self, value: str, element=None) -> str:
"""Resolve a GEDCOM text value which may be a pointer to another element or inline text.
Appends CONT/CONC child lines (skipping empty ones) separated by single newlines.
"""
if not value:
return ""
# Pointer/reference to another element (e.g., NOTE record)
if value.startswith("@") and value.endswith("@"):
target = self.gedcom.get_element_dictionary().get(value)
if not target:
return ""
text = target.get_value() or ""
# Respect CONT vs CONC semantics: CONT => newline, CONC => concatenate
for sub in target.get_child_elements():
tag = sub.get_tag()
val = (sub.get_value() or "")
if not val:
continue
if tag == "CONC":
# concatenate directly
text += val
elif tag == "CONT":
text += "\n" + val
return text
# Inline text with possible CONT/CONC children
text = value or ""
if element is not None:
for sub in element.get_child_elements():
tag = sub.get_tag()
val = (sub.get_value() or "")
if not val:
continue
if tag == "CONC":
text += val
elif tag == "CONT":
text += "\n" + val
return text
def get_notes(self) -> List[str]: def get_notes(self) -> List[str]:
""" """Return the person's notes with continuations resolved and extraneous whitespace collapsed per-line."""
Return the person's notes with inline continuations and referenced NOTE records resolved.
This resolves NOTE cross-references (values like `@X@`), appends `CONT`/`CONC` continuations, trims whitespace, and omits empty or unresolved references.
Returns:
List[str]: Note texts with continuations and referenced NOTE content merged; empty or unresolved notes are omitted.
"""
notes = [] notes = []
for child in self.element.get_child_elements(): for child in self.element.get_child_elements():
if child.get_tag() == "NOTE": if child.get_tag() != "NOTE":
note_text = child.get_value() or "" continue
raw = child.get_value() or ""
# If note_text starts with @, it's a reference to a NOTE record text = self._resolve_gedcom_text(raw, child)
if note_text.startswith("@") and note_text.endswith("@"): if text and not text.startswith("@"):
# Resolve the reference notes.append(self._collapse_preserve_lines(text))
note_element = self.gedcom.get_element_dictionary().get(note_text)
if note_element:
# Get the note text from the NOTE element
note_text = note_element.get_value() or ""
# Get continued text from the NOTE record
for subchild in note_element.get_child_elements():
if subchild.get_tag() in ["CONT", "CONC"]:
note_text += "\n" + (subchild.get_value() or "")
else:
# Inline note - check for continued text in subchilds
for subchild in child.get_child_elements():
if subchild.get_tag() in ["CONT", "CONC"]:
note_text += "\n" + (subchild.get_value() or "")
if note_text and not note_text.startswith("@"):
notes.append(note_text.strip())
return notes return notes
def get_sources(self) -> List[Dict[str, str]]:
"""
Extract SOUR references for this individual and return normalized entries.
Each entry is a dict: {"title": str, "publ": str, "note": str} with internal whitespace collapsed.
Handles both referenced SOURCE pointers (SOUR @X@) and inline SOURCE blocks under the individual.
"""
def _collapse_single_line(text: str) -> str:
return " ".join(text.split()).strip() if text else ""
sources = []
for child in self.element.get_child_elements():
if child.get_tag() != "SOUR":
continue
title = ""
publ = ""
note_text = ""
# child may be a pointer to a SOURCE record or an inline SOURCE element
src_ref = child.get_value() or ""
if src_ref and src_ref.startswith("@"):
elem_to_scan = self.gedcom.get_element_dictionary().get(src_ref) or child
else:
elem_to_scan = child
for sc in elem_to_scan.get_child_elements():
tag = sc.get_tag()
if tag == "TITL":
title = sc.get_value() or ""
elif tag == "PUBL":
publ = sc.get_value() or ""
elif tag == "NOTE":
raw_note = sc.get_value() or ""
note_text = self._resolve_gedcom_text(raw_note, sc)
# Normalize whitespace for title/publ but preserve line breaks in notes
title = _collapse_single_line(title)
publ = _collapse_single_line(publ)
note_text = self._collapse_preserve_lines(note_text)
if title or publ or note_text:
sources.append({"title": title, "publ": publ, "note": note_text})
return sources
def get_stories(self) -> List[Dict]: def get_stories(self) -> List[Dict]:
""" """
Extract story and narrative records referenced by custom `_STO` tags for this individual. Extract story and narrative records referenced by custom `_STO` tags for this individual.
+271 -3
View File
@@ -8,6 +8,7 @@ in the family tree.
from pathlib import Path from pathlib import Path
from typing import List, Optional from typing import List, Optional
import logging import logging
import re
from individual import Individual from individual import Individual
@@ -56,6 +57,7 @@ class MarkdownGenerator:
self.use_subdirectories = use_subdirectories self.use_subdirectories = use_subdirectories
self.generated_stories = {} # Track generated story files self.generated_stories = {} # Track generated story files
self.filename_map = {} # Map from individual ID to actual filename used self.filename_map = {} # Map from individual ID to actual filename used
self._sources_index_generated = False # Ensure global sources index is created only once
def _get_unique_filename(self, base_name: str, individual_id: str) -> str: def _get_unique_filename(self, base_name: str, individual_id: str) -> str:
""" """
@@ -108,6 +110,19 @@ class MarkdownGenerator:
self._write_children(f, individual) self._write_children(f, individual)
self._write_images(f, individual) self._write_images(f, individual)
self._write_notes(f, individual) self._write_notes(f, individual)
# Write Sources section (if any)
self._write_sources(f, individual)
# Generate global sources index once if not already generated. This preserves the behavior
# expected by callers that invoke generate_note() directly (unit tests), while avoiding
# O(N^2) behavior when multiple notes are generated via generate_all().
if not getattr(self, '_sources_index_generated', False):
parser = getattr(individual, 'gedcom', None)
if parser:
try:
self._generate_sources_index(parser)
except Exception:
logger.exception('Failed to generate sources index')
return file_path return file_path
@@ -397,9 +412,9 @@ class MarkdownGenerator:
def _write_notes(self, f, individual: Individual): def _write_notes(self, f, individual: Individual):
""" """
Write the "Notes" section for an individual, including inline notes and links to separate story files. Write the "Notes" section for an individual, including inline notes and links to separate story files.
If the individual has no notes and no stories, nothing is written. For each regular note, writes the note text into the section. For each story, generates or reuses a story markdown file via the generator, then writes a WikiLink to that story (prefixed with the configured stories subdirectory when present) and includes the story's description on the same line if provided. If the individual has no notes and no stories, nothing is written. For each regular note, writes the note text into the section. For each story, generates or reuses a story markdown file via the generator, then writes a WikiLink to that story (prefixed with the configured stories subdirectory when present) and includes the story's description on the same line if provided.
Parameters: Parameters:
f: A writable text file object opened for the individual's markdown note. f: A writable text file object opened for the individual's markdown note.
individual (Individual): The individual whose notes and stories will be rendered. individual (Individual): The individual whose notes and stories will be rendered.
@@ -414,7 +429,13 @@ class MarkdownGenerator:
# Write regular notes # Write regular notes
for note in notes: for note in notes:
f.write(f"{note}\n\n") # Repair broken HTML tags that may span lines, then split into lines
repaired = self._repair_broken_html_tags(note)
lines = repaired.splitlines()
# Escape markdown in each line to avoid accidental emphasis, then write
esc_lines = [self._escape_markdown(ln) for ln in lines]
self._write_multiline_note_block(f, esc_lines, nested=False)
f.write("\n")
# Generate separate story files and link to them # Generate separate story files and link to them
if stories: if stories:
@@ -446,6 +467,239 @@ class MarkdownGenerator:
copilot-pull-request-reviewer[bot] commented 2026-04-17 21:49:52 +02:00 (Migrated from github.com)
Review

The docstring says the source NOTE text is “formatted in italic”, but the implementation escapes emphasis characters and writes plain text (no italics). Either update the docstring to reflect actual behavior, or implement the intended italic formatting in a way that won’t conflict with markdown escaping.

        and, if present, the source's NOTE text will be written as an indented
        escaped note block beneath it.
The docstring says the source NOTE text is “formatted in italic”, but the implementation escapes emphasis characters and writes plain text (no italics). Either update the docstring to reflect actual behavior, or implement the intended italic formatting in a way that won’t conflict with markdown escaping. ```suggestion and, if present, the source's NOTE text will be written as an indented escaped note block beneath it. ```
copilot-pull-request-reviewer[bot] commented 2026-04-17 21:49:53 +02:00 (Migrated from github.com)
Review

In the non-nested branch, the “last non-empty line” is detected by comparing string values (ln == last_non_empty). If the same text appears earlier in lines, earlier occurrences will be treated as the last line and won’t get the intended trailing spaces/hard-break behavior. Track the last non-empty index instead (or iterate with indices) to make this deterministic.

            last_non_empty_idx = next(
                (idx for idx in range(len(lines) - 1, -1, -1) if lines[idx].strip()),
                None,
            )
            for idx, ln in enumerate(lines):
                if not ln.strip():
                    f.write("\n")
                elif idx == last_non_empty_idx:
In the non-nested branch, the “last non-empty line” is detected by comparing string values (`ln == last_non_empty`). If the same text appears earlier in `lines`, earlier occurrences will be treated as the last line and won’t get the intended trailing spaces/hard-break behavior. Track the last non-empty *index* instead (or iterate with indices) to make this deterministic. ```suggestion last_non_empty_idx = next( (idx for idx in range(len(lines) - 1, -1, -1) if lines[idx].strip()), None, ) for idx, ln in enumerate(lines): if not ln.strip(): f.write("\n") elif idx == last_non_empty_idx: ```
copilot-pull-request-reviewer[bot] commented 2026-04-17 21:49:54 +02:00 (Migrated from github.com)
Review

_generate_sources_index accumulates every source (including full note text) into an in-memory sources list before writing. With “several hundred thousand sources”, this can become a large memory spike and/or slow GC. Consider streaming directly to Index.md as you scan elem_dict (write each entry immediately) so memory usage stays bounded.

`_generate_sources_index` accumulates every source (including full note text) into an in-memory `sources` list before writing. With “several hundred thousand sources”, this can become a large memory spike and/or slow GC. Consider streaming directly to `Index.md` as you scan `elem_dict` (write each entry immediately) so memory usage stays bounded.
f.write("\n") f.write("\n")
def _collapse_single_line(self, text: str) -> str:
"""Collapse runs of whitespace into single spaces and strip the result."""
return " ".join(text.split()).strip() if text else ""
def _collapse_preserve_lines(self, text: str) -> str:
"""Collapse runs of whitespace within each line but preserve line breaks.
Returns a string where each original line has internal whitespace collapsed
but newline boundaries between CONT/CONC lines are preserved.
"""
if not text:
return ""
return "\n".join(" ".join(line.split()) for line in text.splitlines()).strip()
def _format_source_entry(self, title: str, publ: str) -> str:
"""Return a formatted markdown line for a source entry.
If title and publ are present, title is rendered as a link to publ.
If only title present, render plain title. If only publ present, use the URL as link text.
"""
title = self._collapse_single_line(title)
publ = self._collapse_single_line(publ)
if title and publ:
return f"[{title}]({publ})"
if title:
return title
if publ:
return f"[{publ}]({publ})"
return "(Unknown source)"
coderabbitai[bot] commented 2026-04-18 06:05:46 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Expect: no S110/BLE001 diagnostics for the empty-index cleanup block.
ruff check src/markdown_generator.py --select S110,BLE001

Repository: AlexKucera/gedcom-to-markdown

Length of output: 1071


🏁 Script executed:

#!/bin/bash
# Check for logger imports and setup in the file
head -50 src/markdown_generator.py | grep -E "^import|^from|logger"

Repository: AlexKucera/gedcom-to-markdown

Length of output: 270


🏁 Script executed:

#!/bin/bash
# Verify the fix by showing the surrounding context and creating a test
cat -n src/markdown_generator.py | sed -n '655,665p'

Repository: AlexKucera/gedcom-to-markdown

Length of output: 539


🏁 Script executed:

#!/bin/bash
# Create a test to verify the proposed fix resolves both diagnostics
cat > /tmp/test_fix.py << 'EOF'
import logging
from pathlib import Path

logger = logging.getLogger(__name__)

# Original code - should trigger S110 and BLE001
def original():
    index_file = Path("test.md")
    if index_file.exists():
        try:
            index_file.unlink()
        except Exception:
            pass

# Proposed fix - should not trigger either diagnostic
def proposed():
    index_file = Path("test.md")
    if index_file.exists():
        try:
            index_file.unlink()
        except OSError:
            logger.exception("Failed to remove empty sources index: %s", index_file)
EOF

# Run ruff on the test file to verify the fix
ruff check /tmp/test_fix.py --select S110,BLE001

Repository: AlexKucera/gedcom-to-markdown

Length of output: 956


🏁 Script executed:

#!/bin/bash
# Verify the proposed fix directly by extracting just that section
cat > /tmp/test_fix_only.py << 'EOF'
import logging
from pathlib import Path

logger = logging.getLogger(__name__)

def fixed():
    index_file = Path("test.md")
    if index_file.exists():
        try:
            index_file.unlink()
        except OSError:
            logger.exception("Failed to remove empty sources index: %s", index_file)
EOF

ruff check /tmp/test_fix_only.py --select S110,BLE001

Repository: AlexKucera/gedcom-to-markdown

Length of output: 91


Log cleanup failures instead of swallowing them.

If removing the empty sources/Index.md fails, the stale file remains and the cause is hidden. The current code triggers both Ruff S110 (try-except-pass without logging) and BLE001 (blind exception catch) diagnostics.

🛠️ Proposed fix
         if not written_any and index_file.exists():
             try:
                 index_file.unlink()
-            except Exception:
-                pass
+            except OSError:
+                logger.exception("Failed to remove empty sources index: %s", index_file)

Catch OSError instead of the overly broad Exception, and log the failure using the available logger.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        # If nothing was actually written, remove the empty index file
        if not written_any and index_file.exists():
            try:
                index_file.unlink()
            except OSError:
                logger.exception("Failed to remove empty sources index: %s", index_file)
🧰 Tools
🪛 Ruff (0.15.10)

[error] 661-662: try-except-pass detected, consider logging the exception

(S110)


[warning] 661-661: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/markdown_generator.py` around lines 657 - 662, The empty-index cleanup
currently swallows all exceptions (try/except/pass) when calling
index_file.unlink(), which hides failures and triggers lint warnings; change the
handler to catch OSError only and log the error via the available logger (e.g.,
call logger.error or self.logger.error) including context that unlinking
index_file failed and the exception details, so replace the bare except with
"except OSError as e" and a logger.error(...) call referencing index_file and e
while leaving the rest of the logic intact (symbols: index_file, written_any).
_⚠️ Potential issue_ | _🟡 Minor_ <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash # Expect: no S110/BLE001 diagnostics for the empty-index cleanup block. ruff check src/markdown_generator.py --select S110,BLE001 ``` Repository: AlexKucera/gedcom-to-markdown Length of output: 1071 --- 🏁 Script executed: ```shell #!/bin/bash # Check for logger imports and setup in the file head -50 src/markdown_generator.py | grep -E "^import|^from|logger" ``` Repository: AlexKucera/gedcom-to-markdown Length of output: 270 --- 🏁 Script executed: ```shell #!/bin/bash # Verify the fix by showing the surrounding context and creating a test cat -n src/markdown_generator.py | sed -n '655,665p' ``` Repository: AlexKucera/gedcom-to-markdown Length of output: 539 --- 🏁 Script executed: ```shell #!/bin/bash # Create a test to verify the proposed fix resolves both diagnostics cat > /tmp/test_fix.py << 'EOF' import logging from pathlib import Path logger = logging.getLogger(__name__) # Original code - should trigger S110 and BLE001 def original(): index_file = Path("test.md") if index_file.exists(): try: index_file.unlink() except Exception: pass # Proposed fix - should not trigger either diagnostic def proposed(): index_file = Path("test.md") if index_file.exists(): try: index_file.unlink() except OSError: logger.exception("Failed to remove empty sources index: %s", index_file) EOF # Run ruff on the test file to verify the fix ruff check /tmp/test_fix.py --select S110,BLE001 ``` Repository: AlexKucera/gedcom-to-markdown Length of output: 956 --- 🏁 Script executed: ```shell #!/bin/bash # Verify the proposed fix directly by extracting just that section cat > /tmp/test_fix_only.py << 'EOF' import logging from pathlib import Path logger = logging.getLogger(__name__) def fixed(): index_file = Path("test.md") if index_file.exists(): try: index_file.unlink() except OSError: logger.exception("Failed to remove empty sources index: %s", index_file) EOF ruff check /tmp/test_fix_only.py --select S110,BLE001 ``` Repository: AlexKucera/gedcom-to-markdown Length of output: 91 --- </details> **Log cleanup failures instead of swallowing them.** If removing the empty `sources/Index.md` fails, the stale file remains and the cause is hidden. The current code triggers both Ruff S110 (try-except-pass without logging) and BLE001 (blind exception catch) diagnostics. <details> <summary>🛠️ Proposed fix</summary> ```diff if not written_any and index_file.exists(): try: index_file.unlink() - except Exception: - pass + except OSError: + logger.exception("Failed to remove empty sources index: %s", index_file) ``` </details> Catch `OSError` instead of the overly broad `Exception`, and log the failure using the available logger. <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion # If nothing was actually written, remove the empty index file if not written_any and index_file.exists(): try: index_file.unlink() except OSError: logger.exception("Failed to remove empty sources index: %s", index_file) ``` </details> <!-- suggestion_end --> <details> <summary>🧰 Tools</summary> <details> <summary>🪛 Ruff (0.15.10)</summary> [error] 661-662: `try`-`except`-`pass` detected, consider logging the exception (S110) --- [warning] 661-661: Do not catch blind exception: `Exception` (BLE001) </details> </details> <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against the current code and only fix it if needed. In `@src/markdown_generator.py` around lines 657 - 662, The empty-index cleanup currently swallows all exceptions (try/except/pass) when calling index_file.unlink(), which hides failures and triggers lint warnings; change the handler to catch OSError only and log the error via the available logger (e.g., call logger.error or self.logger.error) including context that unlinking index_file failed and the exception details, so replace the bare except with "except OSError as e" and a logger.error(...) call referencing index_file and e while leaving the rest of the logic intact (symbols: index_file, written_any). ``` </details> <!-- fingerprinting:phantom:medusa:ibis --> <!-- This is an auto-generated comment by CodeRabbit -->
def _write_sources(self, f, individual: Individual):
"""
Write the "Sources" section for an individual as a numbered list.
Each source will include the formatted title/publication on the numbered line
and, if present, the source's NOTE text will be written indented beneath it
(formatted in italic to match the generated index).
"""
sources = individual.get_sources()
if not sources:
return
f.write("## Sources\n\n")
for i, src in enumerate(sources, 1):
line = self._format_source_entry(src.get("title", ""), src.get("publ", ""))
f.write(f"{i}. {line}\n")
note_text = src.get("note", "")
if note_text:
# Repair broken HTML tags spanning lines and escape markdown
note_text = self._repair_broken_html_tags(note_text)
lines = [self._escape_markdown(ln) for ln in note_text.splitlines()]
self._write_multiline_note_block(f, lines, nested=True)
f.write("\n")
def _generate_sources_index(self, parser):
"""
Generate a summary Index.md in a sources/ subdirectory listing all SOURCE records found in the GEDCOM element dictionary.
"""
try:
elem_dict = parser.get_element_dictionary()
except Exception:
return
sources = []
for elem in elem_dict.values():
try:
if elem.get_tag() != "SOUR":
continue
except Exception:
continue
title = ""
publ = ""
note_text = ""
for sc in elem.get_child_elements():
tag = sc.get_tag()
if tag == "TITL":
title = sc.get_value() or ""
elif tag == "PUBL":
publ = sc.get_value() or ""
elif tag == "NOTE":
note_val = sc.get_value() or ""
if note_val.startswith("@") and note_val.endswith("@"):
n_elem = elem_dict.get(note_val)
if n_elem:
note_text = n_elem.get_value() or ""
for sub in n_elem.get_child_elements():
tag_sub = sub.get_tag()
val_sub = (sub.get_value() or "")
if not val_sub:
continue
if tag_sub == "CONC":
note_text += val_sub
elif tag_sub == "CONT":
note_text += "\n" + val_sub
else:
note_text = note_val
for sub in sc.get_child_elements():
tag_sub = sub.get_tag()
val_sub = (sub.get_value() or "")
if not val_sub:
continue
if tag_sub == "CONC":
note_text += val_sub
elif tag_sub == "CONT":
note_text += "\n" + val_sub
title = self._collapse_single_line(title)
publ = self._collapse_single_line(publ)
note_text = self._collapse_preserve_lines(note_text)
if title or publ or note_text:
sources.append({"title": title, "publ": publ, "note": note_text})
if not sources:
return
# Prefer a global 'sources' directory at the top-level output when using
# the organized subdirectory layout (people/, stories/, media/). The
# generator's output_dir is typically the people/ directory in that
# case, so use its parent as the global output root.
if self.use_subdirectories and self.output_dir and self.output_dir.parent:
sources_dir = self.output_dir.parent / "sources"
else:
sources_dir = self.output_dir / "sources"
sources_dir.mkdir(parents=True, exist_ok=True)
index_file = sources_dir / "Index.md"
with open(index_file, "w", encoding="utf-8") as f:
f.write("# Sources Index\n\n")
for i, src in enumerate(sources, 1):
entry = self._format_source_entry(src.get("title", ""), src.get("publ", ""))
f.write(f"{i}. {entry}\n")
note_text = src.get("note", "")
if note_text:
# Repair broken HTML tags and escape markdown
note_text = self._repair_broken_html_tags(note_text)
lines = [self._escape_markdown(ln) for ln in note_text.splitlines()]
self._write_multiline_note_block(f, lines, nested=True)
f.write("\n")
# Mark that the global sources index has been generated so we don't do this again
self._sources_index_generated = True
def _escape_markdown(self, text: str) -> str:
"""Escape markdown emphasis characters in text to prevent accidental formatting.
Escapes: backslash, asterisk, underscore, backtick, and tilde.
Does not escape bracket characters so links still render.
"""
if not text:
return ""
# Escape backslash first
text = text.replace("\\", "\\\\")
# Escape characters that trigger emphasis or code spans
for ch in ('*', '_', '`', '~'):
text = text.replace(ch, f"\\{ch}")
return text
def _repair_broken_html_tags(self, text: str) -> str:
"""Repair HTML tags that were broken across lines for a small whitelist of tags.
Strategy:
- Find all substrings that look like tags (<...>), possibly spanning lines.
- For each tag, remove newlines inside the tag only if the tag name (after
removing newlines) is in a safe whitelist. This joins broken tag names
like "<b\nr>" into "<br>" while leaving other tags alone.
"""
if not text or '<' not in text:
return text
WHITELIST = {"br", "b", "i", "strong", "em", "a", "span", "div", "p", "ul", "li"}
def repl(m: re.Match) -> str:
raw = m.group(0)
content = raw[1:-1] # inside <...>
# Remove newline and carriage returns to inspect tag name
content_no_nl = content.replace('\n', '').replace('\r', '')
# Extract tag name (skip leading '/')
name_m = re.match(r"\s*/?\s*([A-Za-z0-9]+)", content_no_nl)
if name_m and name_m.group(1).lower() in WHITELIST:
# Rebuild tag with newlines removed but preserve other spaces
repaired = '<' + content_no_nl + '>'
return repaired
return raw
return re.sub(r'<[^>]*>', repl, text, flags=re.DOTALL)
def _write_multiline_note_block(self, f, lines: List[str], nested: bool = True) -> None:
"""Write a multi-line note block.
- If nested is True, writes a nested list bullet (3 spaces + '-') for the first
line and indented continuation lines for the rest. All lines except the
last will end with two trailing spaces to force a hard line break; the
final CONT line is written without the trailing spaces to avoid an extra
blank line after the block.
- If nested is False, writes plain lines; trailing two spaces are added to
all but the last non-empty line.
"""
if not lines:
return
total = len(lines)
if nested:
indent = " "
cont_indent = " "
# First line as a nested bullet; add two spaces if there are continuation lines
if total > 1:
f.write(f"{indent}- {lines[0]} \n")
else:
f.write(f"{indent}- {lines[0]}\n")
for idx, cont in enumerate(lines[1:], start=1):
# For continuation lines, add two spaces except for the last line
if idx < total - 1:
f.write(f"{cont_indent}{cont} \n")
else:
f.write(f"{cont_indent}{cont}\n")
else:
# Non-nested: add two spaces to all non-empty lines except the last non-empty
non_empty = [ln for ln in lines if ln.strip()]
last_non_empty = non_empty[-1] if non_empty else None
for ln in lines:
if not ln.strip():
f.write("\n")
elif ln == last_non_empty:
f.write(f"{ln}\n")
else:
f.write(f"{ln} \n")
def _write_metadata(self, f, key: str, value: str): def _write_metadata(self, f, key: str, value: str):
""" """
Write a visible Obsidian metadata line for the given key and value. Write a visible Obsidian metadata line for the given key and value.
@@ -520,4 +774,18 @@ class MarkdownGenerator:
) )
logger.info(f"Successfully generated {len(paths)} notes") logger.info(f"Successfully generated {len(paths)} notes")
# Generate global sources index once (expensive) using the first available parser
if not self._sources_index_generated:
parser = None
for ind in individuals:
parser = getattr(ind, 'gedcom', None)
if parser:
break
if parser:
try:
self._generate_sources_index(parser)
except Exception:
logger.exception('Failed to generate sources index')
return paths return paths
+110
View File
@@ -0,0 +1,110 @@
from pathlib import Path
copilot-pull-request-reviewer[bot] commented 2026-04-17 21:49:53 +02:00 (Migrated from github.com)
Review

These imports are inconsistent with the repo’s pytest configuration (pythonpath = src). With src/ added directly to sys.path and no src/__init__.py, from src.gedcom_parser ... will fail (it will look for src/src/gedcom_parser.py). Import the modules the same way other tests do (e.g., from gedcom_parser import GedcomParser, etc.).

from gedcom_parser import GedcomParser
from individual import Individual
from markdown_generator import MarkdownGenerator
These imports are inconsistent with the repo’s pytest configuration (`pythonpath = src`). With `src/` added directly to `sys.path` and no `src/__init__.py`, `from src.gedcom_parser ...` will fail (it will look for `src/src/gedcom_parser.py`). Import the modules the same way other tests do (e.g., `from gedcom_parser import GedcomParser`, etc.). ```suggestion from gedcom_parser import GedcomParser from individual import Individual from markdown_generator import MarkdownGenerator ```
coderabbitai[bot] commented 2026-04-17 21:50:49 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟡 Minor

Test name doesn't match what it exercises.

test_note_cont_and_conc_inline declares an inline NOTE @N1@ pointer on @I1@, which routes through the pointer-resolution branch of _resolve_gedcom_text — the same branch that test_note_reference_to_note_with_cont_conc covers. There is currently no coverage for the inline branch (CONT/CONC as direct children of an INDI-level 1 NOTE <text>). Consider either renaming this test or adding a case like:

0 `@I1`@ INDI
1 NAME John /Doe/
1 NOTE First line
2 CONC -continued
2 CONT Next paragraph

to exercise the element is not None path in _resolve_gedcom_text.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_notes_cont_conc.py` around lines 15 - 45, The test currently
exercises the pointer-resolution path of _resolve_gedcom_text because the INDI
uses a NOTE pointer; change the test to cover the inline NOTE branch by
replacing the pointer-style note with an inline NOTE child on the INDI (e.g.,
put the CONT/CONC lines as level-2 children under "1 NOTE" on `@I1`@) or add a new
test that follows that structure; update the test name to reflect whether it now
covers the inline branch (e.g., test_note_cont_and_conc_inline ->
test_note_cont_and_conc_inline_in_indi) and keep assertions for CONC
concatenation and CONT newline behavior.

✅ Addressed in commit 96da61c

_⚠️ Potential issue_ | _🟡 Minor_ **Test name doesn't match what it exercises.** `test_note_cont_and_conc_inline` declares an inline `NOTE `@N1`@` pointer on `@I1@`, which routes through the pointer-resolution branch of `_resolve_gedcom_text` — the same branch that `test_note_reference_to_note_with_cont_conc` covers. There is currently no coverage for the *inline* branch (CONT/CONC as direct children of an INDI-level `1 NOTE <text>`). Consider either renaming this test or adding a case like: ``` 0 `@I1`@ INDI 1 NAME John /Doe/ 1 NOTE First line 2 CONC -continued 2 CONT Next paragraph ``` to exercise the `element is not None` path in `_resolve_gedcom_text`. <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against the current code and only fix it if needed. In `@tests/test_notes_cont_conc.py` around lines 15 - 45, The test currently exercises the pointer-resolution path of _resolve_gedcom_text because the INDI uses a NOTE pointer; change the test to cover the inline NOTE branch by replacing the pointer-style note with an inline NOTE child on the INDI (e.g., put the CONT/CONC lines as level-2 children under "1 NOTE" on `@I1`@) or add a new test that follows that structure; update the test name to reflect whether it now covers the inline branch (e.g., test_note_cont_and_conc_inline -> test_note_cont_and_conc_inline_in_indi) and keep assertions for CONC concatenation and CONT newline behavior. ``` </details> <!-- fingerprinting:phantom:medusa:nectarine:ccd9701b-1961-486a-aa73-330d7083f6ad --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 96da61c
from src.gedcom_parser import GedcomParser
from src.individual import Individual
from src.markdown_generator import MarkdownGenerator
def _make_output_dir(tmp_path):
out = tmp_path / "output"
out.mkdir()
return out
class TestNotesContConc:
def test_note_cont_and_conc_inline(self, tmp_path):
gedcom = """0 HEAD
1 SOUR TestApp
1 GEDC
2 VERS 5.5.1
1 CHAR UTF-8
0 @N1@ NOTE
1 CONT First line
1 CONC -continued
1 CONT Next paragraph
0 @I1@ INDI
1 NAME John /Doe/
1 NOTE @N1@
0 TRLR
"""
f = tmp_path / "note.ged"
f.write_text(gedcom, encoding='utf-8')
parser = GedcomParser(f)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
out = _make_output_dir(tmp_path)
gen = MarkdownGenerator(out)
note = gen.generate_note(person)
content = note.read_text()
# Ensure CONC concatenated without newline
assert "First line-continued" in content
# Ensure CONT produced a newline (rendered as separate paragraph / hard break)
assert "Next paragraph" in content
def test_note_reference_to_note_with_cont_conc(self, tmp_path):
gedcom = """0 HEAD
1 SOUR TestApp
1 GEDC
2 VERS 5.5.1
1 CHAR UTF-8
0 @N1@ NOTE
1 CONT Line one
1 CONC continued
1 CONT Line two
0 @I1@ INDI
1 NAME Jane /Smith/
1 NOTE @N1@
0 TRLR
"""
f = tmp_path / "note_ref.ged"
f.write_text(gedcom, encoding='utf-8')
parser = GedcomParser(f)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
out = _make_output_dir(tmp_path)
gen = MarkdownGenerator(out)
note = gen.generate_note(person)
content = note.read_text()
assert "Line onecontinued" in content
assert "Line two" in content
def test_source_note_cont_conc_and_index(self, tmp_path):
gedcom = """0 HEAD
1 SOUR TestApp
1 GEDC
2 VERS 5.5.1
1 CHAR UTF-8
0 @N1@ NOTE
1 CONT Source line
1 CONC -more
0 @S1@ SOUR
1 TITL Example Source
1 NOTE @N1@
0 @I1@ INDI
1 NAME Alpha /Beta/
1 SOUR @S1@
0 TRLR
"""
f = tmp_path / "sources.ged"
f.write_text(gedcom, encoding='utf-8')
parser = GedcomParser(f)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
out = _make_output_dir(tmp_path)
gen = MarkdownGenerator(out)
# generate a person note which should also trigger sources index generation
gen.generate_note(person)
index = out / 'sources' / 'Index.md'
assert index.exists()
content = index.read_text()
# Ensure concatenation in source note
assert 'Source line-more' in content
+104
View File
@@ -0,0 +1,104 @@
import pytest
from gedcom_parser import GedcomParser
from individual import Individual
from markdown_generator import MarkdownGenerator
coderabbitai[bot] commented 2026-04-17 21:50:49 +02:00 (Migrated from github.com)
Review

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect conftest/pytest config and confirm which import style is supported.
fd -a -H '^(conftest\.py|pytest\.ini|pyproject\.toml|setup\.cfg|tox\.ini)$'
echo '--- conftest.py contents (if any) ---'
fd -H '^conftest\.py$' --exec cat {}
echo '--- pytest config in pyproject.toml ---'
fd -H '^pyproject\.toml$' --exec rg -n -A5 '\[tool\.pytest' {}
echo '--- test import lines across tests/ ---'
rg -n '^from (src\.)?(gedcom_parser|individual|markdown_generator)' tests

Repository: AlexKucera/gedcom-to-markdown

Length of output: 4661


🏁 Script executed:

cat /home/jailuser/git/pytest.ini

Repository: AlexKucera/gedcom-to-markdown

Length of output: 318


Fix import paths to match pytest configuration.

The pytest.ini file configures pythonpath = src, which adds the src/ directory to sys.path. This means imports should use the style from gedcom_parser import ... (without the src. prefix).

The file test_notes_cont_conc.py currently imports from src.gedcom_parser import ..., which contradicts the pytest configuration and differs from the other five test files (test_sources.py, test_individual.py, test_index_generator.py, test_markdown_generator.py, test_gedcom_parser.py) which all use the correct non-prefixed style.

Update test_notes_cont_conc.py to remove the src. prefix from its imports to align with the pytest configuration and the rest of the test suite.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_sources.py` around lines 3 - 5, Update the imports in
test_notes_cont_conc.py to remove the src. prefix so they match pytest.ini's
pythonpath and the other tests; specifically change any imports like from
src.gedcom_parser import GedcomParser (and similarly for Individual,
MarkdownGenerator, etc.) to from gedcom_parser import GedcomParser (and from
individual import Individual, from markdown_generator import MarkdownGenerator)
so the test uses the same non-prefixed module names as the rest of the suite.
_⚠️ Potential issue_ | _🟠 Major_ <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash # Inspect conftest/pytest config and confirm which import style is supported. fd -a -H '^(conftest\.py|pytest\.ini|pyproject\.toml|setup\.cfg|tox\.ini)$' echo '--- conftest.py contents (if any) ---' fd -H '^conftest\.py$' --exec cat {} echo '--- pytest config in pyproject.toml ---' fd -H '^pyproject\.toml$' --exec rg -n -A5 '\[tool\.pytest' {} echo '--- test import lines across tests/ ---' rg -n '^from (src\.)?(gedcom_parser|individual|markdown_generator)' tests ``` Repository: AlexKucera/gedcom-to-markdown Length of output: 4661 --- 🏁 Script executed: ```shell cat /home/jailuser/git/pytest.ini ``` Repository: AlexKucera/gedcom-to-markdown Length of output: 318 --- </details> **Fix import paths to match pytest configuration.** The `pytest.ini` file configures `pythonpath = src`, which adds the `src/` directory to `sys.path`. This means imports should use the style `from gedcom_parser import ...` (without the `src.` prefix). The file `test_notes_cont_conc.py` currently imports `from src.gedcom_parser import ...`, which contradicts the pytest configuration and differs from the other five test files (`test_sources.py`, `test_individual.py`, `test_index_generator.py`, `test_markdown_generator.py`, `test_gedcom_parser.py`) which all use the correct non-prefixed style. Update `test_notes_cont_conc.py` to remove the `src.` prefix from its imports to align with the pytest configuration and the rest of the test suite. <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against the current code and only fix it if needed. In `@tests/test_sources.py` around lines 3 - 5, Update the imports in test_notes_cont_conc.py to remove the src. prefix so they match pytest.ini's pythonpath and the other tests; specifically change any imports like from src.gedcom_parser import GedcomParser (and similarly for Individual, MarkdownGenerator, etc.) to from gedcom_parser import GedcomParser (and from individual import Individual, from markdown_generator import MarkdownGenerator) so the test uses the same non-prefixed module names as the rest of the suite. ``` </details> <!-- fingerprinting:phantom:medusa:nectarine:ccd9701b-1961-486a-aa73-330d7083f6ad --> <!-- This is an auto-generated comment by CodeRabbit -->
def _make_output_dir(tmp_path):
out = tmp_path / "output"
out.mkdir()
return out
class TestSourcesSection:
def test_sources_happy_path_with_publ_and_title(self, tmp_path):
gedcom = """0 HEAD
1 SOUR TestApp
1 GEDC
2 VERS 5.5.1
1 CHAR UTF-8
0 @S1@ SOUR
1 TITL Overland Travels Pioneer Detail
1 PUBL http://history.example/pioneer?id=6262
0 @I1@ INDI
1 NAME John /Doe/
1 SOUR @S1@
0 TRLR
"""
f = tmp_path / "sources.ged"
f.write_text(gedcom, encoding='utf-8')
parser = GedcomParser(f)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
out = _make_output_dir(tmp_path)
gen = MarkdownGenerator(out)
note = gen.generate_note(person)
content = note.read_text()
assert '## Sources' in content
# Whitespace in title should be collapsed
assert '1. [Overland Travels Pioneer Detail](http://history.example/pioneer?id=6262)' in content
# Also an Index file should be created in sources/Index.md
index = out / 'sources' / 'Index.md'
assert index.exists()
idx_content = index.read_text()
assert '[Overland Travels Pioneer Detail](http://history.example/pioneer?id=6262)' in idx_content
def test_sources_title_only_no_publ(self, tmp_path):
gedcom = """0 HEAD
1 SOUR TestApp
1 GEDC
2 VERS 5.5.1
1 CHAR UTF-8
0 @S2@ SOUR
1 TITL Local Archive Record
0 @I1@ INDI
1 NAME Jane /Smith/
1 SOUR @S2@
0 TRLR
"""
f = tmp_path / "sources2.ged"
f.write_text(gedcom, encoding='utf-8')
parser = GedcomParser(f)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
out = _make_output_dir(tmp_path)
gen = MarkdownGenerator(out)
note = gen.generate_note(person)
content = note.read_text()
assert '## Sources' in content
assert '1. Local Archive Record' in content
def test_sources_publ_but_no_title_uses_url_as_text(self, tmp_path):
gedcom = """0 HEAD
1 SOUR TestApp
1 GEDC
2 VERS 5.5.1
1 CHAR UTF-8
0 @S3@ SOUR
1 PUBL https://example.org/doc/123
0 @I1@ INDI
1 NAME Alice /Doe/
1 SOUR @S3@
0 TRLR
"""
f = tmp_path / "sources3.ged"
f.write_text(gedcom, encoding='utf-8')
parser = GedcomParser(f)
individuals = parser.get_individuals()
person = Individual(individuals[0], parser.parser)
out = _make_output_dir(tmp_path)
gen = MarkdownGenerator(out)
note = gen.generate_note(person)
content = note.read_text()
assert '## Sources' in content
assert '1. [https://example.org/doc/123](https://example.org/doc/123)' in content