diff --git a/gcsfs/core.py b/gcsfs/core.py index 1bae97e60..1c1c8c1cf 100644 --- a/gcsfs/core.py +++ b/gcsfs/core.py @@ -1902,21 +1902,22 @@ def _get_dirs_and_update_cache(self, path, objects, prefix="", update_cache=True while parent: dir_key = self.split_path(parent)[1] - if not dir_key or len(parent) < len(path.rstrip("/")): + if len(parent) < len(path.rstrip("/")): break if prefix and not parent.startswith(full_prefix): # If this parent doesn't match the prefix, neither will its parents. break - dirs[parent] = { - "Key": dir_key, - "Size": 0, - "name": parent, - "StorageClass": "DIRECTORY", - "type": "directory", - "size": 0, - } + if dir_key: + dirs[parent] = { + "Key": dir_key, + "Size": 0, + "name": parent, + "StorageClass": "DIRECTORY", + "type": "directory", + "size": 0, + } if not prefix and update_cache: listing = cache_entries.setdefault(parent, {}) @@ -1924,7 +1925,8 @@ def _get_dirs_and_update_cache(self, path, objects, prefix="", update_cache=True if name not in listing: listing[name] = previous - previous = dirs[parent] + if parent in dirs: + previous = dirs[parent] parent = self._parent(parent) if not prefix and update_cache: cache_entries_list = {k: list(v.values()) for k, v in cache_entries.items()} diff --git a/gcsfs/tests/integration/test_extended_hns.py b/gcsfs/tests/integration/test_extended_hns.py index 515dd7181..949ed6f9c 100644 --- a/gcsfs/tests/integration/test_extended_hns.py +++ b/gcsfs/tests/integration/test_extended_hns.py @@ -1339,6 +1339,25 @@ def test_find_updates_dircache_without_prefix( } assert not empty_dir_listing + @pytest.mark.parametrize("withdirs_param", [True, False]) + def test_find_updates_dircache_for_root_bucket( + self, gcs_hns, test_structure, withdirs_param + ): + """Test that find() populates the dircache for the root bucket itself.""" + root_bucket = TEST_HNS_BUCKET + gcs_hns.invalidate_cache() + assert not gcs_hns.dircache + + # Run find on the root bucket to populate the cache + gcs_hns.find(root_bucket, withdirs=withdirs_param) + + # Verify that the cache is now populated for the root bucket + assert root_bucket in gcs_hns.dircache + root_bucket_listing = { + d["name"].rstrip("/") for d in gcs_hns.dircache[root_bucket] + } + assert root_bucket_listing == {test_structure["base_dir"]} + def test_find_maxdepth_updates_cache(self, gcs_hns, test_structure): """Test that find with maxdepth updates cache for deeper objects.""" base_dir = test_structure["base_dir"]