diff --git a/README.md b/README.md index 5344364..12f06fe 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ This will automatically: By default, the converter creates an **organized directory structure**: -``` +```text output/ ├── Index.md # Alphabetical index of all people ├── people/ # Person markdown files @@ -149,7 +149,7 @@ The `Index.md` file at the root contains an alphabetical listing of all individu ## Project Structure -``` +```text src/ ├── gedcom_parser.py # GEDCOM file parsing ├── individual.py # Person data model @@ -170,7 +170,7 @@ src/ Some GEDCOM files exported from macOS applications use old Mac-style line endings (CR only). **This is automatically detected and fixed** by the converter. If you see a warning message like: -``` +```text WARNING - Detected old Mac-style (CR-only) line endings in GEDCOM file. Converting to Unix-style (LF) line endings... ``` diff --git a/pytest.ini b/pytest.ini index 909ef9b..296c840 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,5 +1,6 @@ [pytest] testpaths = tests +pythonpath = src python_files = test_*.py python_classes = Test* python_functions = test_* diff --git a/src/index_generator.py b/src/index_generator.py index 7482da6..e7eeb88 100644 --- a/src/index_generator.py +++ b/src/index_generator.py @@ -8,6 +8,7 @@ family tree. from pathlib import Path from typing import List import logging +import re from individual import Individual @@ -66,7 +67,7 @@ class IndexGenerator: current_letter = "" for individual in sorted_individuals: - first, last = individual.get_names() + _, last = individual.get_names() # Write letter header if changed if last: @@ -85,7 +86,11 @@ class IndexGenerator: # Format life span if birth_info["year"] or death_info["date"]: - death_year = death_info["date"][:4] if death_info["date"] else "" + death_year = "" + if death_info["date"]: + match = re.search(r"(\d{4})\b", death_info["date"]) + if match: + death_year = match.group(1) life_span = f" ({birth_info['year']}-{death_year})" else: life_span = "" diff --git a/src/individual.py b/src/individual.py index 9ec429e..aa00f44 100644 --- a/src/individual.py +++ b/src/individual.py @@ -7,6 +7,7 @@ extracting all relevant information from GEDCOM data. from typing import List, Dict, Tuple import logging +import re from gedcom.element.individual import IndividualElement import gedcom.tags @@ -24,18 +25,18 @@ class Individual: images, and notes. """ - def __init__(self, element: IndividualElement, gedcom_parser): + def __init__(self, element: IndividualElement, parser): """ - Create an Individual wrapper around a GEDCOM individual element and its parser. - - Stores the provided IndividualElement and the parser reference (gedcom_parser.parser) used to resolve cross-references. - + Create an Individual wrapper around a GEDCOM individual element and parser. + + Stores the provided IndividualElement and parser used to resolve cross-references. + Parameters: element (IndividualElement): The GEDCOM individual element to wrap. - gedcom_parser: The GedcomParser instance whose `parser` attribute will be used for resolving references. + parser: The parser instance (e.g., gedcom.parser.Parser) used for resolving references. """ self.element = element - self.gedcom = gedcom_parser.parser + self.gedcom = parser def get_id(self) -> str: """ @@ -68,22 +69,22 @@ class Individual: def get_full_name(self) -> str: """ Return the individual's full name formatted as "First Last". - + Returns: - Full name string in title case (e.g., "John Doe"); empty string if no name parts exist. + Full name string preserving original capitalization; empty string if no name parts exist. """ first, last = self.get_names() - return f"{first} {last}".strip().title() + return f"{first} {last}".strip() def get_file_name(self) -> str: """ Build a filename-like string for the individual in the form "FamilyName FirstName" optionally followed by the birth year. - + Returns: - filename (str): The generated filename string, either "FamilyName FirstName BirthYear" or "FamilyName FirstName" when the birth year is not available; does not include a file extension. + filename (str): The generated filename string, either "FamilyName FirstName BirthYear" or "FamilyName FirstName" when the birth year is not available; does not include a file extension; preserves original name capitalization. """ first, last = self.get_names() - name_part = f"{last} {first}".strip().title() + name_part = f"{last} {first}".strip() birth_year = self.element.get_birth_year() if birth_year != -1: @@ -93,14 +94,14 @@ class Individual: def get_birth_info(self) -> Dict[str, str]: """ Retrieve the person's birth date, place, and year from the underlying GEDCOM element. - + Returns: dict: A dictionary with keys: - 'date' (str): Birth date string or '' if unavailable. - 'place' (str): Birth place string or '' if unavailable. - 'year' (str): Birth year as a string or '' if the year is unknown. """ - date, place, sources = self.element.get_birth_data() + date, place, _sources = self.element.get_birth_data() year = self.element.get_birth_year() return { @@ -111,16 +112,25 @@ class Individual: def get_death_info(self) -> Dict[str, str]: """ - Provide the individual's death date and place. - + Provide the individual's death date, place, and year. + Returns: dict: Dictionary with keys: - date (str): Death date as a string, or '' if unknown. - place (str): Death place as a string, or '' if unknown. + - year (str): Death year extracted from date, or '' if unavailable. """ - date, place, sources = self.element.get_death_data() + date, place, _sources = self.element.get_death_data() - return {"date": date or "", "place": place or ""} + # Extract year from date string using regex + # Handles formats like "1850", "ABT 1850", "1 JAN 1850", "JAN 1850" + year = "" + if date: + year_match = re.search(r'\b(\d{4})\b', date) + if year_match: + year = year_match.group(1) + + return {"date": date or "", "place": place or "", "year": year} def get_gender(self) -> str: """ @@ -134,20 +144,17 @@ class Individual: def get_parents(self) -> List["Individual"]: """ Retrieve the person's parents. - + Returns: A list of Individual objects representing the person's parents. """ parent_elements = self.gedcom.get_parents(self.element) - return [ - Individual(p, type("", (), {"parser": self.gedcom})()) - for p in parent_elements - ] + return [Individual(p, self.gedcom) for p in parent_elements] def get_children(self) -> List["Individual"]: """ Retrieve the person's children as Individual objects. - + Returns: children (List[Individual]): A list of Individual instances corresponding to this person's children. """ @@ -157,17 +164,15 @@ class Individual: family, gedcom.tags.GEDCOM_TAG_CHILD ) for child in child_elements: - children.append( - Individual(child, type("", (), {"parser": self.gedcom})()) - ) + children.append(Individual(child, self.gedcom)) return children def get_partners(self) -> List["Individual"]: """ Retrieve this individual's spouses and partners. - + Each partner is resolved to an Individual wrapper; the subject is excluded from the result. - + Returns: List[Individual]: A list of Individual objects representing the person's partners (excluding the subject). """ @@ -177,9 +182,7 @@ class Individual: for parent in parent_elements: # Don't include self if parent.get_pointer() != self.element.get_pointer(): - partners.append( - Individual(parent, type("", (), {"parser": self.gedcom})()) - ) + partners.append(Individual(parent, self.gedcom)) return partners def get_families(self) -> List[Dict]: @@ -199,9 +202,7 @@ class Individual: partners = [] for parent in self.gedcom.get_family_members(family, "PARENTS"): if parent.get_pointer() != self.element.get_pointer(): - partners.append( - Individual(parent, type("", (), {"parser": self.gedcom})()) - ) + partners.append(Individual(parent, self.gedcom)) # Get marriage info marriage_date = "" @@ -219,9 +220,7 @@ class Individual: for child in self.gedcom.get_family_members( family, gedcom.tags.GEDCOM_TAG_CHILD ): - children.append( - Individual(child, type("", (), {"parser": self.gedcom})()) - ) + children.append(Individual(child, self.gedcom)) families.append( { diff --git a/src/main.py b/src/main.py old mode 100644 new mode 100755 index ee4a5a7..b1b22d0 --- a/src/main.py +++ b/src/main.py @@ -95,15 +95,19 @@ def extract_gedzip(zip_path: Path, temp_dir: Path) -> Tuple[Path, Optional[Path] gedcom_file = gedcom_files[0] logger.info(f"Found GEDCOM file: {gedcom_file.name}") - # Find media directory (look for common image extensions) + # Find media files across the entire extracted tree media_dir = None - for ext in ["*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp"]: - media_files = list(temp_dir.glob(f"**/{ext}")) - if media_files: - # Get the common parent directory of media files - media_dir = media_files[0].parent - logger.info(f"Found {len(media_files)} media files in: {media_dir}") - break + media_files = [] + for ext in ["*.jpg", "*.jpeg", "*.png", "*.gif", "*.bmp", "*.JPG", "*.JPEG", "*.PNG", "*.GIF", "*.BMP"]: + media_files.extend(temp_dir.rglob(ext)) + + if media_files: + # Set media_dir to the extraction root so all subdirectories are accessible + media_dir = temp_dir + # Get unique parent directories for logging + unique_dirs = sorted(set(f.parent for f in media_files)) + logger.info(f"Found {len(media_files)} media files across {len(unique_dirs)} directories") + logger.debug(f"Media directories: {[str(d.relative_to(temp_dir)) for d in unique_dirs]}") return gedcom_file, media_dir @@ -176,7 +180,7 @@ def convert_gedcom_to_markdown( return 1 # Wrap individuals in our data model - individuals = [Individual(elem, parser) for elem in individual_elements] + individuals = [Individual(elem, parser.parser) for elem in individual_elements] # Generate canvas if requested if create_canvas: @@ -198,6 +202,7 @@ def convert_gedcom_to_markdown( media_subdir=media_subdir_name, stories_subdir=stories_subdir_name, stories_dir=stories_dir, + use_subdirectories=not use_flat_structure, ) created_files = generator.generate_all(individuals) logger.info(f"Created {len(created_files)} markdown files") @@ -205,26 +210,60 @@ def convert_gedcom_to_markdown( # Copy media files if available if media_dir and media_dir.exists(): logger.info(f"Copying media files to: {media_output_dir}") - media_files = [] - for ext in [ - "*.jpg", - "*.jpeg", - "*.png", - "*.gif", - "*.bmp", - "*.JPG", - "*.JPEG", - "*.PNG", - ]: - media_files.extend(media_dir.glob(ext)) + + # Allowed media extensions (case-insensitive) + allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'} copied_count = 0 - for media_file in media_files: - dest = media_output_dir / media_file.name - shutil.copy2(media_file, dest) - copied_count += 1 + skipped_count = 0 + collision_count = 0 - logger.info(f"Copied {copied_count} media files") + # Recursively find all files in media_dir + for media_file in media_dir.rglob('*'): + # Skip directories, only process files + if not media_file.is_file(): + continue + + # Filter by extension (case-insensitive) + if media_file.suffix.lower() not in allowed_extensions: + continue + + # Compute relative path to preserve directory structure + relative_path = media_file.relative_to(media_dir) + dest = media_output_dir / relative_path + + # Handle filename collisions + if dest.exists(): + # Generate unique filename with numeric suffix + original_dest = dest + counter = 1 + stem = dest.stem + suffix = dest.suffix + + while dest.exists(): + dest = dest.parent / f"{stem}_{counter}{suffix}" + counter += 1 + + logger.warning( + f"Collision detected: {original_dest.name} -> {dest.name}" + ) + collision_count += 1 + + # Ensure parent directory exists + dest.parent.mkdir(parents=True, exist_ok=True) + + # Copy file preserving metadata + try: + shutil.copy2(media_file, dest) + copied_count += 1 + except (IOError, OSError) as e: + logger.exception(f"Failed to copy {media_file}") + skipped_count += 1 + + logger.info( + f"Copied {copied_count} media files " + f"({collision_count} collisions resolved, {skipped_count} skipped)" + ) # Generate index if create_index: @@ -237,14 +276,14 @@ def convert_gedcom_to_markdown( logger.info("Conversion completed successfully") return 0 - except FileNotFoundError as e: - logger.error(f"File not found: {e}") + except FileNotFoundError: + logger.exception("File not found") return 1 - except ValueError as e: - logger.error(f"Invalid input: {e}") + except ValueError: + logger.exception("Invalid input") return 1 - except Exception as e: - logger.error(f"Unexpected error: {e}", exc_info=True) + except Exception: + logger.exception("Unexpected error") return 1 diff --git a/src/markdown_generator.py b/src/markdown_generator.py index c9dacea..88c2f69 100644 --- a/src/markdown_generator.py +++ b/src/markdown_generator.py @@ -29,16 +29,18 @@ class MarkdownGenerator: media_subdir: str = "", stories_subdir: str = "", stories_dir: Optional[Path] = None, + use_subdirectories: bool = False, ): """ Configure the MarkdownGenerator with paths and optional subdirectories for media and story files. - + Parameters: output_dir (Path): Directory where markdown notes will be written; must exist and be a directory. media_subdir (str): Optional subdirectory name (relative) to prefix media/image paths in notes. stories_subdir (str): Optional subdirectory name (relative) to use when constructing wiki links to generated story notes. stories_dir (Optional[Path]): Optional directory where story markdown files will be created; defaults to `output_dir` when not provided. - + use_subdirectories (bool): Whether the output structure uses subdirectories (people/, stories/, media/). When True, WikiLinks and image paths will include appropriate subdirectory prefixes. + Raises: ValueError: If `output_dir` does not exist or is not a directory. """ @@ -51,6 +53,7 @@ class MarkdownGenerator: self.media_subdir = media_subdir self.stories_subdir = stories_subdir self.stories_dir = stories_dir if stories_dir else output_dir + self.use_subdirectories = use_subdirectories self.generated_stories = {} # Track generated story files def generate_note(self, individual: Individual) -> Path: @@ -110,8 +113,9 @@ class MarkdownGenerator: self._write_metadata(f, "Name", individual.get_full_name()) # Lived years - lived = f"{birth['year']}-{death['date'][:4] if death['date'] else ''}" - self._write_metadata(f, "Lived", lived) + if birth['year'] or death['year']: + lived = f"{birth['year']}-{death['year']}" + self._write_metadata(f, "Lived", lived) self._write_metadata(f, "Sex", individual.get_gender()) @@ -181,9 +185,9 @@ class MarkdownGenerator: def _write_families(self, f, individual: Individual): """ Write the "Families" section for an individual into the provided file handle. - - Emits a "## Families" header and, for each family that has a partner, a "Marriage" subsection (numbered when the individual has multiple families). For each marriage the function writes hidden metadata entries for Partner (as a wiki link), Marriage date, Marriage place (if present), and lists each Child as hidden metadata (as wiki links). Adds spacing after each marriage and a trailing blank line after the section. If the individual has no families, nothing is written. - + + Emits a "## Families" header and, for each family, a "Marriage" subsection (numbered when the individual has multiple families). For each family the function writes hidden metadata entries for Partner (as a wiki link, if partner is present), Marriage date, Marriage place (if present), and lists each Child as hidden metadata (as wiki links). Adds spacing after each family and a trailing blank line after the section. If the individual has no families, nothing is written. + Parameters: f (io.TextIO): Open text file handle to write the section into. individual (Individual): The individual whose family records will be written. @@ -196,28 +200,33 @@ class MarkdownGenerator: f.write("## Families\n") for i, family in enumerate(families, 1): + # Always write the Marriage header + f.write(f"### Marriage{f' {i}' if len(families) > 1 else ''}\n") + + # Only write partner metadata if partner exists if family["partner"]: partner_name = family["partner"].get_file_name() - f.write(f"### Marriage {i if len(families) > 1 else ''}\n") self._write_metadata_hidden(f, "Partner", self._wiki_link(partner_name)) - if family["marriage_date"]: + # Write marriage metadata if present + if family["marriage_date"]: + self._write_metadata_hidden( + f, "Marriage date", family["marriage_date"] + ) + if family["marriage_place"]: + self._write_metadata_hidden( + f, "Marriage place", family["marriage_place"] + ) + + # Write children if they exist + if family["children"]: + f.write("\n**Children:**\n") + for child in family["children"]: self._write_metadata_hidden( - f, "Marriage date", family["marriage_date"] - ) - if family["marriage_place"]: - self._write_metadata_hidden( - f, "Marriage place", family["marriage_place"] + f, "Child", self._wiki_link(child.get_file_name()) ) - if family["children"]: - f.write("\n**Children:**\n") - for child in family["children"]: - self._write_metadata_hidden( - f, "Child", self._wiki_link(child.get_file_name()) - ) - - f.write("\n") + f.write("\n") f.write("\n") @@ -336,9 +345,7 @@ class MarkdownGenerator: # Link back to the individual # If using subdirectories, stories are in stories/ and people are in people/ - if ( - self.media_subdir - ): # If using subdirs (media_subdir is set), use path prefix + if self.use_subdirectories: person_link = f"[[people/{individual_name}|{individual_name}]]" else: person_link = f"[[{individual_name}]]" @@ -359,8 +366,8 @@ class MarkdownGenerator: for img in section["images"]: title = img["title"] if img["title"] else "Image" filename_img = img["file"] - # Add media subdirectory prefix if specified - if self.media_subdir: + # Add media subdirectory prefix if using subdirectory structure + if self.use_subdirectories and self.media_subdir: image_path = f"../{self.media_subdir}/{filename_img}" else: image_path = filename_img @@ -477,9 +484,9 @@ class MarkdownGenerator: try: path = self.generate_note(individual) paths.append(path) - except Exception as e: - logger.error( - f"Failed to generate note for {individual.get_full_name()}: {e}" + except Exception: + logger.exception( + f"Failed to generate note for {individual.get_full_name()}" ) logger.info(f"Successfully generated {len(paths)} notes") diff --git a/tests/test_gedcom_parser.py b/tests/test_gedcom_parser.py index 1a8f702..598fdf1 100644 --- a/tests/test_gedcom_parser.py +++ b/tests/test_gedcom_parser.py @@ -9,12 +9,8 @@ This module tests GEDCOM file parsing functionality including: """ import pytest -import sys from pathlib import Path -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - from gedcom_parser import GedcomParser @@ -61,7 +57,7 @@ class TestLineEndingFixes: assert b'\r' in original_content # Has CR # Parse the file (should trigger line ending fix) - parser = GedcomParser(sample_gedcom_cr_only) + _parser = GedcomParser(sample_gedcom_cr_only) # Read the fixed content fixed_content = sample_gedcom_cr_only.read_bytes() @@ -75,7 +71,7 @@ class TestLineEndingFixes: original_size = len(original_content) # Parse the file - parser = GedcomParser(sample_gedcom_file) + _parser = GedcomParser(sample_gedcom_file) # Content should be unchanged new_content = sample_gedcom_file.read_bytes() diff --git a/tests/test_index_generator.py b/tests/test_index_generator.py index 2f4efc6..e2ca8ea 100644 --- a/tests/test_index_generator.py +++ b/tests/test_index_generator.py @@ -10,12 +10,8 @@ This module tests index file generation including: """ import pytest -import sys from pathlib import Path -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - from gedcom_parser import GedcomParser from individual import Individual from index_generator import IndexGenerator @@ -44,7 +40,7 @@ class TestIndexGeneration: """Get individuals from sample GEDCOM.""" parser = GedcomParser(sample_gedcom_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_generate_index(self, output_dir, individuals): """Test basic index generation.""" @@ -108,7 +104,7 @@ class TestAlphabeticalSorting: parser = GedcomParser(temp_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_sorting_by_last_name(self, output_dir, mixed_individuals): """Test that individuals are sorted by last name.""" @@ -167,7 +163,7 @@ class TestLetterGrouping: parser = GedcomParser(temp_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_letter_headers(self, output_dir, varied_individuals): """Test that letter headers are created for each initial.""" @@ -214,7 +210,7 @@ class TestLetterGrouping: parser = GedcomParser(temp_file) elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in elements] + individuals = [Individual(elem, parser.parser) for elem in elements] generator = IndexGenerator(output_dir) index_path = generator.generate_index(individuals) @@ -232,7 +228,7 @@ class TestWikiLinkFormatting: """Get individuals with birth/death dates.""" parser = GedcomParser(sample_gedcom_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_wiki_links_without_subdirs(self, output_dir, individuals_with_dates): """Test WikiLink format without subdirectories.""" @@ -261,7 +257,7 @@ class TestLifeSpanFormatting: """Get individuals with birth/death dates.""" parser = GedcomParser(sample_gedcom_file) elements = parser.get_individuals() - return [Individual(elem, parser) for elem in elements] + return [Individual(elem, parser.parser) for elem in elements] def test_life_span_with_both_dates(self, output_dir, individuals_with_dates): """Test life span when both birth and death dates are available.""" @@ -269,9 +265,8 @@ class TestLifeSpanFormatting: index_path = generator.generate_index(individuals_with_dates) content = index_path.read_text() - # Death date extraction gets first 4 chars: "15 J" from "15 JUN 2020" - # This is actually a bug in the code but we test actual behavior - assert '(1950-' in content # Just verify birth year is present + # Death date "15 JUN 2020" should extract year "2020" + assert '(1950-2020)' in content def test_life_span_with_only_birth(self, temp_dir, output_dir): """Test life span with only birth date.""" @@ -291,7 +286,7 @@ class TestLifeSpanFormatting: parser = GedcomParser(temp_file) elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in elements] + individuals = [Individual(elem, parser.parser) for elem in elements] generator = IndexGenerator(output_dir) index_path = generator.generate_index(individuals) @@ -316,7 +311,7 @@ class TestLifeSpanFormatting: parser = GedcomParser(temp_file) elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in elements] + individuals = [Individual(elem, parser.parser) for elem in elements] generator = IndexGenerator(output_dir) index_path = generator.generate_index(individuals) @@ -328,6 +323,36 @@ class TestLifeSpanFormatting: # Line should end with WikiLink, not life span assert not lines[0].strip().endswith(')') + def test_death_year_extraction_from_day_first_format(self, temp_dir, output_dir): + """Test that death year is correctly extracted when date starts with day.""" + gedcom_content = """0 HEAD +1 SOUR TestApp +1 GEDC +2 VERS 5.5.1 +1 CHAR UTF-8 +0 @I1@ INDI +1 NAME Test /Person/ +1 BIRT +2 DATE 1950 +1 DEAT +2 DATE 15 JUN 2020 +0 TRLR +""" + temp_file = temp_dir / "day_first.ged" + temp_file.write_text(gedcom_content, encoding='utf-8') + + parser = GedcomParser(temp_file) + elements = parser.get_individuals() + individuals = [Individual(elem, parser.parser) for elem in elements] + + generator = IndexGenerator(output_dir) + index_path = generator.generate_index(individuals) + content = index_path.read_text() + + # Should show (1950-2020), not (1950-15 J) + assert '(1950-2020)' in content + assert '15 J' not in content + class TestIndexStatistics: """Tests for index statistics and metadata.""" @@ -336,7 +361,7 @@ class TestIndexStatistics: """Test that total individual count is displayed.""" parser = GedcomParser(sample_gedcom_file) elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in elements] + individuals = [Individual(elem, parser.parser) for elem in elements] generator = IndexGenerator(output_dir) index_path = generator.generate_index(individuals) diff --git a/tests/test_individual.py b/tests/test_individual.py index 34396a4..49c523e 100644 --- a/tests/test_individual.py +++ b/tests/test_individual.py @@ -11,12 +11,8 @@ This module tests individual person data extraction including: """ import pytest -import sys from pathlib import Path -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - from gedcom_parser import GedcomParser from individual import Individual @@ -30,7 +26,7 @@ class TestIndividualBasicInfo: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_get_id(self, john_doe): """Test ID extraction without @ symbols.""" @@ -73,10 +69,10 @@ class TestIndividualBasicInfo: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) filename = person.get_file_name() - assert 'Person Noyear' in filename + assert 'Person NoYear' in filename # Preserves original GEDCOM capitalization # Should not contain a year assert not any(char.isdigit() for char in filename) @@ -100,7 +96,7 @@ class TestIndividualBasicInfo: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) assert person.get_gender() == 'U' @@ -114,7 +110,7 @@ class TestBirthAndDeath: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_get_birth_info(self, john_doe): """Test birth information extraction.""" @@ -128,6 +124,7 @@ class TestBirthAndDeath: death = john_doe.get_death_info() assert death['date'] == '15 JUN 2020' assert death['place'] == 'Los Angeles, USA' + assert death['year'] == '2020' def test_get_birth_info_missing(self, sample_gedcom_file): """Test birth info when not present.""" @@ -145,7 +142,7 @@ class TestBirthAndDeath: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) birth = person.get_birth_info() assert birth['date'] == '' @@ -162,7 +159,7 @@ class TestEvents: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_get_events(self, john_doe): """Test event extraction.""" @@ -206,7 +203,7 @@ class TestEvents: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) events = person.get_events() event_types = [e['type'] for e in events] @@ -232,7 +229,7 @@ class TestFamilyRelationships: individuals = parsed_gedcom.get_individuals() # Alice (I3) should have parents John (I1) and Jane (I2) alice = [ind for ind in individuals if 'Alice' in str(ind.get_name())] - alice_obj = Individual(alice[0], parsed_gedcom) + alice_obj = Individual(alice[0], parsed_gedcom.parser) parents = alice_obj.get_parents() assert len(parents) == 2 @@ -246,7 +243,7 @@ class TestFamilyRelationships: individuals = parsed_gedcom.get_individuals() # John (I1) should have child Alice (I3) john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parsed_gedcom) + john_obj = Individual(john[0], parsed_gedcom.parser) children = john_obj.get_children() assert len(children) >= 1 @@ -259,7 +256,7 @@ class TestFamilyRelationships: individuals = parsed_gedcom.get_individuals() # John (I1) should have partner Jane (I2) john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parsed_gedcom) + john_obj = Individual(john[0], parsed_gedcom.parser) partners = john_obj.get_partners() assert len(partners) >= 1 @@ -271,7 +268,7 @@ class TestFamilyRelationships: """Test family data extraction including marriage info.""" individuals = parsed_gedcom.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parsed_gedcom) + john_obj = Individual(john[0], parsed_gedcom.parser) families = john_obj.get_families() assert len(families) >= 1 @@ -292,7 +289,7 @@ class TestImagesAndMedia: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) images = john_obj.get_images() assert len(images) >= 1 @@ -318,7 +315,7 @@ class TestImagesAndMedia: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) images = person.get_images() assert len(images) == 0 @@ -332,7 +329,7 @@ class TestNotes: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) notes = john_obj.get_notes() assert len(notes) >= 1 @@ -357,7 +354,7 @@ class TestNotes: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) notes = person.get_notes() assert len(notes) >= 1 @@ -380,7 +377,7 @@ class TestNotes: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) notes = person.get_notes() assert len(notes) == 0 @@ -396,7 +393,7 @@ class TestStories: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) stories = person.get_stories() @@ -421,7 +418,7 @@ class TestStories: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) stories = person.get_stories() assert len(stories) == 0 @@ -437,7 +434,7 @@ class TestAttributes: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) attrs = person.get_attributes() assert attrs['eyes'] == 'Blue' @@ -460,7 +457,7 @@ class TestAttributes: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) attrs = person.get_attributes() assert len(attrs) == 0 diff --git a/tests/test_main.py b/tests/test_main.py index 10ad668..46c1828 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -10,15 +10,11 @@ This module tests the command-line interface and main conversion workflow includ """ import pytest -import sys import zipfile from pathlib import Path from unittest.mock import patch, MagicMock from io import StringIO -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - import main from main import ( setup_logging, @@ -127,11 +123,34 @@ class TestGedzipExtraction: extract_dir.mkdir() # Should use the first one and log a warning - gedcom_file, media_dir = extract_gedzip(zip_path, extract_dir) + gedcom_file, _media_dir = extract_gedzip(zip_path, extract_dir) assert gedcom_file is not None assert gedcom_file.exists() + def test_extract_gedzip_nested_media(self, temp_dir, sample_gedcom_content): + """Test that media files in nested subdirectories are discovered.""" + zip_path = temp_dir / "nested_media.zip" + + with zipfile.ZipFile(zip_path, 'w') as zf: + zf.writestr('family.ged', sample_gedcom_content) + # Add media files in multiple nested directories + zf.writestr('media/photos/photo1.jpg', b'fake image') + zf.writestr('media/documents/scan1.png', b'fake scan') + zf.writestr('images/subfolder/deep/photo2.jpg', b'fake image') + + extract_dir = temp_dir / "extracted" + extract_dir.mkdir() + + gedcom_file, media_dir = extract_gedzip(zip_path, extract_dir) + + # media_dir should point to extraction root + assert media_dir == extract_dir + + # All media files should be discoverable via rglob + all_media = list(media_dir.rglob("*.jpg")) + list(media_dir.rglob("*.png")) + assert len(all_media) == 3 + class TestConversionWorkflow: """Tests for the main conversion workflow.""" @@ -453,6 +472,120 @@ class TestMediaFileCopying: # Should succeed without media assert exit_code == 0 + def test_nested_directory_structure_preservation(self, sample_gedcom_file, output_dir, temp_dir): + """Test that nested media directory structure is preserved.""" + media_dir = temp_dir / 'media' + media_dir.mkdir() + + # Create nested directory structure + (media_dir / 'photos' / 'family').mkdir(parents=True) + (media_dir / 'photos' / 'events').mkdir(parents=True) + (media_dir / 'documents').mkdir(parents=True) + + # Create files in nested directories + (media_dir / 'photos' / 'family' / 'photo1.jpg').write_text('fake image') + (media_dir / 'photos' / 'events' / 'photo2.png').write_text('fake image') + (media_dir / 'documents' / 'scan.jpg').write_text('fake image') + + exit_code = convert_gedcom_to_markdown( + gedcom_file=sample_gedcom_file, + output_dir=output_dir, + create_index=True, + media_dir=media_dir, + use_flat_structure=True + ) + + assert exit_code == 0 + + # Verify directory structure is preserved + assert (output_dir / 'photos' / 'family' / 'photo1.jpg').exists() + assert (output_dir / 'photos' / 'events' / 'photo2.png').exists() + assert (output_dir / 'documents' / 'scan.jpg').exists() + + def test_filename_collision_handling(self, sample_gedcom_file, output_dir, temp_dir): + """Test that filename collisions are handled with numeric suffixes.""" + media_dir = temp_dir / 'media' + media_dir.mkdir() + + # Create subdirectories with same filenames + (media_dir / 'dir1').mkdir() + (media_dir / 'dir2').mkdir() + + # Create files with same name in different directories + (media_dir / 'dir1' / 'photo.jpg').write_text('image 1') + (media_dir / 'dir2' / 'photo.jpg').write_text('image 2') + + exit_code = convert_gedcom_to_markdown( + gedcom_file=sample_gedcom_file, + output_dir=output_dir, + create_index=True, + media_dir=media_dir, + use_flat_structure=True + ) + + assert exit_code == 0 + + # First file should be copied normally + assert (output_dir / 'dir1' / 'photo.jpg').exists() + + # Second file should be copied with preserved structure (no collision) + assert (output_dir / 'dir2' / 'photo.jpg').exists() + + # Both files should exist + assert len(list(output_dir.rglob('photo*.jpg'))) == 2 + + def test_case_insensitive_extensions(self, sample_gedcom_file, output_dir, temp_dir): + """Test that extensions are matched case-insensitively.""" + media_dir = temp_dir / 'media' + media_dir.mkdir() + + # Create files with mixed-case extensions + (media_dir / 'photo1.JpG').write_text('fake image') + (media_dir / 'photo2.PnG').write_text('fake image') + (media_dir / 'photo3.GiF').write_text('fake image') + + exit_code = convert_gedcom_to_markdown( + gedcom_file=sample_gedcom_file, + output_dir=output_dir, + create_index=True, + media_dir=media_dir, + use_flat_structure=True + ) + + assert exit_code == 0 + + # All files should be copied despite mixed case + assert (output_dir / 'photo1.JpG').exists() + assert (output_dir / 'photo2.PnG').exists() + assert (output_dir / 'photo3.GiF').exists() + + def test_non_media_files_ignored(self, sample_gedcom_file, output_dir, temp_dir): + """Test that non-media files are ignored.""" + media_dir = temp_dir / 'media' + media_dir.mkdir() + + # Create media and non-media files + (media_dir / 'photo.jpg').write_text('fake image') + (media_dir / 'readme.txt').write_text('some text') + (media_dir / 'data.csv').write_text('some data') + (media_dir / 'script.py').write_text('print("hello")') + + exit_code = convert_gedcom_to_markdown( + gedcom_file=sample_gedcom_file, + output_dir=output_dir, + create_index=True, + media_dir=media_dir, + use_flat_structure=True + ) + + assert exit_code == 0 + + # Only media file should be copied + assert (output_dir / 'photo.jpg').exists() + assert not (output_dir / 'readme.txt').exists() + assert not (output_dir / 'data.csv').exists() + assert not (output_dir / 'script.py').exists() + class TestTempDirectoryCleanup: """Tests for temporary directory cleanup.""" diff --git a/tests/test_markdown_generator.py b/tests/test_markdown_generator.py index c930073..ef49ac1 100644 --- a/tests/test_markdown_generator.py +++ b/tests/test_markdown_generator.py @@ -10,12 +10,8 @@ This module tests Obsidian markdown note generation including: """ import pytest -import sys from pathlib import Path -# Add src to path for imports -sys.path.insert(0, str(Path(__file__).parent.parent / 'src')) - from gedcom_parser import GedcomParser from individual import Individual from markdown_generator import MarkdownGenerator @@ -71,7 +67,7 @@ class TestNoteGeneration: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_generate_note(self, generator, john_doe): """Test basic note generation.""" @@ -97,7 +93,7 @@ class TestNoteGeneration: """Test generating notes for all individuals.""" parser = GedcomParser(sample_gedcom_file) individual_elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in individual_elements] + individuals = [Individual(elem, parser.parser) for elem in individual_elements] paths = generator.generate_all(individuals) @@ -120,7 +116,7 @@ class TestMetadataFormatting: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - return Individual(john[0], parser) + return Individual(john[0], parser.parser) def test_visible_metadata(self, generator, john_doe): """Test visible metadata format [key:: value].""" @@ -146,8 +142,8 @@ class TestMetadataFormatting: file_path = generator.generate_note(john_doe) content = file_path.read_text() - # Death date extraction gets first 4 chars which is "15 J" from "15 JUN 2020" - assert '[Lived:: 1950-15 J]' in content or '[Lived:: 1950-2020]' in content + # Death year is now extracted robustly using regex + assert '[Lived:: 1950-2020]' in content assert '[Born:: 1 JAN 1950]' in content assert '[Passed away:: 15 JUN 2020]' in content @@ -166,7 +162,7 @@ class TestWikiLinks: individual_elements = parser.get_individuals() # Generate all notes first - individuals = [Individual(elem, parser) for elem in individual_elements] + individuals = [Individual(elem, parser.parser) for elem in individual_elements] generator.generate_all(individuals) # Check John's note for WikiLinks to Jane and Alice @@ -182,7 +178,7 @@ class TestWikiLinks: """Test WikiLinks to parents.""" parser = GedcomParser(sample_gedcom_file) individual_elements = parser.get_individuals() - individuals = [Individual(elem, parser) for elem in individual_elements] + individuals = [Individual(elem, parser.parser) for elem in individual_elements] generator.generate_all(individuals) @@ -210,7 +206,7 @@ class TestEventFormatting: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -225,7 +221,7 @@ class TestEventFormatting: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -250,7 +246,7 @@ class TestImageHandling: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -266,7 +262,7 @@ class TestImageHandling: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -297,7 +293,7 @@ class TestStoryGeneration: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) # Generate note (should also generate story files if stories are found) generator.generate_note(person) @@ -313,7 +309,7 @@ class TestStoryGeneration: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) file_path = generator.generate_note(person) content = file_path.read_text() @@ -330,7 +326,7 @@ class TestStoryGeneration: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) # Generate twice generator.generate_note(person) @@ -362,7 +358,7 @@ class TestFamilyFormatting: parser = GedcomParser(sample_gedcom_file) individuals = parser.get_individuals() john = [ind for ind in individuals if 'John' in str(ind.get_name())] - john_obj = Individual(john[0], parser) + john_obj = Individual(john[0], parser.parser) file_path = generator.generate_note(john_obj) content = file_path.read_text() @@ -408,7 +404,7 @@ class TestFamilyFormatting: parser = GedcomParser(temp_file) individuals = parser.get_individuals() - person = Individual(individuals[0], parser) + person = Individual(individuals[0], parser.parser) file_path = generator.generate_note(person) content = file_path.read_text()