divbase-cli 0.1.0.dev2__tar.gz → 0.1.0.dev5__tar.gz

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.
Files changed (35) hide show
  1. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/.gitignore +9 -1
  2. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/PKG-INFO +3 -4
  3. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/pyproject.toml +9 -4
  4. divbase_cli-0.1.0.dev5/src/divbase_cli/__init__.py +1 -0
  5. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/cli_commands/auth_cli.py +16 -10
  6. divbase_cli-0.1.0.dev5/src/divbase_cli/cli_commands/dimensions_cli.py +439 -0
  7. divbase_cli-0.1.0.dev5/src/divbase_cli/cli_commands/file_cli.py +632 -0
  8. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/cli_commands/query_cli.py +14 -9
  9. divbase_cli-0.1.0.dev5/src/divbase_cli/cli_commands/shared_args_options.py +23 -0
  10. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/cli_commands/task_history_cli.py +3 -8
  11. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/cli_commands/user_config_cli.py +14 -44
  12. divbase_cli-0.1.0.dev5/src/divbase_cli/cli_commands/version_cli.py +214 -0
  13. divbase_cli-0.1.0.dev5/src/divbase_cli/cli_config.py +57 -0
  14. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/cli_exceptions.py +37 -22
  15. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/config_resolver.py +10 -10
  16. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/divbase_cli.py +1 -1
  17. divbase_cli-0.1.0.dev5/src/divbase_cli/retries.py +34 -0
  18. divbase_cli-0.1.0.dev5/src/divbase_cli/services/__init__.py +0 -0
  19. divbase_cli-0.1.0.dev5/src/divbase_cli/services/announcements.py +46 -0
  20. divbase_cli-0.1.0.dev5/src/divbase_cli/services/pre_signed_urls.py +456 -0
  21. divbase_cli-0.1.0.dev5/src/divbase_cli/services/project_versions.py +103 -0
  22. divbase_cli-0.1.0.dev5/src/divbase_cli/services/s3_files.py +442 -0
  23. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/user_auth.py +104 -46
  24. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/user_config.py +20 -9
  25. divbase_cli-0.1.0.dev5/src/divbase_cli/utils.py +28 -0
  26. divbase_cli-0.1.0.dev2/src/divbase_cli/__init__.py +0 -1
  27. divbase_cli-0.1.0.dev2/src/divbase_cli/cli_commands/dimensions_cli.py +0 -143
  28. divbase_cli-0.1.0.dev2/src/divbase_cli/cli_commands/file_cli.py +0 -245
  29. divbase_cli-0.1.0.dev2/src/divbase_cli/cli_commands/version_cli.py +0 -153
  30. divbase_cli-0.1.0.dev2/src/divbase_cli/cli_config.py +0 -39
  31. divbase_cli-0.1.0.dev2/src/divbase_cli/pre_signed_urls.py +0 -169
  32. divbase_cli-0.1.0.dev2/src/divbase_cli/services.py +0 -219
  33. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/README.md +0 -0
  34. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/cli_commands/__init__.py +0 -0
  35. {divbase_cli-0.1.0.dev2 → divbase_cli-0.1.0.dev5}/src/divbase_cli/display_task_history.py +0 -0
@@ -13,13 +13,15 @@ __pycache__/
13
13
 
14
14
  # project specific files
15
15
  /sample_metadata.tsv
16
- sample_metadata_*.tsv
16
+ /sample_metadata_*.tsv
17
17
  *.vcf
18
18
  *.vcf.gz
19
19
  *.vcf.gz.csi
20
+ *.vcf.gz.tbi
20
21
  !tests/fixtures/*.vcf.gz
21
22
  tests/fixtures/temp*
22
23
  tests/fixtures/merged*
24
+ divbase_metadata_template*.tsv
23
25
 
24
26
  # query job config files
25
27
  bcftools_divbase_job_config.json
@@ -28,11 +30,17 @@ bcftools_divbase_job_config.json
28
30
  vcf_dimensions.tsv
29
31
  mock*.tsv
30
32
  task_records*.json
33
+ split_scaffold_files.txt
34
+ scripts/benchmarking/*.yaml
35
+ scripts/benchmarking/results
31
36
 
32
37
  #MacOS artifacts
33
38
  .DS_Store
34
39
 
35
40
  # mkdocs build cache
36
41
  .cache/
42
+ # mkdocs auto generated files
43
+ docs/cli/_auto_generated/*.md
44
+
37
45
  # pypi
38
46
  dist/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: divbase-cli
3
- Version: 0.1.0.dev2
3
+ Version: 0.1.0.dev5
4
4
  Summary: Command Line Interface for Divbase
5
5
  Project-URL: Homepage, https://divbase.scilifelab.se
6
6
  Project-URL: Documentation, https://scilifelabdatacentre.github.io/divbase
@@ -18,9 +18,8 @@ Classifier: Programming Language :: Python :: 3.12
18
18
  Classifier: Programming Language :: Python :: 3.13
19
19
  Classifier: Programming Language :: Python :: 3.14
20
20
  Requires-Python: >=3.12
21
- Requires-Dist: divbase-lib==0.1.0.dev2
22
- Requires-Dist: httpx<2,>=0.28.1
23
- Requires-Dist: typer<1,>=0.21.1
21
+ Requires-Dist: divbase-lib==0.1.0.dev5
22
+ Requires-Dist: typer==0.24.1
24
23
  Description-Content-Type: text/markdown
25
24
 
26
25
  # divbase-cli
@@ -8,9 +8,8 @@ authors = [
8
8
  ]
9
9
  requires-python = ">=3.12"
10
10
  dependencies = [
11
- "divbase-lib==0.1.0.dev2",
12
- "typer>=0.21.1,<1",
13
- "httpx>=0.28.1,<2",
11
+ "typer==0.24.1",
12
+ "divbase-lib==0.1.0.dev5"
14
13
  ]
15
14
  dynamic = ["version"]
16
15
 
@@ -44,4 +43,10 @@ build-backend = "hatchling.build"
44
43
  path = "src/divbase_cli/__init__.py"
45
44
 
46
45
  [tool.uv.sources]
47
- divbase-lib = { workspace = true }
46
+ divbase-lib = { workspace = true }
47
+
48
+ [tool.ruff]
49
+ extend = "../../ruff.toml"
50
+
51
+ [tool.ruff.lint.flake8-tidy-imports.banned-api]
52
+ "divbase_api" = { msg = "divbase-cli cannot use code from divbase-api. Move shared code to divbase-lib." }
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0.dev5"
@@ -2,16 +2,16 @@
2
2
  CLI subcommand for managing user auth with DivBase server.
3
3
  """
4
4
 
5
+ import logging
5
6
  from datetime import datetime
6
- from pathlib import Path
7
7
 
8
8
  import typer
9
9
  from pydantic import SecretStr
10
10
  from typing_extensions import Annotated
11
11
 
12
- from divbase_cli.cli_commands.user_config_cli import CONFIG_FILE_OPTION
13
12
  from divbase_cli.cli_config import cli_settings
14
- from divbase_cli.cli_exceptions import AuthenticationError
13
+ from divbase_cli.cli_exceptions import AuthenticationError, DivBaseAPIConnectionError, DivBaseAPIError
14
+ from divbase_cli.services.announcements import get_and_display_announcements
15
15
  from divbase_cli.user_auth import (
16
16
  check_existing_session,
17
17
  login_to_divbase,
@@ -20,6 +20,8 @@ from divbase_cli.user_auth import (
20
20
  )
21
21
  from divbase_cli.user_config import load_user_config
22
22
 
23
+ logger = logging.getLogger(__name__)
24
+
23
25
  auth_app = typer.Typer(
24
26
  no_args_is_help=True, help="Login/logout of DivBase server. To register, visit https://divbase.scilifelab.se/."
25
27
  )
@@ -30,7 +32,6 @@ def login(
30
32
  email: str,
31
33
  password: Annotated[str, typer.Option(prompt=True, hide_input=True)],
32
34
  divbase_url: str = typer.Option(cli_settings.DIVBASE_API_URL, help="DivBase server URL to connect to."),
33
- config_file: Path = CONFIG_FILE_OPTION,
34
35
  force: bool = typer.Option(False, "--force", "-f", help="Force login again even if already logged in"),
35
36
  ):
36
37
  """
@@ -43,7 +44,7 @@ def login(
43
44
  secret_password = SecretStr(password)
44
45
  del password # avoid user passwords showing up in error messages etc...
45
46
 
46
- config = load_user_config(config_file)
47
+ config = load_user_config()
47
48
 
48
49
  if not force:
49
50
  session_expires_at = check_existing_session(divbase_url=divbase_url, config=config)
@@ -55,7 +56,14 @@ def login(
55
56
  print("Login cancelled.")
56
57
  return
57
58
 
58
- login_to_divbase(email=email, password=secret_password, divbase_url=divbase_url, config_path=config_file)
59
+ login_to_divbase(email=email, password=secret_password, divbase_url=divbase_url)
60
+
61
+ try:
62
+ get_and_display_announcements(divbase_base_url=divbase_url)
63
+ except (DivBaseAPIError, DivBaseAPIConnectionError):
64
+ # lets not fail the login process if announcements are not working.
65
+ logger.error("Failed to get announcements after login. Error was: ", exc_info=True)
66
+
59
67
  print(f"Logged in successfully as: {email}")
60
68
 
61
69
 
@@ -69,13 +77,11 @@ def logout():
69
77
 
70
78
 
71
79
  @auth_app.command("whoami")
72
- def whoami(
73
- config_file: Path = CONFIG_FILE_OPTION,
74
- ):
80
+ def whoami():
75
81
  """
76
82
  Return information about the currently logged-in user.
77
83
  """
78
- config = load_user_config(config_file)
84
+ config = load_user_config()
79
85
  logged_in_url = config.logged_in_url
80
86
 
81
87
  # TODO - move logged in check to the make_authenticated_request function?
@@ -0,0 +1,439 @@
1
+ import csv
2
+ import logging
3
+ from pathlib import Path
4
+
5
+ import typer
6
+ import yaml
7
+ from rich import print
8
+
9
+ from divbase_cli.cli_commands.shared_args_options import PROJECT_NAME_OPTION
10
+ from divbase_cli.config_resolver import resolve_project
11
+ from divbase_cli.user_auth import make_authenticated_request
12
+ from divbase_lib.api_schemas.vcf_dimensions import (
13
+ DimensionsSamplesResult,
14
+ DimensionsScaffoldsResult,
15
+ DimensionsShowResult,
16
+ )
17
+ from divbase_lib.metadata_validator import SharedMetadataValidator
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ dimensions_app = typer.Typer(
23
+ no_args_is_help=True,
24
+ help="Create and inspect dimensions (number of samples, number of variants, scaffold names) of the VCF files in a project",
25
+ )
26
+
27
+
28
+ @dimensions_app.command("update")
29
+ def update_dimensions_index(
30
+ project: str | None = PROJECT_NAME_OPTION,
31
+ ) -> None:
32
+ """Calculate and add the dimensions of a VCF file to the dimensions index file in the project."""
33
+
34
+ project_config = resolve_project(project_name=project)
35
+
36
+ response = make_authenticated_request(
37
+ method="PUT",
38
+ divbase_base_url=project_config.divbase_url,
39
+ api_route=f"v1/vcf-dimensions/projects/{project_config.name}",
40
+ )
41
+
42
+ task_id = response.json()
43
+ print(f"Job submitted successfully with task id: {task_id}")
44
+
45
+
46
+ @dimensions_app.command("show")
47
+ def show_dimensions_index(
48
+ filename: str = typer.Option(
49
+ None,
50
+ "--filename",
51
+ help="If set, will show only the entry for this VCF filename.",
52
+ ),
53
+ unique_scaffolds: bool = (
54
+ typer.Option(
55
+ False,
56
+ "--unique-scaffolds",
57
+ help="If set, will show all unique scaffold names found across all the VCF files in the project.",
58
+ )
59
+ ),
60
+ unique_samples: bool = (
61
+ typer.Option(
62
+ False,
63
+ "--unique-samples",
64
+ help="If set, will show all unique sample names found across all the VCF files in the project.",
65
+ )
66
+ ),
67
+ sample_names_limit: int = typer.Option(
68
+ 20,
69
+ "--sample-names-limit",
70
+ min=1,
71
+ help="Maximum number of sample names to display per list in terminal output.",
72
+ ),
73
+ sample_names_output: str | None = typer.Option(
74
+ None,
75
+ "--sample-names-output",
76
+ help="Write full sample names to file instead of truncating in terminal output. "
77
+ "Mutually exclusive with --sample-names-stdout.",
78
+ ),
79
+ sample_names_stdout: bool = typer.Option(
80
+ False,
81
+ "--sample-names-stdout",
82
+ help="Print full sample names to stdout (useful for piping). Mutually exclusive with --sample-names-output.",
83
+ ),
84
+ project: str | None = PROJECT_NAME_OPTION,
85
+ ) -> None:
86
+ """
87
+ Show the dimensions index file for a project.
88
+ When running --unique-scaffolds, the sorting separates between numeric and non-numeric scaffold names.
89
+ """
90
+
91
+ project_config = resolve_project(project_name=project)
92
+
93
+ # These two options are mutually exclusive. But due to how typer handles options, this error will only be raised if --sample-names-output has an input value (i.e. path).
94
+ # If the path is missing, it will raise an error about the missing path argument instead...
95
+ if sample_names_output and sample_names_stdout:
96
+ typer.echo("Use only one of --sample-names-output or --sample-names-stdout.", err=True)
97
+ raise typer.Exit(code=1)
98
+
99
+ if unique_samples:
100
+ response = make_authenticated_request(
101
+ method="GET",
102
+ divbase_base_url=project_config.divbase_url,
103
+ api_route=f"v1/vcf-dimensions/projects/{project_config.name}/samples",
104
+ )
105
+ unique_sample_names_sorted = DimensionsSamplesResult(**response.json()).unique_samples
106
+ sample_count = len(unique_sample_names_sorted)
107
+
108
+ if sample_names_output:
109
+ output_path = Path(sample_names_output)
110
+ output_path.write_text("\n".join(unique_sample_names_sorted) + "\n")
111
+ print(f"Wrote {sample_count} unique sample names to: {output_path}")
112
+ return
113
+
114
+ if sample_names_stdout:
115
+ print("\n".join(unique_sample_names_sorted))
116
+ return
117
+
118
+ if sample_count > sample_names_limit:
119
+ preview = unique_sample_names_sorted[:sample_names_limit]
120
+ print(
121
+ f"Unique sample names found across all the VCF files in the project (count: {sample_count}, showing first {sample_names_limit}):\n{preview}\n"
122
+ f"To view all, use --sample-names-output <FILE> or --sample-names-stdout."
123
+ )
124
+ return
125
+
126
+ print(
127
+ f"Unique sample names found across all the VCF files in the project (count: {sample_count}):\n{unique_sample_names_sorted}"
128
+ )
129
+ return
130
+
131
+ if unique_scaffolds:
132
+ response = make_authenticated_request(
133
+ method="GET",
134
+ divbase_base_url=project_config.divbase_url,
135
+ api_route=f"v1/vcf-dimensions/projects/{project_config.name}/scaffolds",
136
+ )
137
+ unique_scaffold_names_sorted = DimensionsScaffoldsResult(**response.json()).unique_scaffolds
138
+ scaffold_count = len(unique_scaffold_names_sorted)
139
+ print(
140
+ f"Unique scaffold names found across all the VCF files in the project (count: {scaffold_count}):\n{unique_scaffold_names_sorted}"
141
+ )
142
+ return
143
+
144
+ response = make_authenticated_request(
145
+ method="GET",
146
+ divbase_base_url=project_config.divbase_url,
147
+ api_route=f"v1/vcf-dimensions/projects/{project_config.name}",
148
+ )
149
+ vcf_dimensions_data = DimensionsShowResult(**response.json())
150
+
151
+ dimensions_info = _format_api_response_for_display_in_terminal(vcf_dimensions_data)
152
+
153
+ if filename:
154
+ record = None
155
+ for entry in dimensions_info.get("indexed_files", []):
156
+ if entry.get("filename") == filename:
157
+ record = entry
158
+ break
159
+ if record:
160
+ if sample_names_output or sample_names_stdout:
161
+ _write_or_print_sample_names(
162
+ indexed_files=[record],
163
+ sample_names_output=sample_names_output,
164
+ sample_names_stdout=sample_names_stdout,
165
+ )
166
+ return
167
+
168
+ _truncate_sample_names_in_entry(record, sample_names_limit)
169
+ print(yaml.safe_dump(record, sort_keys=False))
170
+ else:
171
+ print(
172
+ f"No entry found for filename: {filename}. Please check that the filename is correct and that it is a VCF file (extension: .vcf or .vcf.gz)."
173
+ "\nHint: use 'divbase-cli files ls' to view all files in the project."
174
+ )
175
+ return
176
+
177
+ if sample_names_output or sample_names_stdout:
178
+ _write_or_print_sample_names(
179
+ indexed_files=dimensions_info.get("indexed_files", []),
180
+ sample_names_output=sample_names_output,
181
+ sample_names_stdout=sample_names_stdout,
182
+ )
183
+ return
184
+
185
+ for entry in dimensions_info.get("indexed_files", []):
186
+ _truncate_sample_names_in_entry(entry, sample_names_limit)
187
+
188
+ print(yaml.safe_dump(dimensions_info, sort_keys=False))
189
+
190
+
191
+ def _format_api_response_for_display_in_terminal(api_response: DimensionsShowResult) -> dict:
192
+ """
193
+ Convert the API response to a YAML-like format for display in the user's terminal.
194
+ """
195
+
196
+ def sort_scaffolds(scaffolds: list[str]) -> list[str]:
197
+ numeric = sorted([int(s) for s in scaffolds if s.isdigit()])
198
+ non_numeric = sorted([s for s in scaffolds if not s.isdigit()])
199
+ return [str(n) for n in numeric] + non_numeric
200
+
201
+ dimensions_list = []
202
+ for entry in api_response.vcf_files:
203
+ scaffolds = entry.get("scaffolds", [])
204
+ sorted_scaffolds = sort_scaffolds(scaffolds)
205
+ dimensions_entry = {
206
+ "filename": entry["vcf_file_s3_key"],
207
+ "file_version_ID_in_bucket": entry["s3_version_id"],
208
+ "last_updated": entry.get("updated_at"),
209
+ "dimensions": {
210
+ "scaffold_count": len(sorted_scaffolds),
211
+ "scaffolds": sorted_scaffolds,
212
+ "sample_count": entry.get("sample_count", 0),
213
+ "sample_names": entry.get("samples", []),
214
+ "variants": entry.get("variant_count", 0),
215
+ },
216
+ }
217
+ dimensions_list.append(dimensions_entry)
218
+
219
+ skipped_list = []
220
+ for entry in api_response.skipped_files:
221
+ skipped_entry = {
222
+ "filename": entry["vcf_file_s3_key"],
223
+ "file_version_ID_in_bucket": entry["s3_version_id"],
224
+ "skip_reason": entry.get("skip_reason", "unknown"),
225
+ }
226
+ skipped_list.append(skipped_entry)
227
+
228
+ return {
229
+ "indexed_files": dimensions_list,
230
+ "skipped_files": skipped_list,
231
+ }
232
+
233
+
234
+ @dimensions_app.command("create-metadata-template")
235
+ def create_metadata_template_with_project_samples_names(
236
+ output_path: Path | None = typer.Option(
237
+ None,
238
+ "--output",
239
+ "-o",
240
+ file_okay=True,
241
+ dir_okay=False,
242
+ resolve_path=True,
243
+ help="Path to the output TSV file to create. Defaults to sample_metadata_<project_name>.tsv in the current directory. If a file already exists at the given path, you will be prompted to confirm if you want to overwrite it.",
244
+ ),
245
+ project: str | None = PROJECT_NAME_OPTION,
246
+ ) -> None:
247
+ """
248
+ Create a template sample metadata file (TSV format) pre-filled with the sample names from the project's VCF files based on the information stored in the project's VCF dimensions cache. Tip: run 'divbase-cli dimensions update' first to ensure that the VCF dimensions areup-to-date.
249
+ """
250
+
251
+ project_config = resolve_project(project_name=project)
252
+
253
+ if output_path is None:
254
+ output_path = Path.cwd() / f"sample_metadata_{project_config.name}.tsv"
255
+
256
+ response = make_authenticated_request(
257
+ method="GET",
258
+ divbase_base_url=project_config.divbase_url,
259
+ api_route=f"v1/vcf-dimensions/projects/{project_config.name}/samples",
260
+ )
261
+ unique_sample_names_sorted = DimensionsSamplesResult(**response.json()).unique_samples
262
+
263
+ sample_count = len(unique_sample_names_sorted)
264
+ print(
265
+ f"There were {sample_count} unique samples found in the dimensions file for the {project_config.name} project."
266
+ )
267
+
268
+ if sample_count == 0:
269
+ # Fallback in case there are no samples in the dimensions index. If no dimensions entry for the project
270
+ # VCFDimensionsEntryMissingError will be returned. But for some reason, there are no samples in the VCF, this will catch that.
271
+ print("No samples found for this project. No file written.")
272
+ return
273
+
274
+ # Check if file exists and prompt user for confirmation
275
+ if output_path.exists():
276
+ overwrite = typer.confirm(f"File '{output_path}' already exists. Do you want to overwrite it?")
277
+ if not overwrite:
278
+ print("File not written. Exiting.")
279
+ return
280
+
281
+ with open(output_path, mode="w", newline="") as tsvfile:
282
+ writer = csv.writer(tsvfile, delimiter="\t")
283
+ writer.writerow(["#Sample_ID"])
284
+ for sample in unique_sample_names_sorted:
285
+ writer.writerow([sample])
286
+
287
+ print(f"A sample metadata template with these sample names was written to: {output_path}")
288
+
289
+ # TODO perhaps add a message on how to fill in additional columns and how to upload the metadata file to DivBase?
290
+
291
+
292
+ @dimensions_app.command("validate-metadata-file")
293
+ def validate_metadata_template_versus_dimensions_and_formatting_constraints(
294
+ input_path: Path = typer.Argument(
295
+ ...,
296
+ exists=True,
297
+ file_okay=True,
298
+ dir_okay=False,
299
+ resolve_path=True,
300
+ help="Path to the input TSV file to validate.",
301
+ ),
302
+ untruncated: bool = typer.Option(
303
+ False,
304
+ "--untruncated",
305
+ help="Show full (untruncated) validator lists (including sample mismatches and grouped warning row/value previews).",
306
+ ),
307
+ project: str | None = PROJECT_NAME_OPTION,
308
+ ) -> None:
309
+ """
310
+ Validate a sample metadata TSV file (before you upload it to the project's data store) to check that it will work with DivBase queries.
311
+ """
312
+ # Client-side validation of a sidecar metadata TSV file, intended to be run before upload to DivBase.
313
+ # Uses the SharedMetadataValidator (that is also used on the server-side) which checks for formatting errors and also validates that the sample names
314
+ # in the TSV file match the sample names in the dimensions index for the project
315
+
316
+ project_config = resolve_project(project_name=project)
317
+
318
+ print(f"Validating local metadata file: {input_path}")
319
+ print(f"Project: {project_config.name}\n")
320
+
321
+ response = make_authenticated_request(
322
+ method="GET",
323
+ divbase_base_url=project_config.divbase_url,
324
+ api_route=f"v1/vcf-dimensions/projects/{project_config.name}/samples",
325
+ )
326
+ unique_sample_names = DimensionsSamplesResult(**response.json()).unique_samples
327
+
328
+ dimensions_sample_preview_limit = None if untruncated else 20
329
+
330
+ shared_validator = SharedMetadataValidator(
331
+ file_path=input_path,
332
+ project_samples=set(unique_sample_names),
333
+ skip_dimensions_check=False,
334
+ dimensions_sample_preview_limit=dimensions_sample_preview_limit,
335
+ )
336
+ result = shared_validator.load_and_validate()
337
+
338
+ errors = [error_entry.message for error_entry in result.errors]
339
+ warnings = [warning_entry.message for warning_entry in result.warnings]
340
+ stats = result.stats
341
+ numeric_cols = result.numeric_columns
342
+ string_cols = result.string_columns
343
+ mixed_cols = result.mixed_type_columns
344
+
345
+ print("[bold cyan]VALIDATION SUMMARY:[/bold cyan]")
346
+ print(
347
+ f" Total columns: {getattr(stats, 'total_columns', 0)} ({getattr(stats, 'user_defined_columns', 0)} user-defined + 1 Sample_ID column)"
348
+ )
349
+
350
+ samples_in_tsv = getattr(stats, "samples_in_tsv", 0)
351
+ samples_matching = getattr(stats, "samples_matching_project", 0)
352
+ total_project = getattr(stats, "total_project_samples", 0)
353
+
354
+ print(
355
+ f" Samples matching project VCF dimensions: {samples_matching}/{samples_in_tsv} (project has {total_project} total)"
356
+ )
357
+
358
+ print(f" Numeric columns ({len(numeric_cols)}): {', '.join(numeric_cols) if numeric_cols else 'None'}")
359
+ print(f" String columns ({len(string_cols)}): {', '.join(string_cols) if string_cols else 'None'}")
360
+ print(
361
+ f" Mixed-type columns treated as string ({len(mixed_cols)}): {', '.join(mixed_cols) if mixed_cols else 'None'}"
362
+ )
363
+
364
+ if getattr(stats, "has_multi_values", False):
365
+ print(" Multi-value cells: Yes (Python list notation detected)")
366
+ else:
367
+ print(" Multi-value cells: No")
368
+
369
+ empty_cells = getattr(stats, "empty_cells_per_column", {})
370
+ if empty_cells:
371
+ print(
372
+ f" User-defined columns with empty cells ({len(empty_cells)}): {', '.join(f'{col} ({count})' for col, count in empty_cells.items())}"
373
+ )
374
+
375
+ print()
376
+
377
+ if errors:
378
+ print("[red bold]ERRORS (must be fixed):[/red bold]")
379
+ for error in errors:
380
+ print(f" - {error}")
381
+ print()
382
+
383
+ if warnings:
384
+ print("[yellow bold]WARNINGS (should be reviewed):[/yellow bold]")
385
+ for warning in warnings:
386
+ print(f" - {warning}")
387
+ print()
388
+
389
+ if not errors and not warnings:
390
+ print(
391
+ "[green bold]Validation passed![/green bold] The metadata file meets all DivBase requirements. The file is ready to be uploaded to your DivBase project with 'divbase-cli files upload'"
392
+ )
393
+ elif errors:
394
+ print("[red bold]Validation failed![/red bold] Please fix the errors above before uploading.")
395
+ raise typer.Exit(code=1)
396
+ else:
397
+ print("[yellow bold]Validation passed with warnings![/yellow bold] Review the warnings above.")
398
+
399
+ # TODO: Add information about how to upload the validated metadata file to DivBase
400
+
401
+
402
+ def _truncate_sample_names_in_entry(entry: dict, sample_names_limit: int) -> None:
403
+ """
404
+ Truncate sample names output in terminal, while preserving full counts.
405
+ """
406
+ dimensions = entry.get("dimensions", {})
407
+ sample_names = dimensions.get("sample_names", [])
408
+ if len(sample_names) > sample_names_limit:
409
+ dimensions["sample_names"] = sample_names[:sample_names_limit]
410
+ dimensions["sample_names_note"] = (
411
+ f"Showing first {sample_names_limit} of {len(sample_names)} samples. "
412
+ "Use --sample-names-output <FILE> or --sample-names-stdout to view all."
413
+ )
414
+
415
+
416
+ def _write_or_print_sample_names(
417
+ indexed_files: list[dict],
418
+ sample_names_output: str | None,
419
+ sample_names_stdout: bool,
420
+ ) -> None:
421
+ """
422
+ Export full sample names data from divbase-cli dimensions show
423
+ either to a file or to stdout. If used without --unique-samples, it will also include the filename that each sample occurs in.
424
+ """
425
+ lines: list[str] = []
426
+ for entry in indexed_files:
427
+ file_name = entry.get("filename", "")
428
+ sample_names = entry.get("dimensions", {}).get("sample_names", [])
429
+ for sample_name in sample_names:
430
+ lines.append(f"{file_name}\t{sample_name}")
431
+
432
+ if sample_names_output:
433
+ output_path = Path(sample_names_output)
434
+ output_path.write_text("\n".join(lines) + ("\n" if lines else ""))
435
+ print(f"Wrote {len(lines)} sample-name rows to: {output_path}")
436
+ return
437
+
438
+ if sample_names_stdout:
439
+ print("\n".join(lines))