Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions obsidiantools/md_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,13 @@ def _get_md_front_matter_and_content(filepath: Path, *,
if str_transform_func:
file_string = str_transform_func(file_string)
return frontmatter.parse(file_string)
# non-UTF-8 bytes: re-raise with the offending file path so the
# file can be identified (the bare except below would otherwise
# swallow this and raise a confusing UnboundLocalError):
except UnicodeDecodeError as e:
raise UnicodeDecodeError(
e.encoding, e.object, e.start, e.end,
f"{e.reason} (in file: {filepath})") from e
# for invalid YAML, return the whole file as content:
except yaml.scanner.ScannerError as e:
print(f"Front matter not populated for {filepath.name}: {repr(e)}")
Expand Down
12 changes: 12 additions & 0 deletions tests/test_md_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,18 @@ def test_front_matter_parse_double_curly():
assert actual_txt == expected_txt


def test_non_utf8_file_error_includes_filepath(tmp_path):
# a file with non-UTF-8 bytes should raise a UnicodeDecodeError whose
# message identifies the offending file (issue #32)
fpath = tmp_path / 'invalid-encoding.md'
fpath.write_bytes(b'# Heading\n\xff invalid start byte\n')

with pytest.raises(UnicodeDecodeError) as exc_info:
get_front_matter(fpath)

assert str(fpath) in str(exc_info.value)


def test_hash_char_parsing_func():
# '\#' in md file keeps # but stops text from being a tag
in_str = r"\#hash #tag"
Expand Down