@@ -1064,12 +1064,24 @@ def __init__(self) -> None:
10641064 # wrote, mirroring how :class:`FileSystemAgentFileStore` preserves the
10651065 # on-disk casing.
10661066 self ._files : dict [str , tuple [str , str ]] = {}
1067+ self ._dir_counts : dict [str , int ] = {}
1068+ self ._explicit_dirs : dict [str , str ] = {}
10671069 self ._lock = asyncio .Lock ()
10681070
10691071 @staticmethod
10701072 def _key (path : str ) -> str :
10711073 return _normalize_relative_path (path ).lower ()
10721074
1075+ @staticmethod
1076+ def _ancestor_keys (key : str ) -> list [str ]:
1077+ """Return all strict ancestor directory keys in top-down order in linear time."""
1078+ ancestors : list [str ] = []
1079+ idx = key .find ("/" )
1080+ while idx != - 1 :
1081+ ancestors .append (key [:idx ])
1082+ idx = key .find ("/" , idx + 1 )
1083+ return ancestors
1084+
10731085 async def write (self , path : str , content : str , * , overwrite : bool = True ) -> None :
10741086 """Write ``content`` to the file at ``path``.
10751087
@@ -1079,19 +1091,20 @@ async def write(self, path: str, content: str, *, overwrite: bool = True) -> Non
10791091 """
10801092 display = _normalize_relative_path (path )
10811093 key = display .lower ()
1082- dir_prefix = f"{ key } /"
10831094 async with self ._lock :
1084- parts = key .split ("/" )
1085- for i in range (1 , len (parts )):
1086- ancestor = "/" .join (parts [:i ])
1095+ ancestors = self ._ancestor_keys (key )
1096+ for ancestor in ancestors :
10871097 if ancestor in self ._files :
10881098 raise NotADirectoryError (f"Not a directory: { path !r} " )
1089- for existing_key in self ._files :
1090- if existing_key .startswith (dir_prefix ):
1091- raise IsADirectoryError (f"Is a directory: { path !r} " )
1099+ if self ._dir_counts .get (key , 0 ) > 0 or key in self ._explicit_dirs :
1100+ raise IsADirectoryError (f"Is a directory: { path !r} " )
10921101 if not overwrite and key in self ._files :
10931102 raise FileExistsError (f"File already exists: { path !r} " )
1103+ is_new_file = key not in self ._files
10941104 self ._files [key ] = (display , content )
1105+ if is_new_file :
1106+ for ancestor in ancestors :
1107+ self ._dir_counts [ancestor ] = self ._dir_counts .get (ancestor , 0 ) + 1
10951108
10961109 async def read (self , path : str ) -> str | None :
10971110 """Return the file content, or ``None`` if the file does not exist."""
@@ -1104,7 +1117,16 @@ async def delete(self, path: str) -> bool:
11041117 """Delete the file and return whether anything was removed."""
11051118 key = self ._key (path )
11061119 async with self ._lock :
1107- return self ._files .pop (key , None ) is not None
1120+ removed = self ._files .pop (key , None )
1121+ if removed is not None :
1122+ for ancestor in self ._ancestor_keys (key ):
1123+ new_count = self ._dir_counts [ancestor ] - 1
1124+ if new_count <= 0 :
1125+ del self ._dir_counts [ancestor ]
1126+ else :
1127+ self ._dir_counts [ancestor ] = new_count
1128+ return True
1129+ return False
11081130
11091131 async def list_children (self , directory : str = "" ) -> list [FileStoreEntry ]:
11101132 """Return the direct child files and subdirectories of ``directory``.
@@ -1124,11 +1146,12 @@ async def list_children(self, directory: str = "") -> list[FileStoreEntry]:
11241146 prefix += "/"
11251147 prefix_depth = prefix .count ("/" )
11261148 async with self ._lock :
1127- entries = [(key , display ) for key , (display , _ ) in self ._files .items ()]
1149+ file_entries = [(key , display ) for key , (display , _ ) in self ._files .items ()]
1150+ dir_entries = list (self ._explicit_dirs .items ())
11281151 files : list [str ] = []
11291152 directories : list [str ] = []
11301153 seen_dirs : set [str ] = set ()
1131- for key , display in entries :
1154+ for key , display in file_entries :
11321155 if not key .startswith (prefix ):
11331156 continue
11341157 # Unicode lowercasing can change character counts, so key offsets
@@ -1143,6 +1166,17 @@ async def list_children(self, directory: str = "") -> list[FileStoreEntry]:
11431166 continue
11441167 seen_dirs .add (segment_key )
11451168 directories .append (segment )
1169+ for key , display in dir_entries :
1170+ if not key .startswith (prefix ) or key == prefix .rstrip ("/" ):
1171+ continue
1172+ remainder = display .split ("/" , prefix_depth )[- 1 ]
1173+ segment , _ , _ = remainder .partition ("/" )
1174+ if segment :
1175+ segment_key = segment .lower ()
1176+ if segment_key in seen_dirs :
1177+ continue
1178+ seen_dirs .add (segment_key )
1179+ directories .append (segment )
11461180 results : list [FileStoreEntry ] = [FileStoreEntry (name , FileStoreEntry .DIRECTORY ) for name in directories ]
11471181 results .extend (FileStoreEntry (name , FileStoreEntry .FILE ) for name in files )
11481182 return results
@@ -1206,11 +1240,24 @@ async def create_directory(self, path: str) -> None:
12061240 if not key :
12071241 return
12081242 async with self ._lock :
1209- parts = key .split ("/" )
1210- for i in range (1 , len (parts ) + 1 ):
1211- ancestor = "/" .join (parts [:i ])
1243+ ancestors = self ._ancestor_keys (key )
1244+ for ancestor in ancestors :
12121245 if ancestor in self ._files :
12131246 raise FileExistsError (f"File already exists: { ancestor !r} " )
1247+ if key in self ._files :
1248+ raise FileExistsError (f"File already exists: { key !r} " )
1249+ if key not in self ._explicit_dirs :
1250+ idx_display = 0
1251+ for ancestor in ancestors :
1252+ next_slash = display .find ("/" , idx_display )
1253+ if next_slash != - 1 :
1254+ ancestor_display = display [:next_slash ]
1255+ idx_display = next_slash + 1
1256+ else :
1257+ ancestor_display = display
1258+ if ancestor not in self ._explicit_dirs :
1259+ self ._explicit_dirs [ancestor ] = ancestor_display
1260+ self ._explicit_dirs [key ] = display
12141261
12151262
12161263@experimental (feature_id = ExperimentalFeature .HARNESS )
0 commit comments