Coverage for python/lsst/daf/butler/core/location.py : 28%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22from __future__ import annotations
24__all__ = ("Location", "LocationFactory")
26import os
27import os.path
29from typing import (
30 Optional,
31 Union,
32)
34from ._butlerUri import ButlerURI
37class Location:
38 """Identifies a location within the `Datastore`.
40 Parameters
41 ----------
42 datastoreRootUri : `ButlerURI` or `str` or `None`
43 Base URI for this datastore, must include an absolute path.
44 If `None` the `path` must correspond to an absolute URI.
45 path : `ButlerURI` or `str`
46 Relative path within datastore. Assumed to be using the local
47 path separator if a ``file`` scheme is being used for the URI,
48 else a POSIX separator. Can be a full URI if the root URI is `None`.
49 Can also be a schemeless URI if it refers to a relative path.
50 """
52 __slots__ = ("_datastoreRootUri", "_path", "_uri")
54 def __init__(self, datastoreRootUri: Union[None, ButlerURI, str],
55 path: Union[ButlerURI, str]):
56 # Be careful not to force a relative local path to absolute path
57 path_uri = ButlerURI(path, forceAbsolute=False)
59 if isinstance(datastoreRootUri, str):
60 datastoreRootUri = ButlerURI(datastoreRootUri, forceDirectory=True)
61 elif datastoreRootUri is None:
62 if not path_uri.isabs():
63 raise ValueError(f"No datastore root URI given but path '{path}' was not absolute URI.")
64 elif not isinstance(datastoreRootUri, ButlerURI):
65 raise ValueError("Datastore root must be a ButlerURI instance")
67 if datastoreRootUri is not None and not datastoreRootUri.isabs():
68 raise ValueError(f"Supplied root URI must be an absolute path (given {datastoreRootUri}).")
70 self._datastoreRootUri = datastoreRootUri
72 # if the root URI is not None the path must not be absolute since
73 # it is required to be within the root.
74 if datastoreRootUri is not None:
75 if path_uri.isabs():
76 raise ValueError(f"Path within datastore must be relative not absolute, got {path_uri}")
78 self._path = path_uri
80 # Internal cache of the full location as a ButlerURI
81 self._uri: Optional[ButlerURI] = None
83 # Check that the resulting URI is inside the datastore
84 # This can go wrong if we were given ../dir as path
85 if self._datastoreRootUri is not None:
86 pathInStore = self.uri.relative_to(self._datastoreRootUri)
87 if pathInStore is None:
88 raise ValueError(f"Unexpectedly {path} jumps out of {self._datastoreRootUri}")
90 def __str__(self) -> str:
91 return str(self.uri)
93 def __repr__(self) -> str:
94 uri = self._datastoreRootUri
95 path = self._path
96 return f"{self.__class__.__name__}({uri!r}, {path.path!r})"
98 @property
99 def uri(self) -> ButlerURI:
100 """URI corresponding to fully-specified location in datastore.
101 """
102 if self._uri is None:
103 root = self._datastoreRootUri
104 if root is None:
105 uri = self._path
106 else:
107 uri = root.join(self._path)
108 self._uri = uri
109 return self._uri
111 @property
112 def path(self) -> str:
113 """Path corresponding to location.
115 This path includes the root of the `Datastore`, but does not include
116 non-path components of the root URI. Paths will not include URI
117 quoting. If a file URI scheme is being used the path will be returned
118 with the local OS path separator.
119 """
120 full = self.uri
121 try:
122 return full.ospath
123 except AttributeError:
124 return full.unquoted_path
126 @property
127 def pathInStore(self) -> ButlerURI:
128 """Path corresponding to location relative to `Datastore` root.
130 Uses the same path separator as supplied to the object constructor.
131 Can be an absolute URI if that is how the location was configured.
132 """
133 return self._path
135 @property
136 def netloc(self) -> str:
137 """The URI network location."""
138 return self.uri.netloc
140 @property
141 def relativeToPathRoot(self) -> str:
142 """Returns the path component of the URI relative to the network
143 location.
145 Effectively, this is the path property with POSIX separator stripped
146 from the left hand side of the path. Will be unquoted.
147 """
148 return self.uri.relativeToPathRoot
150 def updateExtension(self, ext: Optional[str]) -> None:
151 """Update the file extension associated with this `Location`.
153 All file extensions are replaced.
155 Parameters
156 ----------
157 ext : `str`
158 New extension. If an empty string is given any extension will
159 be removed. If `None` is given there will be no change.
160 """
161 if ext is None:
162 return
164 self._path.updateExtension(ext)
166 # Clear the URI cache so it can be recreated with the new path
167 self._uri = None
169 def getExtension(self) -> str:
170 """Return the file extension(s) associated with this location.
172 Returns
173 -------
174 ext : `str`
175 The file extension (including the ``.``). Can be empty string
176 if there is no file extension. Will return all file extensions
177 as a single extension such that ``file.fits.gz`` will return
178 a value of ``.fits.gz``.
179 """
180 return self.uri.getExtension()
183class LocationFactory:
184 """Factory for `Location` instances.
186 The factory is constructed from the root location of the datastore.
187 This location can be a path on the file system (absolute or relative)
188 or as a URI.
190 Parameters
191 ----------
192 datastoreRoot : `str`
193 Root location of the `Datastore` either as a path in the local
194 filesystem or as a URI. File scheme URIs can be used. If a local
195 filesystem path is used without URI scheme, it will be converted
196 to an absolute path and any home directory indicators expanded.
197 If a file scheme is used with a relative path, the path will
198 be treated as a posixpath but then converted to an absolute path.
199 """
201 def __init__(self, datastoreRoot: Union[ButlerURI, str]):
202 self._datastoreRootUri = ButlerURI(datastoreRoot, forceAbsolute=True,
203 forceDirectory=True)
205 def __str__(self) -> str:
206 return f"{self.__class__.__name__}@{self._datastoreRootUri}"
208 @property
209 def netloc(self) -> str:
210 """Returns the network location of root location of the `Datastore`."""
211 return self._datastoreRootUri.netloc
213 def fromPath(self, path: str) -> Location:
214 """Factory function to create a `Location` from a POSIX path.
216 Parameters
217 ----------
218 path : `str`
219 A standard POSIX path, relative to the `Datastore` root.
221 Returns
222 -------
223 location : `Location`
224 The equivalent `Location`.
225 """
226 if os.path.isabs(path):
227 raise ValueError("LocationFactory path must be relative to datastore, not absolute.")
228 return Location(self._datastoreRootUri, path)