Coverage for python / lsst / daf / butler / script / removeCollections.py: 31%
58 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-10 01:37 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-10 01:37 -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 with Butler.from_config(repo, without_datastore=True) as butler:
94 try:
95 collections_info = sorted(
96 butler.collections.query_info(
97 collection, include_chains=True, include_parents=include_parents
98 )
99 )
100 except MissingCollectionError:
101 # Hide the error and act like no collections should be removed.
102 collections_info = []
103 collections = Table(names=("Collection", "Collection Type"), dtype=(str, str))
104 runCollections = Table(names=("Collection",), dtype=(str,))
105 parents: dict[str, tuple[str, ...]] = {}
106 for collection_info in collections_info:
107 if collection_info.type == CollectionType.RUN:
108 runCollections.add_row((collection_info.name,))
109 else:
110 collections.add_row((collection_info.name, collection_info.type.name))
111 if (
112 include_parents
113 and collection_info.parents is not None
114 and len(collection_info.parents) > 0
115 ):
116 parents[collection_info.name] = tuple(collection_info.parents)
118 return CollectionInfo(collections, runCollections, parents)
121def removeCollections(repo: str, collection: str, remove_from_parents: bool) -> RemoveCollectionResult:
122 """Remove collections.
124 Parameters
125 ----------
126 repo : `str`
127 Same as the ``config`` argument to ``Butler.__init__``.
128 collection : `str`
129 Same as the ``name`` argument to ``Registry.removeCollection``.
130 remove_from_parents : `bool`
131 If `True`, will remove the given collections from any chained
132 collections they belong to before removing the collection
133 itself.
135 Returns
136 -------
137 collections : `RemoveCollectionResult`
138 Contains tables describing what will be removed, and
139 run collections that *will not* be removed.
140 """
141 collectionInfo = _getCollectionInfo(repo, collection, remove_from_parents)
143 def _doRemove(collections: Table) -> None:
144 """Perform the prune collection step."""
145 with Butler.from_config(repo, writeable=True, without_datastore=True) as butler:
146 for name in collections["Collection"]:
147 with butler.transaction():
148 for parent in collectionInfo.parentCollections.get(name, []):
149 butler.collections.remove_from_chain(parent, name)
150 try:
151 butler.collections.x_remove(name)
152 except OrphanedRecordError as e:
153 e.add_note(
154 "Add the --remove-from-parents flag to this command"
155 " if you are sure this collection is no longer needed."
156 )
157 raise
159 remove_chains_table = Table(names=("Child Collection", "Parent Collection"), dtype=(str, str))
160 for child in sorted(collectionInfo.parentCollections.keys()):
161 parents = collectionInfo.parentCollections[child]
162 key = child
163 for parent in sorted(parents):
164 remove_chains_table.add_row((key, parent))
165 key = ""
167 result = RemoveCollectionResult(
168 onConfirmation=partial(_doRemove, collectionInfo.nonRunCollections),
169 removeCollectionsTable=collectionInfo.nonRunCollections,
170 runsTable=collectionInfo.runCollections,
171 removeChainsTable=remove_chains_table,
172 )
173 return result