divbase-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1188 @@
1
+ """
2
+ Command line interface for managing files in a DivBase project's store on DivBase.
3
+ """
4
+
5
+ from collections import defaultdict
6
+ from glob import glob
7
+ from pathlib import Path
8
+
9
+ import typer
10
+ from rich import print
11
+ from rich.console import Console
12
+ from rich.markup import escape as markup_escape
13
+ from rich.table import Table
14
+ from rich.tree import Tree
15
+ from typing_extensions import Annotated
16
+
17
+ from divbase_cli.cli_commands.shared_args_options import DOWNLOAD_DIR_OPTION, FORMAT_AS_TSV_OPTION, PROJECT_NAME_OPTION
18
+ from divbase_cli.cli_exceptions import (
19
+ DuplicateFileNamesError,
20
+ NoFilesSpecifiedError,
21
+ NotEmptyDirectoryError,
22
+ ShellExpandedGlobError,
23
+ UnsupportedCharactersError,
24
+ )
25
+ from divbase_cli.config_resolver import (
26
+ resolve_and_authenticate_project,
27
+ resolve_download_dir,
28
+ )
29
+ from divbase_cli.services.pre_signed_urls import DownloadOutcome
30
+ from divbase_cli.services.project_versions import get_version_details_command
31
+ from divbase_cli.services.s3_files import (
32
+ ToDownload,
33
+ ToUpload,
34
+ download_files_command,
35
+ filter_out_already_downloaded_files,
36
+ get_file_info_command,
37
+ list_files_command,
38
+ list_soft_deleted_files_command,
39
+ make_directories_command,
40
+ restore_objects_command,
41
+ soft_delete_objects_command,
42
+ stream_file_command,
43
+ upload_files_command,
44
+ )
45
+ from divbase_cli.utils import print_rich_table_as_tsv
46
+ from divbase_lib.api_schemas.s3 import ObjectDetails
47
+ from divbase_lib.divbase_constants import (
48
+ SUPPORTED_DIVBASE_FILE_TYPES,
49
+ SUPPORTED_DIVBASE_FILE_TYPES_DISPLAY,
50
+ UNSUPPORTED_CHARACTERS_DISPLAY,
51
+ UNSUPPORTED_CHARACTERS_IN_FILENAMES,
52
+ )
53
+ from divbase_lib.utils import format_datetime_for_cli, format_file_size
54
+
55
+ file_app = typer.Typer(no_args_is_help=True, help="Download/upload/list files to/from the project's store on DivBase.")
56
+
57
+ NO_FILES_SPECIFIED_MSG = "No files specified for the command, exiting..."
58
+ NO_UPLOAD_MATCHES_MSG = "The following file paths or glob patterns did not match any existing files:"
59
+
60
+ PREFIX_ARGUMENT = typer.Argument(
61
+ None,
62
+ help="Optional prefix to filter on. Use a '/' to specify a folder. e.g. 'vcfs/'",
63
+ )
64
+ DISABLE_VERIFY_CHECKSUMS_OPTION = typer.Option(
65
+ False,
66
+ "--disable-verify-checksums",
67
+ "-nc",
68
+ help="Turn off checksum verification which is on by default. "
69
+ "Checksum verification means all downloaded files are verified against their MD5 checksums. "
70
+ "It is recommended to leave checksum verification enabled unless you have a specific reason to disable it.",
71
+ )
72
+ PROJECT_VERSION_OPTION = typer.Option(
73
+ None,
74
+ "--project-version",
75
+ "-pv",
76
+ help="User defined version of the project's at which to download the files. If not provided, downloads the latest version of all selected files.",
77
+ )
78
+ DRY_RUN_OPTION = typer.Option(
79
+ False,
80
+ "--dry-run",
81
+ "-n",
82
+ help="If set, will not actually download the files, just print what would be downloaded.",
83
+ )
84
+ FLATTEN_DOWNLOADS_OPTION = typer.Option(
85
+ False,
86
+ "--flatten",
87
+ "-f",
88
+ help="Download all files directly into the download directory, ignoring any folder paths. "
89
+ "By default the folder structure in the project store is preserved when downloading.",
90
+ )
91
+ INCLUDE_RESULTS_FILES_OPTION = typer.Option(
92
+ False,
93
+ "--include-results-files",
94
+ "-r",
95
+ help="If set, will also show DivBase query results files which are hidden by default.",
96
+ )
97
+
98
+
99
+ @file_app.command("ls")
100
+ def list_files(
101
+ prefix: str | None = PREFIX_ARGUMENT,
102
+ detailed: bool = typer.Option(
103
+ False,
104
+ "--detailed",
105
+ "-l",
106
+ help="Show a detailed view including the file size and upload date.",
107
+ ),
108
+ format_output_as_tsv: bool = FORMAT_AS_TSV_OPTION,
109
+ include_results_files: bool = INCLUDE_RESULTS_FILES_OPTION,
110
+ show_deleted_files: bool = typer.Option(
111
+ False,
112
+ "--show-deleted-files",
113
+ "-s",
114
+ help="Show the files and folders in the project that are currently soft deleted. These can be recovered within a certain time frame after deletion.",
115
+ ),
116
+ project: str | None = PROJECT_NAME_OPTION,
117
+ ):
118
+ """
119
+ List files and folders in the project's DivBase store.
120
+
121
+ Folders are shown highlighted before files. Use --detailed / -l to also show file sizes and upload dates.
122
+
123
+ Examples:
124
+
125
+ - List all files and folders in the project:
126
+ divbase-cli files ls
127
+
128
+ - List files and folders in the 'vcfs/' folder (trailing '/' shows folder contents):
129
+ divbase-cli files ls vcfs/
130
+
131
+ - List all files and folders whose name starts with 'sample':
132
+ divbase-cli files ls sample
133
+
134
+ - Detailed listing with sizes and dates:
135
+ divbase-cli files ls --detailed
136
+
137
+ - List all files including DivBase query results files (hidden by default):
138
+ divbase-cli files ls --include-results-files
139
+ """
140
+ if show_deleted_files and include_results_files:
141
+ raise typer.BadParameter(
142
+ message="The --show-deleted-files and --include-results-files options cannot be used together."
143
+ )
144
+ if detailed and format_output_as_tsv:
145
+ raise typer.BadParameter(message="The --detailed option and --tsv option cannot be used together.")
146
+
147
+ project_config = resolve_and_authenticate_project(project_name=project)
148
+
149
+ if show_deleted_files:
150
+ files = list_soft_deleted_files_command(
151
+ divbase_base_url=project_config.divbase_url,
152
+ project_name=project_config.name,
153
+ prefix=prefix,
154
+ )
155
+
156
+ if not files:
157
+ print(f"No soft deleted files found for the project '{project_config.name}'.")
158
+ return
159
+
160
+ print(f"Soft deleted files for the project '{project_config.name}':")
161
+ for file_details in files:
162
+ deleted_at = format_datetime_for_cli(dt=file_details.last_modified)
163
+ if file_details.name.endswith("/"):
164
+ print(f"- [bold blue]'{file_details.name}'[/bold blue] (deleted at: '{deleted_at}')")
165
+ else:
166
+ print(f"- '{file_details.name}' (deleted at: '{deleted_at}')")
167
+ print("\nTo restore a soft deleted file, use the 'divbase-cli files restore' command.")
168
+ print("To get more information about one of the soft deleted files, use the 'divbase-cli files info' command.")
169
+ return
170
+
171
+ files, folders = list_files_command(
172
+ divbase_base_url=project_config.divbase_url,
173
+ project_name=project_config.name,
174
+ prefix=prefix,
175
+ include_results_files=include_results_files,
176
+ file_system_view=True,
177
+ )
178
+
179
+ # When listing inside a folder (prefix ends with '/'), strip the search prefix from the output
180
+ # And exclude the possible directory placeholder object itself (the empty S3 key that is an object).
181
+ if prefix and prefix.endswith("/"):
182
+ files = [f.model_copy(update={"name": f.name[len(prefix) :]}) for f in files if f.name != prefix]
183
+ folders = [f[len(prefix) :] for f in folders if f != prefix]
184
+
185
+ if not files and not folders:
186
+ print("No files or folders found in the project's store on DivBase.")
187
+ return
188
+
189
+ if detailed:
190
+ _print_ls_detailed(files=files, folders=folders)
191
+ elif format_output_as_tsv:
192
+ _print_ls_tsv_format(files=files, folders=folders)
193
+ else:
194
+ _print_ls_simple(files=files, folders=folders)
195
+
196
+
197
+ @file_app.command("tree")
198
+ def tree_files(
199
+ prefix: str | None = PREFIX_ARGUMENT,
200
+ include_results_files: bool = INCLUDE_RESULTS_FILES_OPTION,
201
+ project: str | None = PROJECT_NAME_OPTION,
202
+ ):
203
+ """
204
+ Display the project's file store in a tree like manner.
205
+
206
+ Examples:
207
+
208
+ - Show the full tree:
209
+ divbase-cli files tree
210
+
211
+ - Show the tree starting from the 'vcfs/' folder:
212
+ divbase-cli files tree vcfs/
213
+ """
214
+ project_config = resolve_and_authenticate_project(project_name=project)
215
+ files, _ = list_files_command(
216
+ divbase_base_url=project_config.divbase_url,
217
+ project_name=project_config.name,
218
+ prefix=prefix,
219
+ include_results_files=include_results_files,
220
+ file_system_view=False,
221
+ )
222
+ if not files:
223
+ print("No files found in the project's store on DivBase.")
224
+ return
225
+
226
+ _print_file_sys_tree_view(files=files, prefix=prefix)
227
+
228
+
229
+ @file_app.command("info")
230
+ def file_info(
231
+ file_name: str = typer.Argument(
232
+ ..., help="Name of the file to get information about. Must be a file, not a folder (no trailing '/')."
233
+ ),
234
+ format_output_as_tsv: bool = FORMAT_AS_TSV_OPTION,
235
+ project: str | None = PROJECT_NAME_OPTION,
236
+ ):
237
+ """
238
+ Get detailed information about a specific file in the project's DivBase store.
239
+
240
+ This includes all versions of the file and whether the file is currently marked as soft deleted.
241
+
242
+ Examples:
243
+
244
+ - Get information about a specific file in the project:
245
+ divbase-cli files info my_file.vcf.gz
246
+ """
247
+ if file_name.endswith("/"):
248
+ raise typer.BadParameter(
249
+ message="The 'info' command is only for files, not folders. Please provide a file name without a trailing '/'."
250
+ )
251
+
252
+ project_config = resolve_and_authenticate_project(project_name=project)
253
+ file_info = get_file_info_command(
254
+ divbase_base_url=project_config.divbase_url,
255
+ project_name=project_config.name,
256
+ object_name=file_name,
257
+ )
258
+
259
+ if not file_info.versions:
260
+ # API should never return an object with no versions, but just in case
261
+ print("No available versions for this file.")
262
+ return
263
+
264
+ if file_info.is_currently_deleted:
265
+ print(
266
+ "[bold red]Warning: This file is marked as soft deleted.\n[/bold red]"
267
+ + "[italic] To restore a deleted file, use the 'divbase-cli files restore' command.\n"
268
+ + " Or upload the file again using the 'divbase-cli files upload' command.\n[/italic]",
269
+ )
270
+
271
+ table = Table(
272
+ title=f"Available Versions for '[bold]{file_info.object_name}[/bold]'",
273
+ caption="Versions shown are ordered with the latest/current version first/at the top",
274
+ )
275
+ table.add_column("File size", justify="left", style="magenta", no_wrap=False)
276
+ table.add_column("Upload date", justify="left", style="green", no_wrap=False)
277
+ table.add_column("MD5 checksum", justify="left", style="yellow", no_wrap=True)
278
+ table.add_column("Version ID", justify="left", style="cyan", no_wrap=True)
279
+
280
+ for version in file_info.versions:
281
+ upload_date = format_datetime_for_cli(dt=version.last_modified)
282
+ file_size = format_file_size(size_bytes=version.size)
283
+ table.add_row(
284
+ file_size,
285
+ upload_date,
286
+ version.etag,
287
+ version.version_id,
288
+ )
289
+
290
+ if not format_output_as_tsv:
291
+ print(table)
292
+ else:
293
+ print_rich_table_as_tsv(table=table)
294
+
295
+
296
+ @file_app.command("download")
297
+ def download_files(
298
+ files: list[str] = typer.Argument(
299
+ None,
300
+ help="Space separated list of files to download. Use a trailing '/' to download all files inside a folder, e.g. 'vcfs/'.",
301
+ ),
302
+ file_list: Path | None = typer.Option(None, "--file-list", help="Text file with list of files to download."),
303
+ download_dir: str = DOWNLOAD_DIR_OPTION,
304
+ flatten: bool = FLATTEN_DOWNLOADS_OPTION,
305
+ dry_run: bool = DRY_RUN_OPTION,
306
+ disable_verify_checksums: bool = DISABLE_VERIFY_CHECKSUMS_OPTION,
307
+ project_version: str | None = PROJECT_VERSION_OPTION,
308
+ project: str | None = PROJECT_NAME_OPTION,
309
+ ):
310
+ """
311
+ Download files from the project's store on DivBase.
312
+
313
+ Files can be specified as a space-separated list or via --file-list. Use a trailing '/' to download
314
+ everything inside a folder. By default, any folder structure from the project store is recreated
315
+ locally; use --flatten to download all files into a single directory instead.
316
+
317
+ Examples:
318
+
319
+ - Download specific files:
320
+ divbase-cli files download file1.vcf.gz file2.tsv
321
+
322
+ - Download all files inside the 'vcfs/' folder (this includes subfolders and their contents):
323
+ divbase-cli files download vcfs/
324
+
325
+ - Download and flatten all files into one directory:
326
+ divbase-cli files download vcfs/ --flatten --download-dir /path/to/save
327
+
328
+ - Download a specific older version of a file (obtain version ID from 'divbase-cli files info'):
329
+ divbase-cli files download "my_file.vcf.gz:VERSION_ID"
330
+
331
+ - Mix latest and versioned files in one command:
332
+ divbase-cli files download file1.vcf.gz "file2.tsv:VERSION_ID"
333
+ """
334
+ if project_version == "":
335
+ raise typer.BadParameter(
336
+ "It seems like you provided an empty string for --project-version. \n"
337
+ "Please provide a valid project version or omit the flag."
338
+ )
339
+
340
+ project_config = resolve_and_authenticate_project(project_name=project)
341
+ download_dir_path = resolve_download_dir(download_dir=download_dir)
342
+
343
+ raw_files_input = _resolve_file_inputs(files=files, file_list=file_list)
344
+ raw_files_input = _expand_folder_prefixes(
345
+ files=raw_files_input,
346
+ divbase_base_url=project_config.divbase_url,
347
+ project_name=project_config.name,
348
+ )
349
+ if flatten:
350
+ check_no_overlap_on_flattened_downloads(to_download=raw_files_input)
351
+
352
+ download_results = download_files_command(
353
+ divbase_base_url=project_config.divbase_url,
354
+ project_name=project_config.name,
355
+ raw_files_input=raw_files_input,
356
+ download_dir=download_dir_path,
357
+ flatten=flatten,
358
+ verify_checksums=not disable_verify_checksums,
359
+ dry_run=dry_run,
360
+ project_version=project_version,
361
+ )
362
+
363
+ _pretty_print_download_results(download_results=download_results)
364
+
365
+
366
+ @file_app.command("download-all")
367
+ def download_all_files(
368
+ download_dir: str = DOWNLOAD_DIR_OPTION,
369
+ flatten: bool = FLATTEN_DOWNLOADS_OPTION,
370
+ resume: bool = typer.Option(
371
+ False,
372
+ "--resume",
373
+ "-r",
374
+ help="If set, will attempt to resume an interrupted download. Will check which files have already been fully downloaded (by checking if a file with the same name and checksum already exists in the download directory) and skip downloading those files again.",
375
+ ),
376
+ dry_run: bool = DRY_RUN_OPTION,
377
+ disable_verify_checksums: bool = DISABLE_VERIFY_CHECKSUMS_OPTION,
378
+ project_version: str | None = PROJECT_VERSION_OPTION,
379
+ project: str | None = PROJECT_NAME_OPTION,
380
+ ):
381
+ """
382
+ Download all files in the project's store on DivBase.
383
+
384
+ DivBase query results files are excluded. Before the download starts you will be prompted to confirm.
385
+ By default, the folder structure from the project store is recreated locally; use --flatten to
386
+ download all files into a single directory instead.
387
+
388
+ Examples:
389
+
390
+ - Download all files, preserving the folder structure from the project store:
391
+ divbase-cli files download-all --download-dir /path/to/save
392
+
393
+ - Resume an interrupted download (use the same --download-dir as the original run):
394
+ divbase-cli files download-all --resume --download-dir /path/to/save
395
+
396
+ - Download all files into a single flat directory:
397
+ divbase-cli files download-all --flatten --download-dir /path/to/save
398
+
399
+ - Preview what would be downloaded without downloading:
400
+ divbase-cli files download-all --dry-run
401
+ """
402
+ if resume and disable_verify_checksums:
403
+ raise typer.BadParameter(
404
+ message="The --resume and --disable-verify-checksums options cannot be used together, "
405
+ "as checksums are used to determine which files don't need to be downloaded."
406
+ )
407
+ if project_version == "":
408
+ raise typer.BadParameter(
409
+ "It seems like you provided an empty string for --project-version. \n"
410
+ "Please provide a valid project version or omit the flag."
411
+ )
412
+
413
+ project_config = resolve_and_authenticate_project(project_name=project)
414
+ download_dir_path = resolve_download_dir(download_dir=download_dir)
415
+
416
+ all_files: list[ToDownload] = []
417
+ if project_version:
418
+ version_details = get_version_details_command(
419
+ project_name=project_config.name,
420
+ divbase_base_url=project_config.divbase_url,
421
+ version_name=project_version,
422
+ )
423
+ for version_name, file_details in version_details.files.items():
424
+ all_files.append(
425
+ ToDownload(
426
+ s3_key=version_name,
427
+ etag=file_details["etag"],
428
+ size_bytes=file_details["size"],
429
+ version_id=file_details["version_id"],
430
+ )
431
+ )
432
+
433
+ else:
434
+ files, _ = list_files_command(
435
+ divbase_base_url=project_config.divbase_url,
436
+ project_name=project_config.name,
437
+ prefix=None,
438
+ include_results_files=False,
439
+ file_system_view=False, # we want all files in a flat list to download al of them, not a file system view with folders and files
440
+ )
441
+ for file_details in files:
442
+ if file_details.name.endswith("/"):
443
+ # skip the directory placeholder objects, we only want to download actual files
444
+ continue
445
+ all_files.append(
446
+ ToDownload(
447
+ s3_key=file_details.name,
448
+ etag=file_details.etag,
449
+ size_bytes=file_details.size,
450
+ version_id=None, # latest version
451
+ )
452
+ )
453
+
454
+ if not all_files:
455
+ print("No files to download as there are no files in the project's store.")
456
+ return
457
+
458
+ if flatten:
459
+ to_download_names = [file.s3_key for file in all_files]
460
+ check_no_overlap_on_flattened_downloads(to_download=to_download_names)
461
+
462
+ # filter files to download based on those which already exist.
463
+ if resume:
464
+ files_to_download, files_to_overwrite = filter_out_already_downloaded_files(
465
+ all_files=all_files, download_dir=download_dir_path, flatten=flatten
466
+ )
467
+ if files_to_overwrite:
468
+ print(
469
+ "[yellow bold]Warning: The following files already exist in the download directory but have a different checksum. "
470
+ "If you choose to proceed, these files will be overwritten by the download:[/yellow bold]"
471
+ )
472
+ for file in files_to_overwrite:
473
+ print(f"- '{file.s3_key}'")
474
+
475
+ files_to_download.extend(files_to_overwrite)
476
+
477
+ if not files_to_download:
478
+ print("No files left to download, your folder matches the project's store on DivBase, exiting...")
479
+ return
480
+ else:
481
+ files_to_download = all_files
482
+
483
+ total_size_bytes = sum(file.size_bytes for file in files_to_download)
484
+ formatted_total_size = format_file_size(size_bytes=total_size_bytes)
485
+
486
+ print(f"There are '{len(files_to_download)}' files to download with a total size of: {formatted_total_size}.")
487
+
488
+ if not dry_run:
489
+ # (dry run will auto exit in the download_files_command)
490
+ do_download = typer.confirm("Do you want to proceed with the download?")
491
+ if not do_download:
492
+ print("Download cancelled...")
493
+ return
494
+
495
+ if project_version:
496
+ raw_files_input = [f"{file.s3_key}:{file.version_id}" for file in files_to_download]
497
+ else:
498
+ raw_files_input = [file.s3_key for file in files_to_download]
499
+ download_results = download_files_command(
500
+ divbase_base_url=project_config.divbase_url,
501
+ project_name=project_config.name,
502
+ raw_files_input=raw_files_input,
503
+ download_dir=download_dir_path,
504
+ flatten=flatten,
505
+ verify_checksums=not disable_verify_checksums,
506
+ dry_run=dry_run,
507
+ project_version=None, # We already know the version id of each file, so can skip the processing here.
508
+ )
509
+
510
+ _pretty_print_download_results(download_results=download_results)
511
+
512
+
513
+ @file_app.command("stream")
514
+ def stream_file(
515
+ file_name: str = typer.Argument(..., help="Name of the file you want to stream."),
516
+ version_id: str | None = typer.Option(
517
+ default=None,
518
+ help="Specify this if you want to look at an older/specific version of the file. "
519
+ "If not provided, the latest version of the file is used. "
520
+ "To get a file's version ids, use the 'divbase-cli files info [FILE_NAME]' command.",
521
+ ),
522
+ project: str | None = PROJECT_NAME_OPTION,
523
+ ):
524
+ """
525
+ Stream a file's content to standard output.
526
+
527
+ This allows you to pipe the output to other tools like 'less', 'head', 'zcat' and 'bcftools'.
528
+
529
+ Examples:
530
+
531
+ - View a file:
532
+ divbase-cli files stream my_file.tsv | less
533
+
534
+ - View a gzipped file:
535
+ divbase-cli files stream my_file.vcf.gz | zcat | less
536
+
537
+ - Run a bcftools command (the "-" tells bcftools to read from standard input):
538
+ divbase-cli files stream my_file.vcf.gz | bcftools view -h -
539
+ """
540
+ project_config = resolve_and_authenticate_project(project_name=project)
541
+ stream_file_command(
542
+ divbase_base_url=project_config.divbase_url,
543
+ project_name=project_config.name,
544
+ file_name=file_name,
545
+ version_id=version_id,
546
+ )
547
+
548
+
549
+ @file_app.command("upload")
550
+ def upload_files(
551
+ files: list[str] | None = typer.Argument(None, help="Space separated list of files or glob patterns to upload."),
552
+ file_list: Path | None = typer.Option(None, "--file-list", "-l", help="Text file with list of files to upload."),
553
+ remote_dir: str | None = typer.Option(
554
+ None,
555
+ "--to",
556
+ "-t",
557
+ help="Remote folder to upload into, e.g. 'vcfs/batch1/'. Folder does not need to exist before uploading.",
558
+ ),
559
+ skip_existing: bool = typer.Option(
560
+ False,
561
+ "--skip-existing",
562
+ "-s",
563
+ help="If set, will skip already uploaded files, from the files you provided in the command. "
564
+ "Already uploaded files are determined by checking if a file with the same name and MD5 checksum already exists in the project's store on DivBase. ",
565
+ ),
566
+ recursive: bool = typer.Option(
567
+ False,
568
+ "--recursive",
569
+ "-r",
570
+ "-R",
571
+ help="If set, recursively include subdirectories contents when uploading (i.e. '**' is expanded). "
572
+ "Without this flag, patterns only match files in the specified directory. "
573
+ "Put your argument in quotes to prevent shell expansion of the glob before it gets to the CLI, e.g. files upload 'data/**/*.vcf.gz' ",
574
+ ),
575
+ dry_run: bool = typer.Option(
576
+ False, "--dry-run", "-n", help="If set, will show what files would be uploaded, but not actually upload them."
577
+ ),
578
+ disable_safe_mode: Annotated[
579
+ bool,
580
+ typer.Option(
581
+ "--disable-safe-mode",
582
+ help="Turn off safe mode which is on by default. Safe mode adds 2 extra bits of security by first calculating the MD5 checksum of each file that you're about to upload:"
583
+ "(1) Checks if any of the files you're about to upload already exist (by comparing name and checksum) and if so stops the upload process."
584
+ "(2) Sends the file's checksum when the file is uploaded so the server can verify the upload was successful (by calculating and comparing the checksums)."
585
+ "It is recommended to leave safe mode enabled unless you have a specific reason to disable it.",
586
+ ),
587
+ ] = False,
588
+ project: str | None = PROJECT_NAME_OPTION,
589
+ ):
590
+ """
591
+ Upload files to your project's store on DivBase.
592
+
593
+ By default only the file name is used as the destination key (directory paths are stripped).
594
+ Use '--to' to place files inside a remote folder. Use '--recursive' with a '**' glob to
595
+ preserve subdirectory structure relative to the glob root.
596
+
597
+ Examples:
598
+
599
+ - Upload multiple files:
600
+ divbase-cli files upload file1.vcf.gz file2.tsv
601
+
602
+ - Upload all .vcf.gz files in the current directory into a remote folder:
603
+ divbase-cli files upload "*.vcf.gz" --to experiment1/
604
+
605
+ - Upload all files in a directory to the root of the project store:
606
+ divbase-cli files upload "/path/to/data/*"
607
+
608
+ - Upload recursively, preserving subdirectory structure (wrap glob in quotes to prevent shell expansion):
609
+ divbase-cli files upload --recursive "/path/to/data/**"
610
+
611
+ - Upload recursively into a remote folder:
612
+ divbase-cli files upload --recursive "/path/to/data/**" --to experiment1/
613
+
614
+ - Upload from a text file list (one file path per line):
615
+ divbase-cli files upload --file-list files_to_upload.txt --to experiment1/
616
+ """
617
+ if bool(files) + bool(file_list) > 1:
618
+ raise typer.BadParameter("You cannot specify files as arguments and provide a --file-list.")
619
+ if skip_existing and disable_safe_mode:
620
+ raise typer.BadParameter(
621
+ "The --skip-existing and --disable-safe-mode options cannot be used together.\n"
622
+ "Safe mode calculates file checksums, "
623
+ "and these checksums are needed for --skip-existing to know what files to skip uploading."
624
+ )
625
+ project_config = resolve_and_authenticate_project(project_name=project)
626
+ to_upload = _resolve_user_upload_inputs(
627
+ files=files,
628
+ file_list=file_list,
629
+ recursive=recursive,
630
+ remote_dir=remote_dir,
631
+ )
632
+ _check_for_duplicate_object_keys(to_upload)
633
+ _check_for_unsupported_files(to_upload)
634
+
635
+ uploaded_results = upload_files_command(
636
+ project_name=project_config.name,
637
+ divbase_base_url=project_config.divbase_url,
638
+ all_files=to_upload,
639
+ safe_mode=not disable_safe_mode,
640
+ skip_existing=skip_existing,
641
+ dry_run=dry_run,
642
+ )
643
+
644
+ if uploaded_results.skipped:
645
+ print("[yellow bold]\nThe following files were skipped: [/yellow bold]")
646
+ for file in uploaded_results.skipped:
647
+ print(f"[yellow]- '{file.object_name}' reason: {file.reason}[/yellow]")
648
+
649
+ if uploaded_results.successful:
650
+ print("[green bold]\nThe following files were successfully uploaded: [/green bold]")
651
+ for file in uploaded_results.successful:
652
+ print(f"[green]- '{file.object_name}' created from file at: '{file.file_path.resolve()}'[/green]")
653
+
654
+ if uploaded_results.failed:
655
+ print("[red bold]\nERROR: Failed to upload the following files:[/red bold]")
656
+ for failed in uploaded_results.failed:
657
+ print(f"[red]- '{failed.object_name}': Exception: '{failed.exception}'[/red]")
658
+ raise typer.Exit(1)
659
+ elif not uploaded_results.successful:
660
+ print("\nNo files were uploaded.")
661
+ else:
662
+ print("\n[green bold]All files uploaded successfully![/green bold]")
663
+
664
+
665
+ @file_app.command("mkdir")
666
+ def make_directory(
667
+ directories: list[str] = typer.Argument(
668
+ ..., help="Space separated list of directories to create. A trailing '/' is added automatically if omitted."
669
+ ),
670
+ project: str | None = PROJECT_NAME_OPTION,
671
+ ):
672
+ """
673
+ Create one or more directories in your project store.
674
+
675
+ Note: directories are created automatically when uploading files with '--to', so you only need
676
+ this command if you want to create the folder structure ahead of time.
677
+
678
+ Examples:
679
+
680
+ - Create a single directory:
681
+ divbase-cli files mkdir vcfs
682
+
683
+ - Create a nested directory structure:
684
+ divbase-cli files mkdir vcfs/batch1/metadata
685
+
686
+ - Create multiple directories at once:
687
+ divbase-cli files mkdir vcfs metadata results
688
+ """
689
+ project_config = resolve_and_authenticate_project(project_name=project)
690
+ cleaned_dir_names = _sanitize_directory_names(directories)
691
+
692
+ dirs_created = make_directories_command(
693
+ directories=cleaned_dir_names,
694
+ divbase_base_url=project_config.divbase_url,
695
+ project_name=project_config.name,
696
+ )
697
+ if dirs_created.created:
698
+ print("Successfully created the following directories:")
699
+ for dir in dirs_created.created:
700
+ print(f"[bold blue]'{dir}'[/bold blue]")
701
+
702
+ if dirs_created.failed:
703
+ print("[red bold]Error: Failed to create the following directories:[/red bold]")
704
+ for dir in dirs_created.failed:
705
+ print(f"[red]'{dir}'[/red]")
706
+ print("This could be due to invalid characters in the directory name or an unexpected server error.\n")
707
+ raise typer.Exit(1)
708
+
709
+
710
+ @file_app.command("rmdir")
711
+ def remove_directory(
712
+ directories: list[str] = typer.Argument(
713
+ ...,
714
+ help="Space separated list of directories to remove. The directory must be empty (remove files first with 'divbase-cli files rm').",
715
+ ),
716
+ project: str | None = PROJECT_NAME_OPTION,
717
+ ):
718
+ """
719
+ Remove one or more empty directories from your project store.
720
+
721
+ All files inside the directory must be deleted first using 'divbase-cli files rm'.
722
+ If a directory does not exist, it is treated as a successful deletion.
723
+
724
+ Examples:
725
+
726
+ - Remove a single directory:
727
+ divbase-cli files rmdir vcfs/
728
+
729
+ - Remove multiple directories at once:
730
+ divbase-cli files rmdir vcfs/ metadata/
731
+ """
732
+ project_config = resolve_and_authenticate_project(project_name=project)
733
+ directories = _sanitize_directory_names(directories)
734
+
735
+ for dir in directories:
736
+ files, _ = list_files_command(
737
+ divbase_base_url=project_config.divbase_url,
738
+ project_name=project_config.name,
739
+ prefix=dir,
740
+ include_results_files=True,
741
+ file_system_view=False,
742
+ )
743
+ non_placeholder_files = [f for f in files if f.name != dir]
744
+ if non_placeholder_files:
745
+ raise NotEmptyDirectoryError(
746
+ f"The directory '{dir}' is not empty.\n"
747
+ "You must first remove all files and/or subdirectories inside the directory using:\n"
748
+ "'divbase-cli files rm' and 'divbase-cli files rmdir'"
749
+ )
750
+
751
+ # NOTE: as dirs are just empty files which end with "/", we can just do a regular soft delete on them.
752
+ deleted_dirs = soft_delete_objects_command(
753
+ divbase_base_url=project_config.divbase_url,
754
+ project_name=project_config.name,
755
+ all_files=directories,
756
+ )
757
+
758
+ if deleted_dirs:
759
+ print("Deleted the following directories:")
760
+ for dir in deleted_dirs:
761
+ print(f"[bold blue]'{dir}'[/bold blue]")
762
+
763
+
764
+ @file_app.command("rm")
765
+ def remove_files(
766
+ files: list[str] | None = typer.Argument(
767
+ None, help="Space separated list of files/objects in the project's store on DivBase to delete."
768
+ ),
769
+ file_list: Path | None = typer.Option(None, "--file-list", help="Text file with list of files to delete."),
770
+ dry_run: bool = typer.Option(
771
+ False, "--dry-run", help="If set, will not actually delete the files, just print what would be deleted."
772
+ ),
773
+ project: str | None = PROJECT_NAME_OPTION,
774
+ ):
775
+ """
776
+ Soft delete files from the project's store on DivBase
777
+
778
+ Note that deleting a non existent file will be treated as a successful deletion.
779
+
780
+ Examples:
781
+ - Delete specific files:
782
+ divbase-cli files rm file1.vcf.gz file2.tsv
783
+
784
+ - Delete files from a text file list (one file name per line):
785
+ divbase-cli files rm --file-list files_to_delete.txt
786
+
787
+ - Run a dry run to see what files would be deleted without actually deleting them:
788
+ divbase-cli files rm file1.vcf.gz file2.tsv --dry-run
789
+ """
790
+ project_config = resolve_and_authenticate_project(project_name=project)
791
+ all_files = _resolve_file_inputs(files=files, file_list=file_list)
792
+
793
+ if dry_run:
794
+ print("Dry run mode enabled. The following files would have been deleted:")
795
+ for file in all_files:
796
+ print(f"- '{file}'")
797
+ return
798
+
799
+ deleted_files = soft_delete_objects_command(
800
+ divbase_base_url=project_config.divbase_url,
801
+ project_name=project_config.name,
802
+ all_files=all_files,
803
+ )
804
+
805
+ if deleted_files:
806
+ print("Deleted files:")
807
+ for file in deleted_files:
808
+ print(f"- '{file}'")
809
+ else:
810
+ print("No files were deleted.")
811
+
812
+
813
+ @file_app.command("restore")
814
+ def restore_soft_deleted_files(
815
+ files: list[str] | None = typer.Argument(
816
+ None, help="Space separated list of files/objects in the project's store on DivBase to restore."
817
+ ),
818
+ file_list: Path | None = typer.Option(None, "--file-list", help="Text file with list of files to restore."),
819
+ project: str | None = PROJECT_NAME_OPTION,
820
+ ):
821
+ """
822
+ Restore soft deleted files from the project's store on DivBase
823
+
824
+ Attempts to restore a file that is not soft deleted will be considered successful and the file will remain live.
825
+
826
+ Examples:
827
+ - Restore specific files:
828
+ divbase-cli files restore file1.vcf.gz file2.tsv
829
+
830
+ - Restore files from a text file list (one file name per line):
831
+ divbase-cli files restore --file-list files_to_restore.txt
832
+ """
833
+ project_config = resolve_and_authenticate_project(project_name=project)
834
+ all_files = _resolve_file_inputs(files=files, file_list=file_list)
835
+
836
+ restored_objects_response = restore_objects_command(
837
+ divbase_base_url=project_config.divbase_url,
838
+ project_name=project_config.name,
839
+ all_files=all_files,
840
+ )
841
+
842
+ if restored_objects_response.restored:
843
+ print("Restored files:")
844
+ for file in restored_objects_response.restored:
845
+ print(f"- '{file}'")
846
+
847
+ if restored_objects_response.not_restored:
848
+ print("[bold red]Error: Some files could not be restored:[/bold red]")
849
+ for file in restored_objects_response.not_restored:
850
+ print(f"[red]- '{file}'[/red]")
851
+
852
+ print(
853
+ "Possible reasons for failed restores:\n"
854
+ "1. The object does not exist in the bucket (e.g., a typo in the name).\n"
855
+ "2. The object was hard-deleted and is unrecoverable.\n"
856
+ "3. An unexpected server error occurred during the restore attempt."
857
+ )
858
+ raise typer.Exit(1)
859
+
860
+
861
+ def _print_file_sys_tree_view(files: list[ObjectDetails], prefix: str | None) -> None:
862
+ """
863
+ Print user file system in tree view using Rich Tree."""
864
+ if prefix and prefix.endswith("/"):
865
+ root_label = prefix.rstrip("/")
866
+ tree_label = f"[bold blue]{root_label}[/bold blue]"
867
+ else:
868
+ root_label = "."
869
+ tree_label = root_label
870
+
871
+ tree = Tree(label=tree_label)
872
+
873
+ nodes: dict[str, Tree] = {}
874
+ names = []
875
+ for file in files:
876
+ if prefix and prefix.endswith("/") and file.name.startswith(prefix):
877
+ names.append(file.name[len(prefix) :])
878
+ else:
879
+ names.append(file.name)
880
+
881
+ for name in sorted(names):
882
+ parts = name.split("/")
883
+ parent = tree
884
+ path = ""
885
+ for part in parts[:-1]:
886
+ path = path + part + "/"
887
+ if path not in nodes:
888
+ nodes[path] = parent.add(f"[bold blue]{part}/[/bold blue]")
889
+ parent = nodes[path]
890
+ if parts[-1]:
891
+ parent.add(parts[-1])
892
+ Console().print(tree)
893
+
894
+
895
+ def _print_ls_simple(files: list[ObjectDetails], folders: list[str]) -> None:
896
+ """Compact folder-aware listing: bold blue folders first, then plain filenames."""
897
+ console = Console()
898
+ for folder in folders:
899
+ console.print(f"[bold blue]{markup_escape(folder)}[/bold blue]")
900
+ for file_details in files:
901
+ console.print(markup_escape(file_details.name))
902
+
903
+
904
+ def _print_ls_tsv_format(files: list[ObjectDetails], folders: list[str]) -> None:
905
+ """Prints the files and folders in a tab-separated format - for programmatic use"""
906
+ for folder in folders:
907
+ print(f"{markup_escape(folder)}\t-\t-")
908
+ for f in files:
909
+ last_modified = format_datetime_for_cli(dt=f.last_modified)
910
+ print(f"{markup_escape(f.name)}\t{format_file_size(f.size)}\t{last_modified}")
911
+
912
+
913
+ def _print_ls_detailed(files: list[ObjectDetails], folders: list[str]) -> None:
914
+ """Unix ls -l style: one entry per line with name, size and date"""
915
+ console = Console()
916
+ for folder in folders:
917
+ console.print(f"[bold blue]{markup_escape(folder)}[/bold blue]")
918
+ for f in files:
919
+ size_str = format_file_size(f.size).rjust(10)
920
+ last_modified = format_datetime_for_cli(dt=f.last_modified)
921
+ console.print(f"{markup_escape(f.name)} [magenta]{size_str}[/magenta] [green]{last_modified}[/green]")
922
+
923
+
924
+ def _resolve_file_inputs(files: list[str] | None, file_list: Path | None) -> list[str]:
925
+ """Helper function to resolve file inputs from command line arguments."""
926
+ if bool(files) + bool(file_list) != 1:
927
+ raise typer.BadParameter("Please specify files as arguments or provide a --file-list.")
928
+
929
+ all_files = set()
930
+ if files:
931
+ all_files.update(files)
932
+ if file_list:
933
+ lines = file_list.read_text().splitlines()
934
+ for line in lines:
935
+ if line.strip():
936
+ all_files.add(line.strip())
937
+
938
+ if not all_files:
939
+ raise NoFilesSpecifiedError(NO_FILES_SPECIFIED_MSG)
940
+ return list(all_files)
941
+
942
+
943
+ def _resolve_user_upload_inputs(
944
+ files: list[str] | None,
945
+ file_list: Path | None,
946
+ recursive: bool,
947
+ remote_dir: str | None,
948
+ ) -> list[ToUpload]:
949
+ """
950
+ Take user CLI input arguments for files upload cmd and create a list of ToUpload objects.
951
+
952
+ Handles the multiple ways a user can specify files for upload.
953
+ """
954
+ to_upload: list[ToUpload] = []
955
+ missing_patterns: list[str] = []
956
+ seen: set[Path] = set()
957
+
958
+ if remote_dir:
959
+ remote_dir = remote_dir[1:] if remote_dir.startswith("/") else remote_dir
960
+ remote_dir = remote_dir if remote_dir.endswith("/") else remote_dir + "/"
961
+ if any(char in remote_dir for char in UNSUPPORTED_CHARACTERS_IN_FILENAMES):
962
+ raise UnsupportedCharactersError(
963
+ "The --to destination path contains unsupported characters.\n"
964
+ f"Unsupported characters: {UNSUPPORTED_CHARACTERS_DISPLAY}"
965
+ )
966
+
967
+ if recursive and files and not any("*" in p for p in files) and any(len(Path(p).parts) > 1 for p in files):
968
+ raise ShellExpandedGlobError(
969
+ "--recursive was passed but all arguments provided are file paths.\n"
970
+ "Your shell likely expanded the glob before passing it to this command.\n"
971
+ "To solve the problem, wrap the pattern(s) in quotes to prevent shell expansion, e.g.:\n"
972
+ " 'divbase-cli files upload 'my_data/**/*.vcf.gz' --recursive' AND NOT \n"
973
+ " 'divbase-cli files upload my_data/**/*.vcf.gz --recursive'"
974
+ )
975
+
976
+ if files:
977
+ for pattern in files:
978
+ # expands something like ~/Downloads/ to /home/user/Downloads/
979
+ expanded_pattern = str(Path(pattern).expanduser())
980
+ matches = [Path(p) for p in glob(expanded_pattern, recursive=recursive) if Path(p).is_file()]
981
+ if not matches:
982
+ if Path(expanded_pattern).is_dir():
983
+ continue
984
+ missing_patterns.append(pattern)
985
+ continue
986
+ for file in matches:
987
+ if file in seen:
988
+ continue
989
+ seen.add(file)
990
+ if recursive and "**" in pattern:
991
+ # this handles case where ** is used inside a dir name e.g. data/some**thing/ etc...
992
+ before_doublestar = expanded_pattern.split("**")[0]
993
+ if not before_doublestar:
994
+ root = Path(".")
995
+ elif before_doublestar.endswith("/"):
996
+ root = Path(before_doublestar)
997
+ else:
998
+ root = Path(before_doublestar).parent
999
+ key = str(file.relative_to(root)).replace("\\", "/")
1000
+ else:
1001
+ key = file.name
1002
+
1003
+ destination_key = (remote_dir or "") + key
1004
+ to_upload.append(ToUpload(file_path=file, destination_key=destination_key))
1005
+
1006
+ if file_list:
1007
+ missing_files: list[Path] = []
1008
+ lines = file_list.read_text().splitlines()
1009
+ for line in lines:
1010
+ if not line.strip():
1011
+ continue
1012
+ path = Path(line.strip())
1013
+ if not path.is_file():
1014
+ missing_files.append(path)
1015
+ continue
1016
+ if path not in seen:
1017
+ seen.add(path)
1018
+ to_upload.append(ToUpload(file_path=path, destination_key=(remote_dir or "") + path.name))
1019
+
1020
+ if missing_files:
1021
+ missing_files_str = "\n".join(f"- '{path}'" for path in missing_files)
1022
+ raise NoFilesSpecifiedError(
1023
+ f"The following file paths provided in your --file-list were not found:\n{missing_files_str}"
1024
+ )
1025
+
1026
+ if missing_patterns:
1027
+ missing_patterns_str = "\n".join(f"- '{pattern}'" for pattern in missing_patterns)
1028
+ raise NoFilesSpecifiedError(f"{NO_UPLOAD_MATCHES_MSG}\n{missing_patterns_str}")
1029
+
1030
+ if not to_upload:
1031
+ raise NoFilesSpecifiedError(NO_FILES_SPECIFIED_MSG)
1032
+
1033
+ return to_upload
1034
+
1035
+
1036
+ def _check_for_duplicate_object_keys(to_upload: list[ToUpload]) -> None:
1037
+ """Check that no two files resolve to the same S3 object key — they would silently overwrite each other."""
1038
+ key_to_paths: dict[str, list[Path]] = {}
1039
+ for s in to_upload:
1040
+ key_to_paths.setdefault(s.destination_key, []).append(s.file_path)
1041
+
1042
+ duplicates = {key: paths for key, paths in key_to_paths.items() if len(paths) > 1}
1043
+ if duplicates:
1044
+ duplicates_str = "\n".join(
1045
+ f"'{key}':\n" + "\n".join(f"- {p.resolve()}" for p in paths) for key, paths in duplicates.items()
1046
+ )
1047
+ raise DuplicateFileNamesError(
1048
+ "The following destination names appear more than once in the upload list.\n"
1049
+ "Multiple local files would overwrite each other at the same key:\n"
1050
+ f"{duplicates_str}\n"
1051
+ "Ensure each file maps to a unique destination file, or upload them separately and use the '--to' flag to place the files in separate folders."
1052
+ )
1053
+
1054
+
1055
+ def _expand_folder_prefixes(
1056
+ files: list[str],
1057
+ divbase_base_url: str,
1058
+ project_name: str,
1059
+ ) -> list[str]:
1060
+ """
1061
+ Given a list of user provided file args, expand any args that are for folders, i.e. they end with a trailing '/'.
1062
+ SO updates the list of files to (e.g. download) to include all files inside the folder(s) and returns the updated list.
1063
+
1064
+ Non-folder arguments are passed through unchanged. Raises NoFilesSpecifiedError if a prefix has no files.
1065
+ """
1066
+ all_files: set[str] = set()
1067
+ for arg in files:
1068
+ if not arg.endswith("/"):
1069
+ all_files.add(arg)
1070
+ continue
1071
+
1072
+ full_s3_file_paths, _ = list_files_command(
1073
+ divbase_base_url=divbase_base_url,
1074
+ project_name=project_name,
1075
+ prefix=arg,
1076
+ include_results_files=True,
1077
+ file_system_view=False,
1078
+ )
1079
+ # strip off any subfolders
1080
+ real_files = [f.name for f in full_s3_file_paths if not f.name.endswith("/")]
1081
+ if not real_files:
1082
+ raise NoFilesSpecifiedError(f"No files found inside the folder: '{arg}' that you provided.")
1083
+
1084
+ all_files.update(real_files)
1085
+
1086
+ return list(all_files)
1087
+
1088
+
1089
+ def check_no_overlap_on_flattened_downloads(to_download: list[str]) -> None:
1090
+ """
1091
+ When downloading files with --flatten option, double check that no two files will resolve to same local file path.
1092
+ If they do, then raise error.
1093
+
1094
+ Could happen if for example divbase-cli files download-all --flatten:
1095
+ - file1.txt
1096
+ - subdir/file1.txt
1097
+ or
1098
+ - file1.txt
1099
+ - file1.txt:specific-version-id
1100
+ """
1101
+ name_to_paths: dict[str, list[str]] = defaultdict(list)
1102
+ for s3_path in to_download:
1103
+ # Strip possible version ID suffix (e.g., "file.txt:VERSION_ID")
1104
+ path_without_version = s3_path.split(":")[0]
1105
+ download_name = Path(path_without_version).name # what it would be download as if --flatten is used
1106
+ name_to_paths[download_name].append(s3_path)
1107
+
1108
+ duplicates = {name: paths for name, paths in name_to_paths.items() if len(paths) > 1}
1109
+ if duplicates:
1110
+ duplicates_str = "\n".join(
1111
+ f"'{name}':\n" + "\n".join(f"- '{p}'" for p in paths) for name, paths in duplicates.items()
1112
+ )
1113
+ raise DuplicateFileNamesError(
1114
+ "The following files would overwrite each other when downloaded with the --flatten option.\n"
1115
+ "Multiple files would resolve to the same local file path:\n"
1116
+ f"{duplicates_str}\n"
1117
+ "You must either download without the --flatten option or only download a subset of the files to avoid this error."
1118
+ )
1119
+
1120
+
1121
+ def _check_for_unsupported_files(all_files: list[ToUpload]) -> None:
1122
+ """
1123
+ Helper fn to check if any of the files to be uploaded are not supported by DivBase.
1124
+ Raises error if so.
1125
+
1126
+ This can be to prevent users from:
1127
+ 1. Accidentally uploading unsupported files.
1128
+ 2. Uploading files that have characters that we reserve for actions like filtering/querying on DivBase.
1129
+ (e.g. the syntax "[file_name]:[version_id]" can be used to download specific file versions).
1130
+
1131
+ This is not a security feature, just for UX purposes.
1132
+ """
1133
+ unsupported_file_types, unsupported_chars = [], []
1134
+ for file in all_files:
1135
+ if not any(file.file_name.endswith(supported) for supported in SUPPORTED_DIVBASE_FILE_TYPES):
1136
+ unsupported_file_types.append(file.file_name)
1137
+
1138
+ if any(char in file.destination_key for char in UNSUPPORTED_CHARACTERS_IN_FILENAMES):
1139
+ unsupported_chars.append(file.file_name)
1140
+
1141
+ if unsupported_file_types:
1142
+ print(
1143
+ f"[red bold]Error: The following files' types are not supported by DivBase and therefore cannot be uploaded: [/red bold] \n"
1144
+ f"[red]{'\n'.join(str(file) for file in unsupported_file_types)}\n\n[/red]"
1145
+ f"DivBase currently supports the following file types: {SUPPORTED_DIVBASE_FILE_TYPES_DISPLAY}\n"
1146
+ "Note that while you can upload '.tbi' and '.csi' files they are not used by DivBase in queries, we create our own index files instead. \n"
1147
+ "If you want us to support another file type, please let us know.",
1148
+ )
1149
+
1150
+ if unsupported_chars:
1151
+ print(
1152
+ f"[red bold]Error: The following file(s) cannot be uploaded because their name or destination path contains unsupported characters:[/red bold]\n"
1153
+ f"[red]{'\n'.join(str(file) for file in unsupported_chars)}\n\n[/red]"
1154
+ f"Unsupported characters: [red]{UNSUPPORTED_CHARACTERS_DISPLAY}[/red]\n"
1155
+ "Please rename the file or choose a different --to destination and try again.",
1156
+ )
1157
+
1158
+ if unsupported_file_types or unsupported_chars:
1159
+ raise typer.Exit(1)
1160
+
1161
+
1162
+ def _sanitize_directory_names(directories: list[str]) -> list[str]:
1163
+ cleaned_dir_names = []
1164
+ for directory in directories:
1165
+ if any(char in directory for char in UNSUPPORTED_CHARACTERS_IN_FILENAMES):
1166
+ raise UnsupportedCharactersError(
1167
+ f"The directory name '{directory}' contains unsupported characters.\n"
1168
+ f"Unsupported characters: {UNSUPPORTED_CHARACTERS_DISPLAY}"
1169
+ )
1170
+
1171
+ directory = directory if directory.endswith("/") else directory + "/"
1172
+ directory = directory[1:] if directory.startswith("/") else directory
1173
+ cleaned_dir_names.append(directory)
1174
+ return cleaned_dir_names
1175
+
1176
+
1177
+ def _pretty_print_download_results(download_results: DownloadOutcome) -> None:
1178
+ """Helper fn used by download and download all commands to print the results of the download in a nice format."""
1179
+ if download_results.successful:
1180
+ print("\n[green bold]Successfully downloaded the following files:[/green bold]")
1181
+ for success in download_results.successful:
1182
+ print(f"- '{success.object_name}' downloaded to: '{success.file_path.resolve()}'")
1183
+
1184
+ if download_results.failed:
1185
+ print("\n[red bold]Error: Failed to download the following files:[/red bold]")
1186
+ for failed in download_results.failed:
1187
+ print(f"[red]- '{failed.object_name}': [/red] Exception: '{failed.exception}'")
1188
+ raise typer.Exit(1)