Coverage for python/lsst/daf/butler/cli/cmd/commands.py : 55%

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/>.
22import click
24from ..opt import (
25 collection_type_option,
26 collection_argument,
27 collections_argument,
28 collections_option,
29 components_option,
30 dataset_type_option,
31 datasets_option,
32 dimensions_argument,
33 directory_argument,
34 element_argument,
35 glob_argument,
36 options_file_option,
37 query_datasets_options,
38 repo_argument,
39 transfer_option,
40 verbose_option,
41 where_option,
42)
44from ..utils import (
45 ButlerCommand,
46 MWOptionDecorator,
47 option_section,
48 printAstropyTables,
49 split_commas,
50 to_upper,
51 typeStrAcceptsMultiple,
52 unwrap,
53 where_help,
54)
56from ... import script
59willCreateRepoHelp = "REPO is the URI or path to the new repository. Will be created if it does not exist."
60existingRepoHelp = "REPO is the URI or path to an existing data repository root or configuration file."
63@click.command(cls=ButlerCommand, short_help="Add existing datasets to a tagged collection.")
64@repo_argument(required=True)
65@collection_argument(help="COLLECTION is the collection the datasets should be associated with.")
66@query_datasets_options(repo=False, showUri=False, useArguments=False)
67@options_file_option()
68def associate(**kwargs):
69 """Add existing datasets to a tagged collection; searches for datasets with
70 the options and adds them to the named COLLECTION.
71 """
72 script.associate(**kwargs)
75# The conversion from the import command name to the butler_import function
76# name for subcommand lookup is implemented in the cli/butler.py, in
77# funcNameToCmdName and cmdNameToFuncName. If name changes are made here they
78# must be reflected in that location. If this becomes a common pattern a better
79# mechanism should be implemented.
80@click.command("import", cls=ButlerCommand)
81@repo_argument(required=True, help=willCreateRepoHelp)
82@directory_argument(required=True)
83@transfer_option()
84@click.option("--export-file",
85 help="Name for the file that contains database information associated with the exported "
86 "datasets. If this is not an absolute path, does not exist in the current working "
87 "directory, and --dir is provided, it is assumed to be in that directory. Defaults "
88 "to \"export.yaml\".",
89 type=click.File("r"))
90@click.option("--skip-dimensions", "-s", type=str, multiple=True, callback=split_commas,
91 metavar=typeStrAcceptsMultiple,
92 help="Dimensions that should be skipped during import")
93@options_file_option()
94def butler_import(*args, **kwargs):
95 """Import data into a butler repository."""
96 script.butlerImport(*args, **kwargs)
99@click.command(cls=ButlerCommand)
100@repo_argument(required=True, help=willCreateRepoHelp)
101@click.option("--seed-config", help="Path to an existing YAML config file to apply (on top of defaults).")
102@click.option("--dimension-config", help="Path to an existing YAML config file with dimension configuration.")
103@click.option("--standalone", is_flag=True, help="Include all defaults in the config file in the repo, "
104 "insulating the repo from changes in package defaults.")
105@click.option("--override", is_flag=True, help="Allow values in the supplied config to override all "
106 "repo settings.")
107@click.option("--outfile", "-f", default=None, type=str, help="Name of output file to receive repository "
108 "configuration. Default is to write butler.yaml into the specified repo.")
109@options_file_option()
110def create(*args, **kwargs):
111 """Create an empty Gen3 Butler repository."""
112 script.createRepo(*args, **kwargs)
115@click.command(short_help="Dump butler config to stdout.", cls=ButlerCommand)
116@repo_argument(required=True, help=existingRepoHelp)
117@click.option("--subset", "-s", type=str,
118 help="Subset of a configuration to report. This can be any key in the hierarchy such as "
119 "'.datastore.root' where the leading '.' specified the delimiter for the hierarchy.")
120@click.option("--searchpath", "-p", type=str, multiple=True, callback=split_commas,
121 metavar=typeStrAcceptsMultiple,
122 help="Additional search paths to use for configuration overrides")
123@click.option("--file", "outfile", type=click.File("w"), default="-",
124 help="Print the (possibly-expanded) configuration for a repository to a file, or to stdout "
125 "by default.")
126@options_file_option()
127def config_dump(*args, **kwargs):
128 """Dump either a subset or full Butler configuration to standard output."""
129 script.configDump(*args, **kwargs)
132@click.command(short_help="Validate the configuration files.", cls=ButlerCommand)
133@repo_argument(required=True, help=existingRepoHelp)
134@click.option("--quiet", "-q", is_flag=True, help="Do not report individual failures.")
135@dataset_type_option(help="Specific DatasetType(s) to validate.", multiple=True)
136@click.option("--ignore", "-i", type=str, multiple=True, callback=split_commas,
137 metavar=typeStrAcceptsMultiple,
138 help="DatasetType(s) to ignore for validation.")
139@options_file_option()
140def config_validate(*args, **kwargs):
141 """Validate the configuration files for a Gen3 Butler repository."""
142 is_good = script.configValidate(*args, **kwargs)
143 if not is_good:
144 raise click.exceptions.Exit(1)
147@click.command(cls=ButlerCommand)
148@repo_argument(required=True)
149@collection_argument(help=unwrap("""COLLECTION is the Name of the collection to remove. If this is a tagged or
150 chained collection, datasets within the collection are not modified unless --unstore
151 is passed. If this is a run collection, --purge and --unstore must be passed, and
152 all datasets in it are fully removed from the data repository."""))
153@click.option("--purge",
154 help=unwrap("""Permit RUN collections to be removed, fully removing datasets within them.
155 Requires --unstore as an added precaution against accidental deletion. Must not be
156 passed if the collection is not a RUN."""),
157 is_flag=True)
158@click.option("--unstore",
159 help=("""Remove all datasets in the collection from all datastores in which they appear."""),
160 is_flag=True)
161@click.option("--unlink",
162 help="Before removing the given `collection` unlink it from from this parent collection.",
163 multiple=True,
164 callback=split_commas)
165@options_file_option()
166def prune_collection(**kwargs):
167 """Remove a collection and possibly prune datasets within it."""
168 script.pruneCollection(**kwargs)
171pruneDatasets_wouldRemoveMsg = unwrap("""The following datasets will be removed from any datastores in which
172 they are present:""")
173pruneDatasets_wouldDisassociateMsg = unwrap("""The following datasets will be disassociated from {collections}
174 if they are currently present in it (which is not checked):""")
175pruneDatasets_wouldDisassociateAndRemoveMsg = unwrap("""The following datasets will be disassociated from
176 {collections} if they are currently present in it (which is
177 not checked), and removed from any datastores in which they
178 are present.""")
179pruneDatasets_willRemoveMsg = "The following datasets will be removed:"
180pruneDatasets_askContinueMsg = "Continue?"
181pruneDatasets_didRemoveAforementioned = "The datasets were removed."
182pruneDatasets_didNotRemoveAforementioned = "Did not remove the datasets."
183pruneDatasets_didRemoveMsg = "Removed the following datasets:"
184pruneDatasets_noDatasetsFound = "Did not find any datasets."
185pruneDatasets_errPurgeAndDisassociate = unwrap(
186 """"--disassociate and --purge may not be used together: --disassociate purges from just the passed TAGged
187 collections, but --purge forces disassociation from all of them. """
188)
189pruneDatasets_errQuietWithDryRun = "Can not use --quiet and --dry-run together."
190pruneDatasets_errNoCollectionRestriction = unwrap(
191 """Must indicate collections from which to prune datasets by passing COLLETION arguments (select all
192 collections by passing '*', or consider using 'butler prune-collections'), by using --purge to pass a run
193 collection, or by using --disassociate to select a tagged collection.""")
194pruneDatasets_errPruneOnNotRun = "Can not prune a collection that is not a RUN collection: {collection}"
195pruneDatasets_errNoOp = "No operation: one of --purge, --unstore, or --disassociate must be provided."
197disassociate_option = MWOptionDecorator(
198 "--disassociate", "disassociate_tags",
199 help=unwrap("""Disassociate pruned datasets from the given tagged collections. May not be used with
200 --purge."""),
201 multiple=True,
202 callback=split_commas,
203 metavar="TAG"
204)
207purge_option = MWOptionDecorator(
208 "--purge", "purge_run",
209 help=unwrap("""Completely remove the dataset from the given RUN in the Registry. May not be used with
210 --disassociate. Note, this may remove provenance information from datasets other than those
211 provided, and should be used with extreme care."""),
212 metavar="RUN"
213)
216find_all_option = MWOptionDecorator(
217 "--find-all", is_flag=True,
218 help=unwrap("""Purge the dataset results from all of the collections in which a dataset of that dataset
219 type + data id combination appear. (By default only the first found dataset type + data id is
220 purged, according to the order of COLLECTIONS passed in).""")
221)
224unstore_option = MWOptionDecorator(
225 "--unstore",
226 is_flag=True,
227 help=unwrap("""Remove these datasets from all datastores configured with this data repository. If
228 --disassociate and --purge are not used then --unstore will be used by default. Note that
229 --unstore will make it impossible to retrieve these datasets even via other collections.
230 Datasets that are already not stored are ignored by this option.""")
231)
234dry_run_option = MWOptionDecorator(
235 "--dry-run",
236 is_flag=True,
237 help=unwrap("""Display the datasets that would be removed but do not remove them.
239 Note that a dataset can be in collections other than its RUN-type collection, and removing it
240 will remove it from all of them, even though the only one this will show is its RUN
241 collection.""")
242)
245confirm_option = MWOptionDecorator(
246 "--confirm/--no-confirm",
247 default=True,
248 help="Print expected action and a confirmation prompt before executing. Default is --confirm."
249)
252quiet_option = MWOptionDecorator(
253 "--quiet",
254 is_flag=True,
255 help=unwrap("""Makes output quiet. Implies --no-confirm. Requires --dry-run not be passed.""")
256)
259@click.command(cls=ButlerCommand, short_help="Remove datasets.")
260@repo_argument(required=True)
261@collections_argument(help=unwrap("""COLLECTIONS is or more expressions that identify the collections to
262 search for datasets. Glob-style expressions may be used but only if the
263 --find-all flag is also passed."""))
264@option_section("Query Datasets Options:")
265@datasets_option(help="One or more glob-style expressions that identify the dataset types to be pruned.",
266 multiple=True,
267 callback=split_commas)
268@find_all_option()
269@where_option(help=where_help)
270@option_section("Prune Options:")
271@disassociate_option()
272@purge_option()
273@unstore_option()
274@option_section("Execution Options:")
275@dry_run_option()
276@confirm_option()
277@quiet_option()
278@option_section("Other Options:")
279@options_file_option()
280def prune_datasets(**kwargs):
281 """Query for and remove one or more datasets from a collection and/or
282 storage.
283 """
284 quiet = kwargs.pop("quiet", False)
285 if quiet:
286 if kwargs["dry_run"]:
287 raise click.ClickException(pruneDatasets_errQuietWithDryRun)
288 kwargs["confirm"] = False
290 result = script.pruneDatasets(**kwargs)
292 if result.errPurgeAndDisassociate:
293 raise click.ClickException(pruneDatasets_errPurgeAndDisassociate)
294 return
295 if result.errNoCollectionRestriction:
296 raise click.ClickException(pruneDatasets_errNoCollectionRestriction)
297 if result.errPruneOnNotRun:
298 raise click.ClickException(pruneDatasets_errPruneOnNotRun.format(**result.errDict))
299 if result.errNoOp:
300 raise click.ClickException(pruneDatasets_errNoOp)
301 if result.dryRun:
302 if result.action["disassociate"] and result.action["unstore"]:
303 msg = pruneDatasets_wouldDisassociateAndRemoveMsg
304 elif result.action["disassociate"]:
305 msg = pruneDatasets_wouldDisassociateMsg
306 else:
307 msg = pruneDatasets_wouldRemoveMsg
308 print(msg.format(**result.action))
309 printAstropyTables(result.tables)
310 return
311 if result.confirm:
312 if not result.tables:
313 print(pruneDatasets_noDatasetsFound)
314 return
315 print(pruneDatasets_willRemoveMsg)
316 printAstropyTables(result.tables)
317 doContinue = click.confirm(pruneDatasets_askContinueMsg, default=False)
318 if doContinue:
319 result.onConfirmation()
320 print(pruneDatasets_didRemoveAforementioned)
321 else:
322 print(pruneDatasets_didNotRemoveAforementioned)
323 return
324 if result.finished:
325 if not quiet:
326 print(pruneDatasets_didRemoveMsg)
327 printAstropyTables(result.tables)
328 return
331@click.command(short_help="Search for collections.", cls=ButlerCommand)
332@repo_argument(required=True)
333@glob_argument(help="GLOB is one or more glob-style expressions that fully or partially identify the "
334 "collections to return.")
335@collection_type_option()
336@click.option("--chains",
337 default="table",
338 help=unwrap("""Affects how results are presented. TABLE lists each dataset in a row with
339 chained datasets' children listed in a Definition column. TREE lists children below
340 their parent in tree form. FLATTEN lists all datasets, including child datasets in
341 one list.Defaults to TABLE. """),
342 callback=to_upper,
343 type=click.Choice(("TABLE", "TREE", "FLATTEN"), case_sensitive=False))
344@options_file_option()
345def query_collections(*args, **kwargs):
346 """Get the collections whose names match an expression."""
347 table = script.queryCollections(*args, **kwargs)
348 # The unit test that mocks script.queryCollections does not return a table
349 # so we need the following `if`.
350 if table:
351 # When chains==TREE, the children of chained datasets are indented
352 # relative to their parents. For this to work properly the table must
353 # be left-aligned.
354 table.pprint_all(align="<")
357@click.command(cls=ButlerCommand)
358@repo_argument(required=True)
359@glob_argument(help="GLOB is one or more glob-style expressions that fully or partially identify the "
360 "dataset types to return.")
361@verbose_option(help="Include dataset type name, dimensions, and storage class in output.")
362@components_option()
363@options_file_option()
364def query_dataset_types(*args, **kwargs):
365 """Get the dataset types in a repository."""
366 table = script.queryDatasetTypes(*args, **kwargs)
367 if table:
368 table.pprint_all()
369 else:
370 print("No results. Try --help for more information.")
373@click.command(cls=ButlerCommand)
374@repo_argument(required=True)
375@click.argument('dataset-type-name', nargs=1)
376def remove_dataset_type(*args, **kwargs):
377 """Remove a dataset type definition from a repository."""
378 script.removeDatasetType(*args, **kwargs)
381@click.command(cls=ButlerCommand)
382@query_datasets_options()
383@options_file_option()
384def query_datasets(**kwargs):
385 """List the datasets in a repository."""
386 for table in script.QueryDatasets(**kwargs).getTables():
387 print("")
388 table.pprint_all()
389 print("")
392@click.command(cls=ButlerCommand)
393@repo_argument(required=True)
394@click.argument('input-collection')
395@click.argument('output-collection')
396@click.argument('dataset-type-name')
397@click.option("--begin-date", type=str, default=None,
398 help=unwrap("""ISO-8601 datetime (TAI) of the beginning of the validity range for the
399 certified calibrations."""))
400@click.option("--end-date", type=str, default=None,
401 help=unwrap("""ISO-8601 datetime (TAI) of the end of the validity range for the
402 certified calibrations."""))
403@click.option("--search-all-inputs", is_flag=True, default=False,
404 help=unwrap("""Search all children of the inputCollection if it is a CHAINED collection,
405 instead of just the most recent one."""))
406@options_file_option()
407def certify_calibrations(*args, **kwargs):
408 """Certify calibrations in a repository.
409 """
410 script.certifyCalibrations(*args, **kwargs)
413@click.command(cls=ButlerCommand)
414@repo_argument(required=True)
415@dimensions_argument(help=unwrap("""DIMENSIONS are the keys of the data IDs to yield, such as exposure,
416 instrument, or tract. Will be expanded to include any dependencies."""))
417@collections_option()
418@datasets_option(help=unwrap("""An expression that fully or partially identifies dataset types that should
419 constrain the yielded data IDs. For example, including "raw" here would
420 constrain the yielded "instrument", "exposure", "detector", and
421 "physical_filter" values to only those for which at least one "raw" dataset
422 exists in "collections"."""))
423@where_option(help=where_help)
424@options_file_option()
425def query_data_ids(**kwargs):
426 """List the data IDs in a repository.
427 """
428 table = script.queryDataIds(**kwargs)
429 if table:
430 table.pprint_all()
431 else:
432 if not kwargs.get("dimensions") and not kwargs.get("datasets"):
433 print("No results. Try requesting some dimensions or datasets, see --help for more information.")
434 else:
435 print("No results. Try --help for more information.")
438@click.command(cls=ButlerCommand)
439@repo_argument(required=True)
440@element_argument(required=True)
441@datasets_option(help=unwrap("""An expression that fully or partially identifies dataset types that should
442 constrain the yielded records. Only affects results when used with
443 --collections."""))
444@collections_option(help=collections_option.help + " Only affects results when used with --datasets.")
445@where_option(help=where_help)
446@click.option("--no-check", is_flag=True,
447 help=unwrap("""Don't check the query before execution. By default the query is checked before it
448 executed, this may reject some valid queries that resemble common mistakes."""))
449@options_file_option()
450def query_dimension_records(**kwargs):
451 """Query for dimension information."""
452 table = script.queryDimensionRecords(**kwargs)
453 if table:
454 table.pprint_all()
455 else:
456 print("No results. Try --help for more information.")