diff --git a/CHANGELOG.md b/CHANGELOG.md index 1425406..5a56e72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - `open_href` ([#123](https://github.com/stac-utils/stac-asset/pull/123)) +### Fixed + +- Directory for writing Item JSON is always created ([#152](https://github.com/stac-utils/stac-asset/pull/152)) + ## [0.2.3] - 2023-10-20 ### Added diff --git a/src/stac_asset/_functions.py b/src/stac_asset/_functions.py index d628932..3bdc3be 100644 --- a/src/stac_asset/_functions.py +++ b/src/stac_asset/_functions.py @@ -238,6 +238,7 @@ async def download_item( if self_href: make_asset_hrefs_relative(item) d = item.to_dict(include_self_link=True, transform_hrefs=False) + os.makedirs(os.path.dirname(self_href), exist_ok=True) with open(self_href, "w") as f: json.dump(d, f) diff --git a/tests/test_functions.py b/tests/test_functions.py index 36c00c6..6bee32a 100644 --- a/tests/test_functions.py +++ b/tests/test_functions.py @@ -74,6 +74,18 @@ async def test_download_missing_asset_delete(tmp_path: Path, item: Item) -> None assert "does-not-exist" not in item.assets +async def test_download_nonexistent_asset(tmp_path: Path, item: Item) -> None: + # this previously had a bug where the code assumed the directory had + # been created by downloading the assets when trying to write the item json, + # but it hadn't, so a failure occurred + await stac_asset.download_item( + item, + tmp_path / "dir-that-doesnt-exist", + file_name="item.json", + config=Config(include=["non-existent-asset"]), + ) + + async def test_download_missing_asset_fail_fast(tmp_path: Path, item: Item) -> None: item.assets["does-not-exist"] = Asset("not-a-file.md5") with pytest.raises(FileNotFoundError):