diff --git a/CHANGELOG.md b/CHANGELOG.md index cb59f4f..cc794ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Changelog ========= +Version 2.0.2 +------------- + +- Fixing #137 passing non-existent filename to from_string()/from_stream() no longer raises FileNotFoundError (thanks to denisw) + Version 2.0.1 ------------- diff --git a/puremagic/main.py b/puremagic/main.py index d9e2ef6..2ca1e7c 100644 --- a/puremagic/main.py +++ b/puremagic/main.py @@ -34,7 +34,7 @@ ) __author__ = "Chris Griffith" -__version__ = "2.0.1" +__version__ = "2.0.2" __all__ = [ "magic_file", "magic_string", @@ -208,7 +208,7 @@ def perform_magic(header: bytes, footer: bytes, mime: bool, ext=None, filename=N if not header: raise PureValueError("Input was empty") infos = identify_all(header, footer, ext) - if filename and os.getenv("PUREMAGIC_DEEPSCAN") != "0": + if filename and os.path.isfile(filename) and os.getenv("PUREMAGIC_DEEPSCAN") != "0": results = run_deep_scan(infos, filename, header, footer, raise_on_none=True) if results: if results[0].extension == "": @@ -362,7 +362,7 @@ def magic_string(string, filename: os.PathLike | str | None = None) -> list[Pure ext = ext_from_filename(filename) if filename else None info = identify_all(head, foot, ext) info.sort(key=lambda x: x.confidence, reverse=True) - if filename and os.getenv("PUREMAGIC_DEEPSCAN") != "0": + if filename and os.path.isfile(filename) and os.getenv("PUREMAGIC_DEEPSCAN") != "0": return run_deep_scan(info, filename, head, foot, raise_on_none=False) return info @@ -385,7 +385,7 @@ def magic_stream( ext = ext_from_filename(filename) if filename else None info = identify_all(head, foot, ext) info.sort(key=lambda x: x.confidence, reverse=True) - if filename and os.getenv("PUREMAGIC_DEEPSCAN") != "0": + if filename and os.path.isfile(filename) and os.getenv("PUREMAGIC_DEEPSCAN") != "0": return run_deep_scan(info, filename, head, foot, raise_on_none=False) return info diff --git a/test/test_scanners.py b/test/test_scanners.py index bb9bd52..b14344b 100644 --- a/test/test_scanners.py +++ b/test/test_scanners.py @@ -57,6 +57,19 @@ def test_utf16_le_csv_deep_scan(): assert results[0].confidence >= 0.9 +def test_from_string_nonexistent_filename(): + # GH #137: passing filename for extension hint should not raise FileNotFoundError + # Use PDF-like bytes so identify_all finds a match via magic numbers, + # then deep scan is skipped (file doesn't exist) and the match is returned. + pdf_bytes = b"%PDF-1.4 fake content" + result = puremagic.from_string(pdf_bytes, filename="nonexistent.pdf") + assert result == ".pdf" + + # magic_string should also work without crashing + results = puremagic.magic_string(pdf_bytes, filename="nonexistent.pdf") + assert any(r.extension == ".pdf" for r in results) + + def test_python_scanner(): # Test the Python scanner with a sample Python file py_file = SYSTEM_DIR / "test.py"