Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c68264978d | ||
|
|
676b4014ca | ||
|
|
96da61c1ff | ||
|
|
6259bfffd6 | ||
|
|
1f48292e60 |
No files matched your search
+195
-25
@@ -17,6 +17,98 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
EVENT_TAGS = {"BIRT", "DEAT", "MARR", "OCCU", "EDUC", "RESI", "BURI"}
|
||||
|
||||
def collapse_single_line(text: str) -> str:
|
||||
"""Normalize whitespace on a single logical line.
|
||||
|
||||
This helper collapses runs of whitespace (spaces, tabs) into single spaces
|
||||
and trims leading/trailing whitespace. It is intended for short metadata
|
||||
fields such as titles, publication strings, or other single-line values
|
||||
where internal spacing should be normalized but line breaks must be
|
||||
preserved elsewhere.
|
||||
|
||||
Examples:
|
||||
>>> collapse_single_line(" Overland Travels Pioneer Detail ")
|
||||
'Overland Travels Pioneer Detail'
|
||||
|
||||
Returns an empty string when passed a false-y value.
|
||||
"""
|
||||
return " ".join(text.split()).strip() if text else ""
|
||||
|
||||
|
||||
def resolve_gedcom_text(parser, value: str, element=None) -> str:
|
||||
"""Resolve a GEDCOM text value including CONT/CONC continuations.
|
||||
|
||||
GEDCOM continuation rules:
|
||||
- CONC: concatenate to previous line (no newline inserted)
|
||||
- CONT: start a new line (insert a newline in the output)
|
||||
|
||||
This helper handles both pointer-style NOTE references (e.g. "@N1@") and
|
||||
inline NOTE bodies (where the parent element contains CONT/CONC children).
|
||||
|
||||
Parameters
|
||||
----------
|
||||
parser:
|
||||
The GEDCOM parser instance used to resolve pointer targets via
|
||||
parser.get_element_dictionary().
|
||||
value (str):
|
||||
The immediate value of the tag. May be a pointer ("@N1@") or plain
|
||||
text. When it's a pointer, the referenced element is resolved and its
|
||||
child CONT/CONC lines are applied.
|
||||
element:
|
||||
Optional element whose child CONT/CONC children should be read when
|
||||
resolving inline NOTE content. Provide this when `value` is an inline
|
||||
value and the continuations are stored on the element itself.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
Resolved text with CONC concatenated directly and CONT lines separated
|
||||
by a single newline. Empty CONT/CONC values are skipped.
|
||||
|
||||
Examples
|
||||
--------
|
||||
Given a referenced NOTE element with:
|
||||
0 @N1@ NOTE
|
||||
1 CONT First line
|
||||
1 CONC -continued
|
||||
1 CONT Second para
|
||||
Calling resolve_gedcom_text(parser, "@N1@") returns:
|
||||
"First line-continued\nSecond para"
|
||||
"""
|
||||
# Pointer/reference to another element (e.g., NOTE record)
|
||||
if value and value.startswith("@") and value.endswith("@"):
|
||||
target = parser.get_element_dictionary().get(value)
|
||||
if not target:
|
||||
return ""
|
||||
text = target.get_value() or ""
|
||||
# Respect CONT vs CONC semantics: CONT => newline, CONC => concatenate.
|
||||
# An empty CONT line represents a blank line in GEDCOM and must still
|
||||
# contribute a newline so paragraph breaks are preserved.
|
||||
for sub in target.get_child_elements():
|
||||
tag = sub.get_tag()
|
||||
val = (sub.get_value() or "")
|
||||
if tag == "CONC":
|
||||
if val:
|
||||
text += val
|
||||
elif tag == "CONT":
|
||||
text += "\n" + val
|
||||
return text
|
||||
|
||||
# Inline text with possible CONT/CONC children.
|
||||
# Same rule: empty CONC is a no-op, but empty CONT preserves a blank line.
|
||||
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 tag == "CONC":
|
||||
if val:
|
||||
text += val
|
||||
elif tag == "CONT":
|
||||
text += "\n" + val
|
||||
return text
|
||||
|
||||
|
||||
class Individual:
|
||||
"""
|
||||
Represents an individual person in the family tree.
|
||||
@@ -57,6 +149,18 @@ class Individual:
|
||||
"""
|
||||
return self.element.get_pointer()
|
||||
|
||||
def get_fs_id(self) -> str:
|
||||
"""
|
||||
Return the FamilySearch Tree ID (`_FSFTID`) if present.
|
||||
|
||||
Returns:
|
||||
str: FamilySearch Tree ID value, or an empty string when not available.
|
||||
"""
|
||||
for child in self.element.get_child_elements():
|
||||
if child.get_tag() == "_FSFTID":
|
||||
return child.get_value() or ""
|
||||
return ""
|
||||
|
||||
def get_names(self) -> Tuple[str, str]:
|
||||
"""
|
||||
Return the individual's first and last name with surrounding whitespace removed.
|
||||
@@ -450,6 +554,33 @@ class Individual:
|
||||
|
||||
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:
|
||||
"""Instance-level wrapper for the module resolve_gedcom_text helper.
|
||||
|
||||
This method forwards to the module-level resolve_gedcom_text function
|
||||
passing the parser instance bound to this Individual. It exists to keep
|
||||
call sites on the Individual instance simple while centralizing the
|
||||
continuation resolution logic in one place.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
value (str): The immediate tag value (may be a pointer like "@N1@"
|
||||
or inline text).
|
||||
element: Optional element to read CONT/CONC children from when resolving
|
||||
inline note content.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str: Resolved note/text with CONT/CONC applied.
|
||||
"""
|
||||
return resolve_gedcom_text(self.gedcom, value, element)
|
||||
|
||||
def get_notes(self) -> List[str]:
|
||||
"""
|
||||
Return the person's notes with inline continuations and referenced NOTE records resolved.
|
||||
@@ -460,34 +591,73 @@ class Individual:
|
||||
List[str]: Note texts with continuations and referenced NOTE content merged; empty or unresolved notes are omitted.
|
||||
"""
|
||||
notes = []
|
||||
|
||||
for child in self.element.get_child_elements():
|
||||
if child.get_tag() == "NOTE":
|
||||
note_text = child.get_value() or ""
|
||||
|
||||
# If note_text starts with @, it's a reference to a NOTE record
|
||||
if note_text.startswith("@") and note_text.endswith("@"):
|
||||
# Resolve the reference
|
||||
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())
|
||||
|
||||
if child.get_tag() != "NOTE":
|
||||
continue
|
||||
raw = child.get_value() or ""
|
||||
text = self._resolve_gedcom_text(raw, child)
|
||||
if text and not text.startswith("@"):
|
||||
notes.append(self._collapse_preserve_lines(text))
|
||||
return notes
|
||||
|
||||
def get_sources(self) -> List[Dict[str, str]]:
|
||||
"""Extract source references associated with this individual.
|
||||
|
||||
Each source entry returned is a dictionary with keys:
|
||||
- "title": The source title (single-line whitespace collapsed)
|
||||
- "publ": The publication or URL (single-line whitespace collapsed)
|
||||
- "note": The NOTE text for the source with original line breaks preserved
|
||||
(CONT produces a newline, CONC concatenates). Empty continuation
|
||||
lines are skipped.
|
||||
|
||||
The method handles two forms of source associations:
|
||||
1. Pointer-style references (1 SOUR @S1@) where @S1@ points to a separate
|
||||
SOURCE record elsewhere in the GEDCOM file. In this case the referenced
|
||||
SOURCE element's TITL/PUBL/NOTE children are resolved.
|
||||
2. Inline SOURCE blocks nested under the individual (1 SOUR ... with
|
||||
sub-tags at level 2). These are read directly from the child's children.
|
||||
|
||||
Notes are resolved via the shared resolve_gedcom_text helper so pointer
|
||||
references and inline NOTE children are handled consistently.
|
||||
"""
|
||||
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 ""
|
||||
# Treat as a pointer only if it both starts and ends with '@' (e.g., @S1@)
|
||||
if src_ref and src_ref.startswith("@") and src_ref.endswith("@"):
|
||||
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]:
|
||||
"""
|
||||
Extract story and narrative records referenced by custom `_STO` tags for this individual.
|
||||
|
||||
+327
-3
@@ -8,8 +8,9 @@ in the family tree.
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
import logging
|
||||
import re
|
||||
|
||||
from individual import Individual
|
||||
from individual import Individual, collapse_single_line, resolve_gedcom_text
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -56,6 +57,7 @@ class MarkdownGenerator:
|
||||
self.use_subdirectories = use_subdirectories
|
||||
self.generated_stories = {} # Track generated story files
|
||||
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 _coordinate_values(
|
||||
self, data: dict, lat_key: str = "lat", long_key: str = "long"
|
||||
@@ -121,6 +123,21 @@ class MarkdownGenerator:
|
||||
self._write_children(f, individual)
|
||||
self._write_images(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')
|
||||
# Prevent repeated expensive retries on persistent failures (e.g., IO/permissions)
|
||||
self._sources_index_generated = True
|
||||
|
||||
return file_path
|
||||
|
||||
@@ -136,8 +153,11 @@ class MarkdownGenerator:
|
||||
|
||||
birth = individual.get_birth_info()
|
||||
death = individual.get_death_info()
|
||||
fs_id = individual.get_fs_id()
|
||||
|
||||
f.write(f"ID: {individual.get_id()}\n")
|
||||
if fs_id:
|
||||
f.write(f"FamilySearch ID: {fs_id}\n")
|
||||
f.write(f"Name: {individual.get_full_name()}\n")
|
||||
|
||||
# Lived years
|
||||
@@ -427,7 +447,7 @@ class MarkdownGenerator:
|
||||
def _write_notes(self, f, individual: Individual):
|
||||
"""
|
||||
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.
|
||||
|
||||
Parameters:
|
||||
@@ -444,7 +464,13 @@ class MarkdownGenerator:
|
||||
|
||||
# Write regular 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
|
||||
if stories:
|
||||
@@ -476,6 +502,290 @@ class MarkdownGenerator:
|
||||
|
||||
f.write("\n")
|
||||
|
||||
def _collapse_single_line(self, text: str) -> str:
|
||||
"""Normalize a single-line string's internal whitespace.
|
||||
|
||||
This is a thin adapter that delegates to the shared collapse_single_line
|
||||
helper located in the individual module. It is kept on the generator
|
||||
class for convenience and to match the previous API; callers should use
|
||||
this method when normalizing titles and publication strings that must
|
||||
not contain extra internal whitespace.
|
||||
"""
|
||||
return collapse_single_line(text)
|
||||
|
||||
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 text is escaped to prevent markdown emphasis characters from triggering formatting.
|
||||
"""
|
||||
title = self._collapse_single_line(title)
|
||||
publ = self._collapse_single_line(publ)
|
||||
escaped_title = self._escape_markdown(title)
|
||||
|
||||
if title and publ:
|
||||
return f"[{escaped_title}]({publ})"
|
||||
if title:
|
||||
return escaped_title
|
||||
if publ:
|
||||
return f"[{publ}]({publ})"
|
||||
return "(Unknown source)"
|
||||
|
||||
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 as an indented
|
||||
escaped note block beneath it (nested, non-italicized) to avoid accidental Markdown emphasis.
|
||||
"""
|
||||
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 global sources Index.md from the GEDCOM element dictionary.
|
||||
|
||||
This method scans the parser's element dictionary for SOURCE (SOUR)
|
||||
records and writes a single streamed Index.md file inside the output
|
||||
'sources/' directory. To avoid using excessive memory when many source
|
||||
records exist, entries are written to disk as they are discovered rather
|
||||
than being accumulated in memory.
|
||||
|
||||
The created Index.md contains a numbered list of sources; if a source
|
||||
has associated NOTE text, the NOTE is written as a nested, escaped
|
||||
indented block beneath the numbered entry. The function repairs certain
|
||||
HTML tags that may have been split across GEDCOM CONT lines and escapes
|
||||
markdown emphasis characters in NOTE lines to avoid accidental
|
||||
formatting.
|
||||
|
||||
The method sets the generator's _sources_index_generated flag on success
|
||||
or when encountering unrecoverable errors so that subsequent calls avoid
|
||||
re-scanning the element dictionary.
|
||||
"""
|
||||
try:
|
||||
elem_dict = parser.get_element_dictionary()
|
||||
except (AttributeError, ValueError) as e:
|
||||
logger.exception("Failed to retrieve GEDCOM element dictionary for sources index: %s", e)
|
||||
# Prevent repeated attempts on failure
|
||||
self._sources_index_generated = True
|
||||
return
|
||||
except Exception:
|
||||
# Unexpected failure type: log at debug and mark generated to avoid retry storms
|
||||
logger.exception("Unexpected error retrieving GEDCOM element dictionary for sources index")
|
||||
self._sources_index_generated = True
|
||||
return
|
||||
|
||||
# Stream sources to the Index.md file as we discover them to avoid
|
||||
# accumulating a potentially very large in-memory list.
|
||||
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"
|
||||
|
||||
i = 0
|
||||
index_file = sources_dir / "Index.md"
|
||||
|
||||
# Delay creating the file and directory until the first source is found so
|
||||
# that no empty Index.md is left behind when there are no SOUR records.
|
||||
f = None
|
||||
try:
|
||||
for elem in elem_dict.values():
|
||||
try:
|
||||
if elem.get_tag() != "SOUR":
|
||||
continue
|
||||
except (AttributeError, ValueError) as e:
|
||||
logger.debug("Skipping non-source element or malformed element during sources scan: %s", e)
|
||||
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 ""
|
||||
# Use shared resolver to handle pointer vs inline NOTE with CONT/CONC semantics
|
||||
note_text = resolve_gedcom_text(parser, note_val, sc)
|
||||
|
||||
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:
|
||||
if f is None:
|
||||
# First source found: create directory and open file
|
||||
sources_dir.mkdir(parents=True, exist_ok=True)
|
||||
f = open(index_file, "w", encoding="utf-8")
|
||||
f.write("# Sources Index\n\n")
|
||||
i += 1
|
||||
entry = self._format_source_entry(title, publ)
|
||||
f.write(f"{i}. {entry}\n")
|
||||
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)
|
||||
|
||||
if f is not None:
|
||||
f.write("\n")
|
||||
finally:
|
||||
if f is not None:
|
||||
f.close()
|
||||
|
||||
# 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 a small set of HTML tags that may have been split across GEDCOM lines.
|
||||
|
||||
Some GEDCOM exports break existing HTML fragments across CONT/CONC lines,
|
||||
which can cause HTML tags (e.g. "<br>") to be split such that Markdown
|
||||
or HTML rendering becomes corrupted (for example "<b\nr>" becoming a
|
||||
literal "<b" followed by "r>"). This function attempts a conservative
|
||||
repair for a safe whitelist of simple tags by removing newline and
|
||||
carriage return characters that occur inside a single tag token.
|
||||
|
||||
Notes:
|
||||
- This is intentionally conservative: it does not attempt to join broken
|
||||
attributes or complex tags, and it only acts on a small whitelist of
|
||||
tag names commonly used in source text (br, b, i, strong, em, a,
|
||||
span, div, p, ul, li).
|
||||
- The function preserves all other tag-like text unchanged.
|
||||
|
||||
Returns the (possibly repaired) text.
|
||||
"""
|
||||
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 into the open file.
|
||||
|
||||
This helper emits a block representing multi-line note text in a way that
|
||||
is maximally compatible with common Markdown renderers used by editors
|
||||
like Obsidian, BBEdit, and Nova. Two behaviors are supported:
|
||||
|
||||
- nested=True: Emit a nested list item. The first line is written as a
|
||||
nested bullet (" - first line"). Continuation lines are indented
|
||||
and written beneath the bullet. All continuation lines except the
|
||||
final one are suffixed with two spaces to generate an explicit
|
||||
hard-break (<br>) in Markdown renderers. The final line is written
|
||||
without trailing spaces so the block does not create an extra blank
|
||||
paragraph after it.
|
||||
|
||||
- nested=False: Emit plain lines (no list bullet). All non-empty lines
|
||||
except the last non-empty line are suffixed with two spaces. Empty
|
||||
input lines are preserved as blank lines.
|
||||
|
||||
Parameters:
|
||||
f: file-like writable object opened with utf-8 encoding.
|
||||
lines: list of text lines (already escaped if required).
|
||||
nested: whether to render the block as a nested list under a parent
|
||||
list item (True) or as a flat paragraph/list of lines (False).
|
||||
|
||||
Rationale:
|
||||
Trailing two spaces are used to force <br> behavior in many Markdown
|
||||
renderers. The special handling of the final line avoids producing an
|
||||
extra blank paragraph after the note block.
|
||||
"""
|
||||
if not lines:
|
||||
return
|
||||
|
||||
total = len(lines)
|
||||
if nested:
|
||||
# Use 4-space indent so nested content is correctly parsed as continuation
|
||||
# of the parent ordered list item even for multi-digit list numbers (e.g. "10.")
|
||||
# in CommonMark-compliant renderers.
|
||||
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
|
||||
# Determine the index of the last non-empty line to make the decision
|
||||
# deterministic even when the same line text appears multiple times.
|
||||
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:
|
||||
f.write(f"{ln}\n")
|
||||
else:
|
||||
f.write(f"{ln} \n")
|
||||
|
||||
def _write_metadata(self, f, key: str, value: str):
|
||||
"""
|
||||
Write a visible Obsidian metadata line for the given key and value.
|
||||
@@ -550,4 +860,18 @@ class MarkdownGenerator:
|
||||
)
|
||||
|
||||
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
|
||||
@@ -41,6 +41,7 @@ def sample_gedcom_content():
|
||||
1 NAME John /Doe/
|
||||
2 GIVN John
|
||||
2 SURN Doe
|
||||
1 _FSFTID G123-ABC
|
||||
1 SEX M
|
||||
1 BIRT
|
||||
2 DATE 1 JAN 1950
|
||||
|
||||
@@ -81,6 +81,15 @@ class TestIndividualBasicInfo:
|
||||
"""Test gender extraction."""
|
||||
assert john_doe.get_gender() == 'M'
|
||||
|
||||
def test_get_fs_id(self, john_doe, sample_gedcom_file):
|
||||
"""Test FamilySearch Tree ID extraction from _FSFTID tag."""
|
||||
assert john_doe.get_fs_id() == 'G123-ABC'
|
||||
parser = GedcomParser(sample_gedcom_file)
|
||||
individuals = parser.get_individuals()
|
||||
jane = [ind for ind in individuals if 'Jane' in str(ind.get_name())]
|
||||
jane_doe = Individual(jane[0], parser.parser)
|
||||
assert jane_doe.get_fs_id() == ''
|
||||
|
||||
def test_get_gender_default_unknown(self, sample_gedcom_file):
|
||||
"""Test that missing gender defaults to 'U'."""
|
||||
gedcom_content = """0 HEAD
|
||||
|
||||
@@ -129,6 +129,7 @@ class TestMetadataFormatting:
|
||||
|
||||
# Check for YAML frontmatter metadata
|
||||
assert 'ID: I1' in content
|
||||
assert 'FamilySearch ID: G123-ABC' in content
|
||||
assert 'Name: John Doe' in content
|
||||
assert 'Sex: M' in content
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
from pathlib import Path
|
||||
|
||||
from gedcom_parser import GedcomParser
|
||||
from individual import Individual
|
||||
from 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_in_indi(self, tmp_path):
|
||||
gedcom = """0 HEAD
|
||||
1 SOUR TestApp
|
||||
1 GEDC
|
||||
2 VERS 5.5.1
|
||||
1 CHAR UTF-8
|
||||
0 @I1@ INDI
|
||||
1 NAME John /Doe/
|
||||
1 NOTE
|
||||
2 CONT First line
|
||||
2 CONC -continued
|
||||
2 CONT Next paragraph
|
||||
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
|
||||
@@ -0,0 +1,104 @@
|
||||
import pytest
|
||||
|
||||
from gedcom_parser import GedcomParser
|
||||
from individual import Individual
|
||||
from markdown_generator import MarkdownGenerator
|
||||
|
||||
|
||||
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
|
||||
Reference in new issue
Block a user