Coverage for python/lsst/daf/butler/script/removeCollections.py: 31%
58 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-11-13 01:31 -0800
« prev ^ index » next coverage.py v7.11.0, created at 2025-11-13 01:31 -0800
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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
27from __future__ import annotations
29from collections.abc import Callable
30from dataclasses import dataclass
31from functools import partial
33from astropy.table import Table
35from .._butler import Butler
36from .._collection_type import CollectionType
37from ..registry import MissingCollectionError, OrphanedRecordError
40@dataclass
41class RemoveCollectionResult:
42 """Container to return to the cli command; holds tables describing the
43 collections that will be removed, as well as any found RUN collections
44 which can not be removed by this command. Also holds the callback function
45 to execute the remove upon user confirmation.
46 """
48 # the callback function to do the removal
49 onConfirmation: Callable[[], None]
50 # astropy table describing data that will be removed.
51 removeCollectionsTable: Table
52 # astropy table describing collection chain references that will be
53 # removed.
54 removeChainsTable: Table
55 # astropy table describing any run collections that will NOT be removed.
56 runsTable: Table
59@dataclass
60class CollectionInfo:
61 """Lightweight container to hold the name and type of non-run
62 collections, as well as the names of run collections.
63 """
65 nonRunCollections: Table
66 runCollections: Table
67 parentCollections: dict[str, tuple[str, ...]]
68 """Mapping from child collection name to the list of chained collections
69 names that contain it.
70 """
73def _getCollectionInfo(repo: str, collection: str, include_parents: bool) -> CollectionInfo:
74 """Get the names and types of collections that match the collection
75 string.
77 Parameters
78 ----------
79 repo : `str`
80 The URI to the repository.
81 collection : `str`
82 The collection string to search for. Same as the `expression`
83 argument to `registry.queryCollections`.
84 include_parents : `bool`
85 If `True`, will fetch the list of parent chained collections containing
86 the given collections.
88 Returns
89 -------
90 collectionInfo : `CollectionInfo`
91 Contains tables with run and non-run collection info.
92 """
93 butler = Butler.from_config(repo, without_datastore=True)
94 try:
95 collections_info = sorted(
96 butler.collections.query_info(collection, include_chains=True, include_parents=include_parents)
97 )
98 except MissingCollectionError:
99 # Hide the error and act like no collections should be removed.
100 collections_info = []
101 collections = Table(names=("Collection", "Collection Type"), dtype=(str, str))
102 runCollections = Table(names=("Collection",), dtype=(str,))
103 parents: dict[str, tuple[str, ...]] = {}
104 for collection_info in collections_info:
105 if collection_info.type == CollectionType.RUN:
106 runCollections.add_row((collection_info.name,))
107 else:
108 collections.add_row((collection_info.name, collection_info.type.name))
109 if include_parents and collection_info.parents is not None and len(collection_info.parents) > 0:
110 parents[collection_info.name] = tuple(collection_info.parents)
112 return CollectionInfo(collections, runCollections, parents)
115def removeCollections(repo: str, collection: str, remove_from_parents: bool) -> RemoveCollectionResult:
116 """Remove collections.
118 Parameters
119 ----------
120 repo : `str`
121 Same as the ``config`` argument to ``Butler.__init__``.
122 collection : `str`
123 Same as the ``name`` argument to ``Registry.removeCollection``.
124 remove_from_parents : `bool`
125 If `True`, will remove the given collections from any chained
126 collections they belong to before removing the collection
127 itself.
129 Returns
130 -------
131 collections : `RemoveCollectionResult`
132 Contains tables describing what will be removed, and
133 run collections that *will not* be removed.
134 """
135 collectionInfo = _getCollectionInfo(repo, collection, remove_from_parents)
137 def _doRemove(collections: Table) -> None:
138 """Perform the prune collection step."""
139 butler = Butler.from_config(repo, writeable=True, without_datastore=True)
141 for name in collections["Collection"]:
142 with butler.transaction():
143 for parent in collectionInfo.parentCollections.get(name, []):
144 butler.collections.remove_from_chain(parent, name)
145 try:
146 butler.collections.x_remove(name)
147 except OrphanedRecordError as e:
148 e.add_note(
149 "Add the --remove-from-parents flag to this command"
150 " if you are sure this collection is no longer needed."
151 )
152 raise
154 remove_chains_table = Table(names=("Child Collection", "Parent Collection"), dtype=(str, str))
155 for child in sorted(collectionInfo.parentCollections.keys()):
156 parents = collectionInfo.parentCollections[child]
157 key = child
158 for parent in sorted(parents):
159 remove_chains_table.add_row((key, parent))
160 key = ""
162 result = RemoveCollectionResult(
163 onConfirmation=partial(_doRemove, collectionInfo.nonRunCollections),
164 removeCollectionsTable=collectionInfo.nonRunCollections,
165 runsTable=collectionInfo.runCollections,
166 removeChainsTable=remove_chains_table,
167 )
168 return result