21 """Interfaces and common code for recursively scanning directories for Gen2
24 The `PathElementHandler` ABC is defined here instead of ``handlers.py`` for
25 dependency reasons: `DirectoryScanner` uses the ABC, while its concrete
26 implementations use `DirectorySCanner`.
28 from __future__
import annotations
30 __all__ = [
"PathElementHandler",
"DirectoryScanner"]
32 from abc
import ABC, abstractmethod
44 from lsst.daf.butler
import (
52 """An interface for objects that handle a single path element (directory or
53 file) in a Gen2 data repository.
55 Handlers are added to a `DirectoryScanner` instance, which then calls them
56 until one succeeds when it processes each element in a directory.
61 __slots__ = (
"lastDataId2",
"log")
65 """Report what kind of path element this object handlers.
69 Return `True` if this handler is for file entries, or `False` if it
72 raise NotImplementedError()
75 def __call__(self, path: str, name: str, datasets: Mapping[DatasetType, List[FileDataset]], *,
76 predicate: Callable[[DataCoordinate], bool]) -> bool:
77 """Apply the handler to a file path.
82 Full path of the file or directory.
84 Local name of the file or directory within its parent directory.
85 datasets : `dict` [`DatasetType`, `list` [`FileDataset`] ]
86 Dictionary that found datasets should be added to.
87 predicate : `~collections.abc.Callable`
88 A callable taking a single `DataCoordinate` argument and returning
89 `bool`, indicating whether that (Gen3) data ID represents one
90 that should be included in the scan.'
95 `True` if this handler was a match for the given path and no other
96 handlers need to be tried on it, `False` otherwise.
98 raise NotImplementedError()
103 """Return a rough indication of how flexible this handler is in terms
104 of the path element names it can match.
106 Handlers that match a constant path element should always return zero.
108 raise NotImplementedError()
110 def translate(self, dataId2: dict, *, partial: bool =
False) -> Optional[DataCoordinate]:
111 """Translate the given data ID from Gen2 to Gen3.
113 The default implementation returns `None`. Subclasses that are able
114 to translate data IDs should override this method.
120 partial : `bool`, optional
121 If `True` (`False` is default) this is a partial data ID for some
122 dataset, and missing keys are expected.
126 dataId3 : `lsst.daf.butler.DataCoordinate` or `None`
127 A Gen3 data ID, or `None` if this handler cannot translate data
132 def __lt__(self, other: PathElementHandler):
133 """Handlers are sorted by rank to reduce the possibility that more
134 flexible handlers will have a chance to match something they shouldn't.
136 return self.
rank < other.rank
139 """The Gen2 data ID obtained by processing parent levels in the directory
142 This attribute should be reset by calling code whenever a new parent
143 directory is entered, before invoking `__call__`.
147 """A logger to use for all diagnostic messages (`lsst.log.Log`).
149 This attribute is set on a handler in `DirectoryScanner.add`; this avoids
150 needing to forward one through all subclass constructors.
155 """An object that uses `PathElementHandler` instances to process the files
156 and subdirectories in a directory tree.
160 log : `Log`, optional
161 Log to use to report warnings and debug information.
167 log = Log.getLogger(
"obs.base.gen2to3.walker")
170 __slots__ = (
"_files",
"_subdirectories",
"log")
172 def add(self, handler: PathElementHandler):
173 """Add a new handler to the scanner.
177 handler : `PathElementHandler`
178 The handler to be added.
180 handler.log = self.
log
181 if handler.isForFiles():
182 bisect.insort(self.
_files, handler)
186 def __iter__(self) -> Iterator[PathElementHandler]:
187 """Iterate over all handlers.
192 def scan(self, path: str, datasets: Mapping[DatasetType, List[FileDataset]], *,
193 predicate: Callable[[DataCoordinate], bool]):
194 """Process a directory.
199 Full path to the directory to be processed.
200 datasets : `dict` [`DatasetType`, `list` [`FileDataset`] ]
201 Dictionary that found datasets should be added to.
202 predicate : `~collections.abc.Callable`
203 A callable taking a single `DataCoordinate` argument and returning
204 `bool`, indicating whether that (Gen3) data ID represents one
205 that should be included in the scan.
208 for entry
in os.scandir(path):
215 for handler
in handlers:
216 if handler(entry.path, entry.name, datasets, predicate=predicate):
219 unrecognized.append(entry.name)
221 self.
log.
warn(
"Skipped unrecognized entries in %s: %s", path, unrecognized)