Coverage for python/lsst/daf/butler/cli/cmd/commands.py: 77%
289 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-25 10:50 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-25 10:50 +0000
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
29__all__ = ()
31from typing import Any
33import click
35from ... import script
36from ..opt import (
37 collection_argument,
38 collection_type_option,
39 collections_argument,
40 collections_option,
41 components_option,
42 confirm_option,
43 dataset_type_option,
44 datasets_option,
45 destination_argument,
46 dimensions_argument,
47 directory_argument,
48 element_argument,
49 glob_argument,
50 limit_option,
51 offset_option,
52 options_file_option,
53 order_by_option,
54 query_datasets_options,
55 register_dataset_types_option,
56 repo_argument,
57 transfer_dimensions_option,
58 transfer_option,
59 verbose_option,
60 where_option,
61)
62from ..utils import (
63 ButlerCommand,
64 MWOptionDecorator,
65 option_section,
66 printAstropyTables,
67 split_commas,
68 to_upper,
69 typeStrAcceptsMultiple,
70 unwrap,
71 where_help,
72)
74willCreateRepoHelp = "REPO is the URI or path to the new repository. Will be created if it does not exist."
75existingRepoHelp = "REPO is the URI or path to an existing data repository root or configuration file."
78@click.command(cls=ButlerCommand, short_help="Add existing datasets to a tagged collection.")
79@repo_argument(required=True)
80@collection_argument(help="COLLECTION is the collection the datasets should be associated with.")
81@query_datasets_options(repo=False, showUri=False, useArguments=False)
82@options_file_option()
83def associate(**kwargs: Any) -> None:
84 """Add existing datasets to a tagged collection; searches for datasets with
85 the options and adds them to the named COLLECTION.
86 """
87 script.associate(**kwargs)
90# The conversion from the import command name to the butler_import function
91# name for subcommand lookup is implemented in the cli/butler.py, in
92# funcNameToCmdName and cmdNameToFuncName. If name changes are made here they
93# must be reflected in that location. If this becomes a common pattern a better
94# mechanism should be implemented.
95@click.command("import", cls=ButlerCommand)
96@repo_argument(required=True, help=willCreateRepoHelp)
97@directory_argument(required=True)
98@transfer_option()
99@click.option(
100 "--export-file",
101 help="Name for the file that contains database information associated with the exported "
102 "datasets. If this is not an absolute path, does not exist in the current working "
103 "directory, and --dir is provided, it is assumed to be in that directory. Defaults "
104 'to "export.yaml".',
105 type=str,
106)
107@click.option(
108 "--skip-dimensions",
109 "-s",
110 type=str,
111 multiple=True,
112 callback=split_commas,
113 metavar=typeStrAcceptsMultiple,
114 help="Dimensions that should be skipped during import",
115)
116@options_file_option()
117def butler_import(*args: Any, **kwargs: Any) -> None:
118 """Import data into a butler repository."""
119 script.butlerImport(*args, **kwargs)
122@click.command(cls=ButlerCommand)
123@repo_argument(required=True, help=willCreateRepoHelp)
124@click.option("--seed-config", help="Path to an existing YAML config file to apply (on top of defaults).")
125@click.option("--dimension-config", help="Path to an existing YAML config file with dimension configuration.")
126@click.option(
127 "--standalone",
128 is_flag=True,
129 help="Include all defaults in the config file in the repo, "
130 "insulating the repo from changes in package defaults.",
131)
132@click.option(
133 "--override", is_flag=True, help="Allow values in the supplied config to override all repo settings."
134)
135@click.option(
136 "--outfile",
137 "-f",
138 default=None,
139 type=str,
140 help="Name of output file to receive repository "
141 "configuration. Default is to write butler.yaml into the specified repo.",
142)
143@options_file_option()
144def create(*args: Any, **kwargs: Any) -> None:
145 """Create an empty Gen3 Butler repository."""
146 script.createRepo(*args, **kwargs)
149@click.command(short_help="Dump butler config to stdout.", cls=ButlerCommand)
150@repo_argument(required=True, help=existingRepoHelp)
151@click.option(
152 "--subset",
153 "-s",
154 type=str,
155 help="Subset of a configuration to report. This can be any key in the hierarchy such as "
156 "'.datastore.root' where the leading '.' specified the delimiter for the hierarchy.",
157)
158@click.option(
159 "--searchpath",
160 "-p",
161 type=str,
162 multiple=True,
163 callback=split_commas,
164 metavar=typeStrAcceptsMultiple,
165 help="Additional search paths to use for configuration overrides",
166)
167@click.option(
168 "--file",
169 "outfile",
170 type=click.File(mode="w"),
171 default="-",
172 help="Print the (possibly-expanded) configuration for a repository to a file, or to stdout by default.",
173)
174@options_file_option()
175def config_dump(*args: Any, **kwargs: Any) -> None:
176 """Dump either a subset or full Butler configuration to standard output."""
177 script.configDump(*args, **kwargs)
180@click.command(short_help="Validate the configuration files.", cls=ButlerCommand)
181@repo_argument(required=True, help=existingRepoHelp)
182@click.option("--quiet", "-q", is_flag=True, help="Do not report individual failures.")
183@dataset_type_option(help="Specific DatasetType(s) to validate.", multiple=True)
184@click.option(
185 "--ignore",
186 "-i",
187 type=str,
188 multiple=True,
189 callback=split_commas,
190 metavar=typeStrAcceptsMultiple,
191 help="DatasetType(s) to ignore for validation.",
192)
193@options_file_option()
194def config_validate(*args: Any, **kwargs: Any) -> None:
195 """Validate the configuration files for a Gen3 Butler repository."""
196 is_good = script.configValidate(*args, **kwargs)
197 if not is_good:
198 raise click.exceptions.Exit(1)
201pruneDatasets_wouldRemoveMsg = unwrap(
202 """The following datasets will be removed from any datastores in which
203 they are present:"""
204)
205pruneDatasets_wouldDisassociateMsg = unwrap(
206 """The following datasets will be disassociated from {collections}
207 if they are currently present in it (which is not checked):"""
208)
209pruneDatasets_wouldDisassociateAndRemoveMsg = unwrap(
210 """The following datasets will be disassociated from
211 {collections} if they are currently present in it (which is
212 not checked), and removed from any datastores in which they
213 are present."""
214)
215pruneDatasets_willRemoveMsg = "The following datasets will be removed:"
216pruneDatasets_askContinueMsg = "Continue?"
217pruneDatasets_didRemoveAforementioned = "The datasets were removed."
218pruneDatasets_didNotRemoveAforementioned = "Did not remove the datasets."
219pruneDatasets_didRemoveMsg = "Removed the following datasets:"
220pruneDatasets_noDatasetsFound = "Did not find any datasets."
221pruneDatasets_errPurgeAndDisassociate = unwrap(
222 """"--disassociate and --purge may not be used together: --disassociate purges from just the passed TAGged
223 collections, but --purge forces disassociation from all of them. """
224)
225pruneDatasets_errQuietWithDryRun = "Can not use --quiet and --dry-run together."
226pruneDatasets_errNoCollectionRestriction = unwrap(
227 """Must indicate collections from which to prune datasets by passing COLLECTION arguments (select all
228 collections by passing '*', or consider using 'butler prune-collections'), by using --purge to pass a run
229 collection, or by using --disassociate to select a tagged collection."""
230)
231pruneDatasets_errPruneOnNotRun = "Can not prune a collection that is not a RUN collection: {collection}"
232pruneDatasets_errNoOp = "No operation: one of --purge, --unstore, or --disassociate must be provided."
234disassociate_option = MWOptionDecorator(
235 "--disassociate",
236 "disassociate_tags",
237 help=unwrap(
238 """Disassociate pruned datasets from the given tagged collections. May not be used with
239 --purge."""
240 ),
241 multiple=True,
242 callback=split_commas,
243 metavar="TAG",
244)
247purge_option = MWOptionDecorator(
248 "--purge",
249 "purge_run",
250 help=unwrap(
251 """Completely remove the dataset from the given RUN in the Registry. May not be used with
252 --disassociate. Implies --unstore. Note, this may remove provenance information from
253 datasets other than those provided, and should be used with extreme care.
254 RUN has to be provided for backward compatibility, but is used only if COLLECTIONS is
255 not provided. Otherwise, datasets will be removed from
256 any RUN-type collections in COLLECTIONS."""
257 ),
258 metavar="RUN",
259)
262find_all_option = MWOptionDecorator(
263 "--find-all",
264 is_flag=True,
265 help=unwrap(
266 """Purge the dataset results from all of the collections in which a dataset of that dataset
267 type + data id combination appear. (By default only the first found dataset type + data id is
268 purged, according to the order of COLLECTIONS passed in)."""
269 ),
270)
273unstore_option = MWOptionDecorator(
274 "--unstore",
275 is_flag=True,
276 help=unwrap(
277 """Remove these datasets from all datastores configured with this data repository. If
278 --disassociate and --purge are not used then --unstore will be used by default. Note that
279 --unstore will make it impossible to retrieve these datasets even via other collections.
280 Datasets that are already not stored are ignored by this option."""
281 ),
282)
285dry_run_option = MWOptionDecorator(
286 "--dry-run",
287 is_flag=True,
288 help=unwrap(
289 """Display the datasets that would be removed but do not remove them.
291 Note that a dataset can be in collections other than its RUN-type collection, and removing it
292 will remove it from all of them, even though the only one this will show is its RUN
293 collection."""
294 ),
295)
298quiet_option = MWOptionDecorator(
299 "--quiet",
300 is_flag=True,
301 help=unwrap("""Makes output quiet. Implies --no-confirm. Requires --dry-run not be passed."""),
302)
305@click.command(cls=ButlerCommand, short_help="Remove datasets.")
306@repo_argument(required=True)
307@collections_argument(
308 help=unwrap(
309 """COLLECTIONS is or more expressions that identify the collections to
310 search for datasets. Glob-style expressions may be used but only if the
311 --find-all flag is also passed."""
312 )
313)
314@option_section("Query Datasets Options:")
315@datasets_option(
316 help="One or more glob-style expressions that identify the dataset types to be pruned.",
317 multiple=True,
318 callback=split_commas,
319)
320@find_all_option()
321@where_option(help=where_help)
322@option_section("Prune Options:")
323@disassociate_option()
324@purge_option()
325@unstore_option()
326@option_section("Execution Options:")
327@dry_run_option()
328@confirm_option()
329@quiet_option()
330@option_section("Other Options:")
331@options_file_option()
332def prune_datasets(**kwargs: Any) -> None:
333 """Query for and remove one or more datasets from a collection and/or
334 storage.
335 """
336 quiet = kwargs.pop("quiet", False)
337 if quiet:
338 if kwargs["dry_run"]:
339 raise click.ClickException(message=pruneDatasets_errQuietWithDryRun)
340 kwargs["confirm"] = False
342 result = script.pruneDatasets(**kwargs)
344 if result.errPurgeAndDisassociate:
345 raise click.ClickException(message=pruneDatasets_errPurgeAndDisassociate)
346 if result.errNoCollectionRestriction:
347 raise click.ClickException(message=pruneDatasets_errNoCollectionRestriction)
348 if result.errPruneOnNotRun:
349 raise click.ClickException(message=pruneDatasets_errPruneOnNotRun.format(**result.errDict))
350 if result.errNoOp:
351 raise click.ClickException(message=pruneDatasets_errNoOp)
352 if result.dryRun:
353 assert result.action is not None, "Dry run results have not been set up properly."
354 if result.action["disassociate"] and result.action["unstore"]:
355 msg = pruneDatasets_wouldDisassociateAndRemoveMsg
356 elif result.action["disassociate"]:
357 msg = pruneDatasets_wouldDisassociateMsg
358 else:
359 msg = pruneDatasets_wouldRemoveMsg
360 print(msg.format(**result.action))
361 printAstropyTables(result.tables)
362 return
363 if result.confirm:
364 if not result.tables:
365 print(pruneDatasets_noDatasetsFound)
366 return
367 print(pruneDatasets_willRemoveMsg)
368 printAstropyTables(result.tables)
369 doContinue = click.confirm(text=pruneDatasets_askContinueMsg, default=False)
370 if doContinue:
371 if result.onConfirmation:
372 result.onConfirmation()
373 print(pruneDatasets_didRemoveAforementioned)
374 else:
375 print(pruneDatasets_didNotRemoveAforementioned)
376 return
377 if result.finished:
378 if not quiet:
379 print(pruneDatasets_didRemoveMsg)
380 printAstropyTables(result.tables)
381 return
384@click.command(short_help="Search for collections.", cls=ButlerCommand)
385@repo_argument(required=True)
386@glob_argument(
387 help="GLOB is one or more glob-style expressions that fully or partially identify the "
388 "collections to return."
389)
390@collection_type_option()
391@click.option(
392 "--chains",
393 default="TREE",
394 help="""Affects how results are presented:
396 TABLE lists each dataset in table form, with columns for dataset name
397 and type, and a column that lists children of CHAINED datasets (if any
398 CHAINED datasets are found).
400 INVERSE-TABLE is like TABLE but instead of a column listing CHAINED
401 dataset children, it lists the parents of the dataset if it is contained
402 in any CHAINED collections.
404 TREE recursively lists children below each CHAINED dataset in tree form.
406 INVERSE-TREE recursively lists parent datasets below each dataset in
407 tree form.
409 FLATTEN lists all datasets, including child datasets, in one list.
411 [default: TREE]""",
412 # above, the default value is included, instead of using show_default, so
413 # that the default is printed on its own line instead of coming right after
414 # the FLATTEN text.
415 callback=to_upper,
416 type=click.Choice(
417 choices=("TABLE", "INVERSE-TABLE", "TREE", "INVERSE-TREE", "FLATTEN"),
418 case_sensitive=False,
419 ),
420)
421@options_file_option()
422def query_collections(*args: Any, **kwargs: Any) -> None:
423 """Get the collections whose names match an expression."""
424 table = script.queryCollections(*args, **kwargs)
425 # The unit test that mocks script.queryCollections does not return a table
426 # so we need the following `if`.
427 if table:
428 # When chains==TREE, the children of chained datasets are indented
429 # relative to their parents. For this to work properly the table must
430 # be left-aligned.
431 table.pprint_all(align="<")
434@click.command(cls=ButlerCommand)
435@repo_argument(required=True)
436@glob_argument(
437 help="GLOB is one or more glob-style expressions that fully or partially identify the "
438 "dataset types to return."
439)
440@verbose_option(help="Include dataset type name, dimensions, and storage class in output.")
441@components_option()
442@options_file_option()
443def query_dataset_types(*args: Any, **kwargs: Any) -> None:
444 """Get the dataset types in a repository."""
445 # Drop the components option.
446 components = kwargs.pop("components")
447 if components is not None:
448 comp_opt_str = "" if components else "no-"
449 click.echo(f"WARNING: --{comp_opt_str}components option is deprecated and will be removed after v27.")
450 table = script.queryDatasetTypes(*args, **kwargs)
451 if table:
452 table.pprint_all()
453 else:
454 print("No results. Try --help for more information.")
457@click.command(cls=ButlerCommand)
458@repo_argument(required=True)
459@click.argument("dataset-type-name", nargs=-1)
460def remove_dataset_type(*args: Any, **kwargs: Any) -> None:
461 """Remove the dataset type definitions from a repository."""
462 script.removeDatasetType(*args, **kwargs)
465@click.command(cls=ButlerCommand)
466@query_datasets_options()
467@options_file_option()
468def query_datasets(**kwargs: Any) -> None:
469 """List the datasets in a repository."""
470 for table in script.QueryDatasets(**kwargs).getTables():
471 print("")
472 table.pprint_all()
473 print("")
476@click.command(cls=ButlerCommand)
477@repo_argument(required=True)
478@click.argument("input-collection")
479@click.argument("output-collection")
480@click.argument("dataset-type-name")
481@click.option(
482 "--begin-date",
483 type=str,
484 default=None,
485 help=unwrap(
486 """ISO-8601 datetime (TAI) of the beginning of the validity range for the
487 certified calibrations."""
488 ),
489)
490@click.option(
491 "--end-date",
492 type=str,
493 default=None,
494 help=unwrap(
495 """ISO-8601 datetime (TAI) of the end of the validity range for the
496 certified calibrations."""
497 ),
498)
499@click.option(
500 "--search-all-inputs",
501 is_flag=True,
502 default=False,
503 help=unwrap(
504 """Search all children of the inputCollection if it is a CHAINED collection,
505 instead of just the most recent one."""
506 ),
507)
508@options_file_option()
509def certify_calibrations(*args: Any, **kwargs: Any) -> None:
510 """Certify calibrations in a repository."""
511 script.certifyCalibrations(*args, **kwargs)
514@click.command(cls=ButlerCommand)
515@repo_argument(required=True)
516@dimensions_argument(
517 help=unwrap(
518 """DIMENSIONS are the keys of the data IDs to yield, such as exposure,
519 instrument, or tract. Will be expanded to include any dependencies."""
520 )
521)
522@collections_option(help=collections_option.help + " May only be used with --datasets.")
523@datasets_option(
524 help=unwrap(
525 """An expression that fully or partially identifies dataset types that should
526 constrain the yielded data IDs. For example, including "raw" here would
527 constrain the yielded "instrument", "exposure", "detector", and
528 "physical_filter" values to only those for which at least one "raw" dataset
529 exists in "collections". Requires --collections."""
530 )
531)
532@where_option(help=where_help)
533@order_by_option()
534@limit_option()
535@offset_option()
536@options_file_option()
537def query_data_ids(**kwargs: Any) -> None:
538 """List the data IDs in a repository."""
539 table, reason = script.queryDataIds(**kwargs)
540 if table:
541 table.pprint_all()
542 else:
543 if reason:
544 print(reason)
545 if not kwargs.get("dimensions") and not kwargs.get("datasets"):
546 print("No results. Try requesting some dimensions or datasets, see --help for more information.")
547 else:
548 print("No results. Try --help for more information.")
551@click.command(cls=ButlerCommand)
552@repo_argument(required=True)
553@element_argument(required=True)
554@datasets_option(
555 help=unwrap(
556 """An expression that fully or partially identifies dataset types that should
557 constrain the yielded records. May only be used with
558 --collections."""
559 )
560)
561@collections_option(help=collections_option.help + " May only be used with --datasets.")
562@where_option(help=where_help)
563@order_by_option()
564@limit_option()
565@offset_option()
566@click.option(
567 "--no-check",
568 is_flag=True,
569 help=unwrap(
570 """Don't check the query before execution. By default the query is checked before it
571 executed, this may reject some valid queries that resemble common mistakes."""
572 ),
573)
574@options_file_option()
575def query_dimension_records(**kwargs: Any) -> None:
576 """Query for dimension information."""
577 table = script.queryDimensionRecords(**kwargs)
578 if table:
579 table.pprint_all()
580 else:
581 print("No results. Try --help for more information.")
584@click.command(cls=ButlerCommand)
585@repo_argument(required=True)
586@query_datasets_options(showUri=False, useArguments=False, repo=False)
587@destination_argument(help="Destination URI of folder to receive file artifacts.")
588@transfer_option()
589@verbose_option(help="Report destination location of all transferred artifacts.")
590@click.option(
591 "--preserve-path/--no-preserve-path",
592 is_flag=True,
593 default=True,
594 help="Preserve the datastore path to the artifact at the destination.",
595)
596@click.option(
597 "--clobber/--no-clobber",
598 is_flag=True,
599 default=False,
600 help="If clobber, overwrite files if they exist locally.",
601)
602@options_file_option()
603def retrieve_artifacts(**kwargs: Any) -> None:
604 """Retrieve file artifacts associated with datasets in a repository."""
605 verbose = kwargs.pop("verbose")
606 transferred = script.retrieveArtifacts(**kwargs)
607 if verbose and transferred:
608 print(f"Transferred the following to {kwargs['destination']}:")
609 for uri in transferred:
610 print(uri)
611 print()
612 print(f"Number of artifacts retrieved into destination {kwargs['destination']}: {len(transferred)}")
615@click.command(cls=ButlerCommand)
616@click.argument("source", required=True)
617@click.argument("dest", required=True)
618@query_datasets_options(showUri=False, useArguments=False, repo=False)
619@transfer_option()
620@register_dataset_types_option()
621@transfer_dimensions_option()
622@options_file_option()
623def transfer_datasets(**kwargs: Any) -> None:
624 """Transfer datasets from a source butler to a destination butler.
626 SOURCE is a URI to the Butler repository containing the RUN dataset.
628 DEST is a URI to the Butler repository that will receive copies of the
629 datasets.
630 """
631 number = script.transferDatasets(**kwargs)
632 print(f"Number of datasets transferred: {number}")
635@click.command(cls=ButlerCommand)
636@repo_argument(required=True)
637@click.argument("parent", required=True, nargs=1)
638@click.argument("children", required=False, nargs=-1, callback=split_commas)
639@click.option(
640 "--doc",
641 default="",
642 help="Documentation string associated with this collection. "
643 "Only relevant if the collection is newly created.",
644)
645@click.option(
646 "--flatten/--no-flatten",
647 default=False,
648 help="If `True` recursively flatten out any nested chained collections in children first.",
649)
650@click.option(
651 "--mode",
652 type=click.Choice(["redefine", "extend", "remove", "prepend", "pop"]),
653 default="redefine",
654 help="Update mode: "
655 "'redefine': Create new chain or redefine existing chain with the supplied CHILDREN. "
656 "'remove': Modify existing chain to remove the supplied CHILDREN. "
657 "'pop': Pop a numbered element off the chain. Defaults to popping "
658 "the first element (0). ``children`` must be integers if given. "
659 "'prepend': Modify existing chain to prepend the supplied CHILDREN to the front. "
660 "'extend': Modify existing chain to extend it with the supplied CHILDREN.",
661)
662def collection_chain(**kwargs: Any) -> None:
663 """Define a collection chain.
665 PARENT is the name of the chained collection to create or modify. If the
666 collection already exists the chain associated with it will be updated.
668 CHILDREN are the collections to be used to modify the chain. The supplied
669 values will be split on comma. The exact usage depends on the MODE option.
670 For example,
672 $ butler collection-chain REPO PARENT child1,child2 child3
674 will result in three children being included in the chain.
676 When the MODE is 'pop' the CHILDREN should be integer indices indicating
677 collections to be removed from the current chain.
678 MODE 'pop' can take negative integers to indicate removal relative to the
679 end of the chain, but when doing that '--' must be given to indicate the
680 end of the options specification.
682 $ butler collection-chain REPO --mode=pop PARENT -- -1
684 Will remove the final collection from the chain.
685 """
686 chain = script.collectionChain(**kwargs)
687 print(f"[{', '.join(chain)}]")
690@click.command(cls=ButlerCommand)
691@repo_argument(required=True)
692@click.argument("dataset_type", required=True)
693@click.argument("run", required=True)
694@click.argument("table_file", required=True)
695@click.option(
696 "--formatter",
697 type=str,
698 help="Fully-qualified python class to use as the Formatter. If not specified the formatter"
699 " will be determined from the dataset type and datastore configuration.",
700)
701@click.option(
702 "--id-generation-mode",
703 default="UNIQUE",
704 help="Mode to use for generating dataset IDs. The default creates a unique ID. Other options"
705 " are: 'DATAID_TYPE' for creating a reproducible ID from the dataID and dataset type;"
706 " 'DATAID_TYPE_RUN' for creating a reproducible ID from the dataID, dataset type and run."
707 " The latter is usually used for 'raw'-type data that will be ingested in multiple."
708 " repositories.",
709 callback=to_upper,
710 type=click.Choice(("UNIQUE", "DATAID_TYPE", "DATAID_TYPE_RUN"), case_sensitive=False),
711)
712@click.option(
713 "--data-id",
714 type=str,
715 multiple=True,
716 callback=split_commas,
717 help="Keyword=value string with an additional dataId value that is fixed for all ingested"
718 " files. This can be used to simplify the table file by removing repeated entries that are"
719 " fixed for all files to be ingested. Multiple key/values can be given either by using"
720 " comma separation or multiple command line options.",
721)
722@click.option(
723 "--prefix",
724 type=str,
725 help="For relative paths in the table file, specify a prefix to use. The default is to"
726 " use the current working directory.",
727)
728@transfer_option()
729def ingest_files(**kwargs: Any) -> None:
730 """Ingest files from table file.
732 DATASET_TYPE is the name of the dataset type to be associated with these
733 files. This dataset type must already exist and will not be created by
734 this command. There can only be one dataset type per invocation of this
735 command.
737 RUN is the run to use for the file ingest.
739 TABLE_FILE refers to a file that can be read by astropy.table with
740 columns of:
742 file URI, dimension1, dimension2, ..., dimensionN
744 where the first column is the URI to the file to be ingested and the
745 remaining columns define the dataId to associate with that file.
746 The column names should match the dimensions for the specified dataset
747 type. Relative file URI by default is assumed to be relative to the
748 current working directory but can be overridden using the ``--prefix``
749 option.
751 This command does not create dimension records and so any records must
752 be created by other means. This command should not be used to ingest
753 raw camera exposures.
754 """
755 script.ingest_files(**kwargs)
758@click.command(cls=ButlerCommand)
759@repo_argument(required=True)
760@click.argument("dataset_type", required=True)
761@click.argument("storage_class", required=True)
762@click.argument("dimensions", required=False, nargs=-1)
763@click.option(
764 "--is-calibration/--no-is-calibration",
765 is_flag=True,
766 default=False,
767 help="Indicate that this dataset type can be part of a calibration collection.",
768)
769def register_dataset_type(**kwargs: Any) -> None:
770 """Register a new dataset type with this butler repository.
772 DATASET_TYPE is the name of the dataset type.
774 STORAGE_CLASS is the name of the StorageClass to be associated with
775 this dataset type.
777 DIMENSIONS is a list of all the dimensions relevant to this
778 dataset type. It can be an empty list.
780 A component dataset type (such as "something.component") is not a
781 real dataset type and so can not be defined by this command. They are
782 automatically derived from the composite dataset type when a composite
783 storage class is specified.
784 """
785 inserted = script.register_dataset_type(**kwargs)
786 if inserted:
787 print("Dataset type successfully registered.")
788 else:
789 print("Dataset type already existed in identical form.")
792@click.command(cls=ButlerCommand)
793@repo_argument(required=True)
794@directory_argument(required=True, help="DIRECTORY is the folder to receive the exported calibrations.")
795@collections_argument(help="COLLECTIONS are the collection to export calibrations from.")
796@dataset_type_option(help="Specific DatasetType(s) to export.", multiple=True)
797@transfer_option()
798def export_calibs(*args: Any, **kwargs: Any) -> None:
799 """Export calibrations from the butler for import elsewhere."""
800 table = script.exportCalibs(*args, **kwargs)
801 if table:
802 table.pprint_all(align="<")