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,413 @@
1
+ """
2
+ Query subcommand for the DivBase CLI.
3
+
4
+ Submits queries (sample metadata and/or bcftools) to the DivBase API.
5
+
6
+ If sample metadata query:
7
+ results are printed to the console.
8
+
9
+ If bcftools query:
10
+ a task id is returned which can be used to check the status of the job.
11
+ After task completed, a merged VCF file will be added to the project's storage bucket which can be downloaded by the user.
12
+ """
13
+
14
+ import logging
15
+ from pathlib import Path
16
+
17
+ import stamina
18
+ import typer
19
+ from rich import print
20
+
21
+ from divbase_cli.cli_commands.file_cli import _pretty_print_download_results
22
+ from divbase_cli.cli_commands.shared_args_options import DOWNLOAD_DIR_OPTION, PROJECT_NAME_OPTION
23
+ from divbase_cli.cli_config import cli_settings
24
+ from divbase_cli.cli_exceptions import PolledTaskNotFinalError, QueryTaskFailedError
25
+ from divbase_cli.config_resolver import (
26
+ resolve_and_authenticate_project,
27
+ resolve_download_dir,
28
+ )
29
+ from divbase_cli.retries import (
30
+ retry_polling_until_final_or_retryable_api_errors,
31
+ )
32
+ from divbase_cli.services.s3_files import download_files_command
33
+ from divbase_cli.user_auth import make_authenticated_request
34
+ from divbase_lib.api_schemas.queries import (
35
+ BcftoolsQueryRequest,
36
+ SampleMetadataQueryRequest,
37
+ SampleMetadataQueryTaskResult,
38
+ )
39
+ from divbase_lib.api_schemas.task_history import TaskHistoryResult
40
+ from divbase_lib.divbase_constants import QUERY_RESULTS_FILE_PREFIX
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+
45
+ METADATA_TSV_ARGUMENT = typer.Option(
46
+ cli_settings.METADATA_TSV_NAME, help="Name of the sample metadata TSV file in the project's data store on DivBase."
47
+ )
48
+
49
+ BCFTOOLS_ARGUMENT = typer.Option(
50
+ ...,
51
+ help="""
52
+ String consisting of the bcftools view command(s) to run. E.g. "view -r 21:15000000-25000000" or "view -s".
53
+ The string cannot be empty; if you only want to subset on the selected samples, use: --command "view -s"
54
+ """,
55
+ )
56
+
57
+ # Sample metadata and VCF queries both use the same core text, so it is defined up here.
58
+ TSV_FILTER_SYNTAX = (
59
+ "String consisting of keys:values in the tsv file to filter on. "
60
+ "The syntax is 'Key1:Value1,Value2;Key2:Value3,Value4', where the keys are the column header names in the tsv, "
61
+ "and values are the column values. Multiple values for a key are separated by commas, and multiple keys are "
62
+ "separated by semicolons. When multiple keys are provided, an intersect query will be performed. "
63
+ "E.g. 'Area:West of Ireland,Northern Portugal;Sex:F'."
64
+ )
65
+
66
+ TSV_FILTER_HELP_TEXT_VCF = (
67
+ "This option calculates the samples to filter the VCFs on based on a sample metadata query. "
68
+ + TSV_FILTER_SYNTAX
69
+ + "\n\nMutually exclusive with --samples, --samples-file, and --all-samples."
70
+ )
71
+
72
+ SAMPLE_SELECTION_HELP_PANEL = "Sample Selection (Required: Include Exactly One)"
73
+ VCF_QUERY_HELP_TEXT = (
74
+ "Submit a VCF query to run on the DivBase API. "
75
+ "A single, merged VCF file with the query results will be added to the project on success.\n\n"
76
+ "Exactly one sample-selection mode is required: "
77
+ "--tsv-filter | --samples | --samples-file | --all-samples."
78
+ )
79
+
80
+ MAX_WAIT_MINS_HARD_LIMIT = 600 # 10 hours
81
+
82
+ GET_RESULTS_HELP_TEXT = (
83
+ "Wait for a 'divbase-cli query vcf' job to complete and download the results file when complete. "
84
+ "Similar to running 'divbase-cli task-history id <TASK_ID>' but with the added benefit of polling for the "
85
+ "terminal state of the job (SUCCESS/FAILED). Designed to be of particular use in scripts and other automated workflows. "
86
+ "Error codes (e.g. for scripts): 0 — task succeeded and file downloaded; 1 — task failed; 2 — unsupported task type"
87
+ )
88
+
89
+ query_app = typer.Typer(
90
+ help="Run queries on the VCF files stored in the project's data store on DivBase. Queries are run on the DivBase API",
91
+ no_args_is_help=True,
92
+ )
93
+
94
+
95
+ @query_app.command("tsv")
96
+ def sample_metadata_query(
97
+ tsv_filter: str = typer.Argument(
98
+ ...,
99
+ help=TSV_FILTER_SYNTAX,
100
+ ),
101
+ show_sample_results: bool = typer.Option(
102
+ default=False,
103
+ help="Print sample_ID and Filename results from the query.",
104
+ ),
105
+ metadata_tsv_name: str = METADATA_TSV_ARGUMENT,
106
+ project: str | None = PROJECT_NAME_OPTION,
107
+ ) -> None:
108
+ """
109
+ Query the tsv sidecar metadata file for the VCF files in the project's data store on DivBase.
110
+ Returns the sample IDs and filenames that match the query.
111
+ """
112
+ project_config = resolve_and_authenticate_project(project_name=project)
113
+ request_data = SampleMetadataQueryRequest(tsv_filter=tsv_filter, metadata_tsv_name=metadata_tsv_name)
114
+
115
+ response = make_authenticated_request(
116
+ method="POST",
117
+ divbase_base_url=project_config.divbase_url,
118
+ api_route=f"v1/query/sample-metadata/projects/{project_config.name}",
119
+ json=request_data.model_dump(),
120
+ timeout=20, # This is longer than default (5), as api call response is query result, not a task-id.
121
+ )
122
+ results = SampleMetadataQueryTaskResult(**response.json())
123
+
124
+ if results.warnings:
125
+ print("[yellow]Warnings:[/yellow]")
126
+ for warning in results.warnings:
127
+ print(f" • {warning}")
128
+ print()
129
+
130
+ if show_sample_results:
131
+ print("[bright_blue]Name and file for each sample in query results:[/bright_blue]")
132
+ for sample in results.sample_and_filename_subset:
133
+ print(f"Sample ID: '{sample.sample_id}', Filename: '{sample.filename}'")
134
+
135
+ print(f"The results for the query ([bright_blue]{results.query_message}[/bright_blue]):")
136
+
137
+ unique_sample_ids = results.unique_sample_ids or []
138
+ unique_filenames = results.unique_filenames or []
139
+ print(f"Unique Sample IDs: {unique_sample_ids}")
140
+ print(f"Unique filenames: {unique_filenames}\n")
141
+ if not unique_sample_ids:
142
+ print("[yellow]No samples match your query filters.[/yellow]\n")
143
+
144
+
145
+ @query_app.command("vcf", help=VCF_QUERY_HELP_TEXT)
146
+ def vcf_query(
147
+ tsv_filter: str | None = typer.Option(
148
+ None, help=TSV_FILTER_HELP_TEXT_VCF, rich_help_panel=SAMPLE_SELECTION_HELP_PANEL
149
+ ),
150
+ samples: str | None = typer.Option(
151
+ None,
152
+ help="Comma-separated list of sample IDs. Mutually exclusive with --tsv-filter, --samples-file, and --all-samples.",
153
+ rich_help_panel=SAMPLE_SELECTION_HELP_PANEL,
154
+ ),
155
+ samples_file: Path | None = typer.Option(
156
+ None,
157
+ exists=True,
158
+ file_okay=True,
159
+ dir_okay=False,
160
+ readable=True,
161
+ resolve_path=True,
162
+ help=(
163
+ "Path to a UTF-8 text file with one sample ID per line. Blank lines and lines starting with # are ignored. "
164
+ "Mutually exclusive with --tsv-filter, --samples, and --all-samples."
165
+ ),
166
+ rich_help_panel=SAMPLE_SELECTION_HELP_PANEL,
167
+ ),
168
+ all_samples: bool = typer.Option(
169
+ False,
170
+ "--all-samples",
171
+ help=(
172
+ "Use all samples in the project for the query. "
173
+ "Mutually exclusive with --tsv-filter, --samples, and --samples-file."
174
+ ),
175
+ rich_help_panel=SAMPLE_SELECTION_HELP_PANEL,
176
+ ),
177
+ command: str = BCFTOOLS_ARGUMENT,
178
+ metadata_tsv_name: str = METADATA_TSV_ARGUMENT,
179
+ project: str | None = PROJECT_NAME_OPTION,
180
+ ) -> None:
181
+ """
182
+ Submit a VCF query to run on the DivBase API. A single, merged VCF file with the query results will be added to the project on success.
183
+ """
184
+
185
+ # TODO Error handling for subprocess calls.
186
+ # TODO: handle the case empty results are returned from tsv_query()
187
+ # TODO what if a job fails and the user wants to re-run it? do we store temp files?
188
+
189
+ # Note! Pydantic model validator also enforces this on the API side just queries can be submitted directly to the endpoint.
190
+ # This block here is to catch it on the CLI side with a more user-friendly error message before even making the API call.
191
+ has_tsv_filter = tsv_filter is not None
192
+ has_samples = samples is not None
193
+ has_samples_file = samples_file is not None
194
+ has_all_samples = all_samples
195
+ selection_count = sum([has_tsv_filter, has_samples, has_samples_file, has_all_samples])
196
+ if selection_count > 1:
197
+ raise typer.BadParameter("Use only one of --tsv-filter, --samples, --samples-file, or --all-samples.")
198
+ if selection_count == 0:
199
+ raise typer.BadParameter(
200
+ "Sample selection is required. Use one of --tsv-filter, --samples, --samples-file, or --all-samples."
201
+ )
202
+
203
+ normalized_samples, sample_input_warnings = _normalize_samples_input(samples=samples, samples_file=samples_file)
204
+ if sample_input_warnings:
205
+ print("[yellow]Warnings:[/yellow]")
206
+ for warning in sample_input_warnings:
207
+ print(f" • {warning}")
208
+ print()
209
+
210
+ project_config = resolve_and_authenticate_project(project_name=project)
211
+ request_data = BcftoolsQueryRequest(
212
+ tsv_filter=tsv_filter,
213
+ command=command,
214
+ metadata_tsv_name=metadata_tsv_name,
215
+ samples=normalized_samples,
216
+ all_samples=all_samples,
217
+ )
218
+ response = make_authenticated_request(
219
+ method="POST",
220
+ divbase_base_url=project_config.divbase_url,
221
+ api_route=f"v1/query/vcf/projects/{project_config.name}",
222
+ json=request_data.model_dump(),
223
+ )
224
+
225
+ task_id = response.json()
226
+ print(
227
+ f"Job submitted successfully with task id: {task_id}. To check the status of your job, use the command: divbase-cli task-history id {task_id}"
228
+ )
229
+
230
+
231
+ @query_app.command("get-vcf-results", help=GET_RESULTS_HELP_TEXT)
232
+ def get_results_from_query_job_by_task_id(
233
+ task_id: int = typer.Argument(..., help="Task ID of the query job to poll for results from."),
234
+ download_dir: str = DOWNLOAD_DIR_OPTION,
235
+ project: str | None = PROJECT_NAME_OPTION,
236
+ max_wait_mins: int = typer.Option(
237
+ 120,
238
+ "--max-wait-mins",
239
+ help=f"Maximum number of minutes to poll for task completion. Must be between 1 and {MAX_WAIT_MINS_HARD_LIMIT}.",
240
+ ),
241
+ ) -> None:
242
+ """
243
+ Get results from a VCF query job by its task ID by first polling for the final state of the task and then downloading the results file.
244
+
245
+ Exit codes (for programmatic use in scripts and other automated workflows):
246
+ 0 — task succeeded and file downloaded (default, no explicit call needed)
247
+ 1 — task failed (Celery job final status was FAILURE)
248
+ 2 — unsupported task type
249
+ """
250
+
251
+ if not 1 <= max_wait_mins <= MAX_WAIT_MINS_HARD_LIMIT:
252
+ raise typer.BadParameter(
253
+ f"--max-wait-mins must be between 1 and {MAX_WAIT_MINS_HARD_LIMIT} minutes, got {max_wait_mins}."
254
+ )
255
+
256
+ project_config = resolve_and_authenticate_project(project_name=project)
257
+
258
+ task_status = poll_task_until_final_state_reached(
259
+ divbase_url=project_config.divbase_url,
260
+ task_id=task_id,
261
+ timeout_mins=max_wait_mins,
262
+ )
263
+
264
+ resolved_download_dir = resolve_download_dir(download_dir=download_dir)
265
+ log_filename = f"{QUERY_RESULTS_FILE_PREFIX}{task_id}.log"
266
+
267
+ if task_status == "SUCCESS":
268
+ result_filename = f"{QUERY_RESULTS_FILE_PREFIX}{task_id}.vcf.gz"
269
+ download_results = download_files_command(
270
+ divbase_base_url=project_config.divbase_url,
271
+ project_name=project_config.name,
272
+ raw_files_input=[result_filename],
273
+ download_dir=resolved_download_dir,
274
+ flatten=False,
275
+ verify_checksums=True,
276
+ dry_run=False,
277
+ project_version=None,
278
+ )
279
+ _pretty_print_download_results(download_results=download_results)
280
+ else:
281
+ raise QueryTaskFailedError(
282
+ f"Task {task_id} failed. Run 'divbase-cli task-history id {task_id}' for more details on the failure.\n"
283
+ f"The task's log file can be downloaded for debugging using the command:\n'divbase-cli files download {log_filename}'\n"
284
+ f"You can view the log file contents directly in your terminal with:\n'divbase-cli files stream {log_filename}'"
285
+ )
286
+
287
+
288
+ def poll_task_until_final_state_reached(divbase_url: str, task_id: int, timeout_mins: int) -> str:
289
+ """
290
+ Poll for the final state (SUCCESS/FAILURE) of a celery task by task ID.
291
+
292
+ Note that this is designed with two layers of retry_only_on_retryable_divbase_api_errors: the outer layer (this function), and the inner layer (make_authenticated_request; 3 attempts).
293
+ This is to make this polling more resilient to temporary API errors for the intent of using the CLI command that calls this in scripts and other automated workflows.
294
+ """
295
+
296
+ FINAL_STATES = {"SUCCESS", "FAILURE"}
297
+ SUPPORTED_TASK_NAMES = {"tasks.bcftools_query"}
298
+
299
+ # inline retry_context instead of using @stamina.retry decorator because timeout_mins is a runtime value input from the CLI, not a constant (which the decorator needs)
300
+ for attempt in stamina.retry_context(
301
+ on=retry_polling_until_final_or_retryable_api_errors,
302
+ attempts=None, # no attempt cap — rely solely on timeout_mins
303
+ wait_initial=1.0, # seconds. Some overhead time is required to init the Celery task even with idle workers, so wait a bit before first poll.
304
+ wait_exp_base=2, # exponential backoff factor
305
+ wait_max=60.0, # cap exponential backoff at once per 60 seconds if it reaches that far.
306
+ wait_jitter=0.0,
307
+ timeout=timeout_mins * 60,
308
+ ):
309
+ with attempt:
310
+ response = make_authenticated_request(
311
+ method="GET",
312
+ divbase_base_url=divbase_url,
313
+ api_route=f"v1/task-history/tasks/{task_id}",
314
+ )
315
+ # Endpoint returns 403 if the task is not found or the user does not have permission to view it. So item should not be empty.
316
+ items = response.json()
317
+
318
+ task_results = TaskHistoryResult(**items[0]) # for task ID lookups, only one entry is returned
319
+
320
+ if task_results.status is None:
321
+ raise PolledTaskNotFinalError(f"Task {task_id} is queued and waiting to start")
322
+
323
+ if task_results.name not in SUPPORTED_TASK_NAMES:
324
+ raise typer.BadParameter(
325
+ f"Task {task_id} has unsupported task type '{task_results.name}'. Only VCF query jobs are supported for this CLI command."
326
+ )
327
+
328
+ if task_results.status and task_results.status in FINAL_STATES:
329
+ return task_results.status
330
+
331
+ raise PolledTaskNotFinalError(f"Task {task_id} state is {task_results.status}")
332
+
333
+
334
+ def _normalize_samples_input(samples: str | None, samples_file: Path | None) -> tuple[list[str] | None, list[str]]:
335
+ """
336
+ Normalize sample selection inputs from CLI options.
337
+ """
338
+ if samples is not None:
339
+ normalized = []
340
+ for sample in samples.split(","):
341
+ sample_clean = sample.strip()
342
+ if sample_clean:
343
+ normalized.append(sample_clean)
344
+
345
+ if not normalized:
346
+ raise typer.BadParameter("--samples must contain at least one non-empty sample ID.")
347
+ return normalized, []
348
+
349
+ if samples_file is not None:
350
+ raw_lines = samples_file.read_text(encoding="utf-8").splitlines()
351
+ normalized = []
352
+ warnings = []
353
+ delimiter_lines = []
354
+ found_delimiters = set()
355
+ disallowed_delimiters = (",", ";", "\t", "|")
356
+ delimiter_display = {
357
+ ",": "','",
358
+ ";": "';'",
359
+ "\t": "'tab'",
360
+ "|": "'|'",
361
+ }
362
+
363
+ for line_number, raw_line in enumerate(raw_lines, start=1):
364
+ stripped = raw_line.strip()
365
+ if not stripped or stripped.startswith("#"):
366
+ continue
367
+
368
+ normalized.append(stripped)
369
+ line_delimiters = set()
370
+ for delimiter in disallowed_delimiters:
371
+ if delimiter in stripped:
372
+ line_delimiters.add(delimiter)
373
+
374
+ if line_delimiters:
375
+ delimiter_lines.append((line_number, stripped))
376
+ found_delimiters.update(line_delimiters)
377
+
378
+ if not normalized:
379
+ raise typer.BadParameter(
380
+ f"Samples file has no sample IDs after ignoring blank/comment lines: {samples_file}. Please ensure that it contains at least one sample ID."
381
+ )
382
+
383
+ if delimiter_lines:
384
+ preview_entries = [] # Only preview up to the first 3 lines with delimiters to avoid overwhelming the user with a long list if there are many problematic lines.
385
+ for line_number, line_value in delimiter_lines[:3]:
386
+ preview_entries.append(f"line {line_number} ('{line_value}')")
387
+ preview = ", ".join(preview_entries)
388
+
389
+ previewed_line_count = min(len(delimiter_lines), 3)
390
+ extra_line_count = len(delimiter_lines) - previewed_line_count
391
+ extra_msg = f", +{extra_line_count} more line(s)" if extra_line_count > 0 else ""
392
+
393
+ delimiter_names = []
394
+ for delimiter in disallowed_delimiters:
395
+ if delimiter in found_delimiters:
396
+ delimiter_names.append(delimiter_display[delimiter])
397
+ delimiters_found_str = ", ".join(delimiter_names)
398
+
399
+ raise typer.BadParameter(
400
+ "Invalid --samples-file format: expected one sample ID per line with no delimiters. "
401
+ f"Found delimiter(s) {delimiters_found_str} on {len(delimiter_lines)} line(s): \n{preview}{extra_msg}. "
402
+ "\nPlease do not use delimiters (',' ';' '\\t' '|') in your samples file."
403
+ )
404
+
405
+ if len(normalized) == 1:
406
+ warnings.append(
407
+ "Only one sample ID was found in --samples-file after ignoring blank/comment lines. "
408
+ "If this was not intended, verify that the file has one sample ID per line."
409
+ )
410
+
411
+ return normalized, warnings
412
+
413
+ return None, []
@@ -0,0 +1,33 @@
1
+ """
2
+ To avoid potential problems with circular imports, we can put shared typer args + options (etc...) here
3
+
4
+ If you have something that is only used in one of the cli subcommands, don't move it here.
5
+ """
6
+
7
+ import typer
8
+
9
+ DOWNLOAD_DIR_OPTION = typer.Option(
10
+ None,
11
+ "--download-dir",
12
+ "-d",
13
+ help="""Directory to download the files to.
14
+ If not provided, defaults to what you specified in your user config.
15
+ If also not specified in your user config, downloads to the current directory.
16
+ You can also specify "." to download to the current directory.""",
17
+ )
18
+
19
+ PROJECT_NAME_OPTION = typer.Option(
20
+ None,
21
+ "--project",
22
+ "-p",
23
+ help="Name of the DivBase project, if not provided uses the default in your DivBase config file",
24
+ show_default=False,
25
+ )
26
+
27
+
28
+ FORMAT_AS_TSV_OPTION = typer.Option(
29
+ False,
30
+ "--tsv",
31
+ "-t",
32
+ help="If set, will print the output in .TSV format for easier programmatic parsing.",
33
+ )
@@ -0,0 +1,126 @@
1
+ """
2
+ Task history subcommand for the DivBase CLI.
3
+
4
+ Submits a query for fetching the Celery task history for the user to the DivBase API.
5
+
6
+ """
7
+
8
+ import logging
9
+
10
+ import typer
11
+
12
+ from divbase_cli.cli_commands.shared_args_options import FORMAT_AS_TSV_OPTION
13
+ from divbase_cli.config_resolver import (
14
+ resolve_and_authenticate_project,
15
+ resolve_url_for_non_project_specific_commands,
16
+ )
17
+ from divbase_cli.display_task_history import TaskHistoryDisplayManager
18
+ from divbase_cli.user_auth import make_authenticated_request
19
+ from divbase_cli.user_config import load_user_config
20
+ from divbase_lib.api_schemas.task_history import TaskHistoryResult
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ task_history_app = typer.Typer(
26
+ help="Get the task history of query jobs submitted by the user to the DivBase API.",
27
+ no_args_is_help=True,
28
+ )
29
+
30
+
31
+ @task_history_app.command("user")
32
+ def list_task_history_for_user(
33
+ format_output_as_tsv: bool = FORMAT_AS_TSV_OPTION,
34
+ limit: int = typer.Option(10, help="Maximum number of tasks to display in the terminal. Sorted by recency."),
35
+ project: str | None = typer.Option(
36
+ None, help="Optional project name to filter the user's task history by project."
37
+ ),
38
+ ):
39
+ """
40
+ Check status of all tasks submitted by the user. Displays the latest 10 tasks by default, unless --limit is specified. Can be filtered by project name.
41
+ """
42
+ # TODO add option to sort ASC/DESC by task timestamp
43
+ divbase_url = resolve_url_for_non_project_specific_commands()
44
+
45
+ if project:
46
+ task_history_response = make_authenticated_request(
47
+ method="GET",
48
+ divbase_base_url=divbase_url,
49
+ api_route=f"v1/task-history/tasks/user/projects/{project}",
50
+ )
51
+ else:
52
+ task_history_response = make_authenticated_request(
53
+ method="GET",
54
+ divbase_base_url=divbase_url,
55
+ api_route="v1/task-history/tasks/user",
56
+ )
57
+
58
+ task_history_data = [TaskHistoryResult(**item) for item in task_history_response.json()]
59
+
60
+ config = load_user_config()
61
+ TaskHistoryDisplayManager(
62
+ task_items=task_history_data,
63
+ user_email=config.logged_in_email,
64
+ project_name=project,
65
+ mode="user_project" if project else "user",
66
+ display_limit=limit,
67
+ format_output_as_tsv=format_output_as_tsv,
68
+ ).print_task_history()
69
+
70
+
71
+ @task_history_app.command("id")
72
+ def task_history_by_id(
73
+ task_id: int | None = typer.Argument(..., help="Task ID to check the status of a specific query job."),
74
+ format_output_as_tsv: bool = FORMAT_AS_TSV_OPTION,
75
+ ):
76
+ """
77
+ Check status of a specific task submitted by the user by its task ID.
78
+ """
79
+ divbase_url = resolve_url_for_non_project_specific_commands()
80
+
81
+ task_history_response = make_authenticated_request(
82
+ method="GET",
83
+ divbase_base_url=divbase_url,
84
+ api_route=f"v1/task-history/tasks/{task_id}",
85
+ )
86
+ task_history_data = [TaskHistoryResult(**item) for item in task_history_response.json()]
87
+
88
+ TaskHistoryDisplayManager(
89
+ task_items=task_history_data,
90
+ user_email=None,
91
+ project_name=None,
92
+ mode="id",
93
+ format_output_as_tsv=format_output_as_tsv,
94
+ ).print_task_history()
95
+
96
+
97
+ @task_history_app.command("project")
98
+ def list_task_history_for_project(
99
+ project: str = typer.Argument(
100
+ None,
101
+ help="Project name to check the task history for. Leave blank to use the default project set in your config.",
102
+ ),
103
+ limit: int = typer.Option(10, help="Maximum number of tasks to display in the terminal. Sorted by recency."),
104
+ format_output_as_tsv: bool = FORMAT_AS_TSV_OPTION,
105
+ ):
106
+ """
107
+ Check status of all tasks submitted for a project. Requires a manager role in the project. Displays the latest 10 tasks by default, unless --limit is specified.
108
+ """
109
+ # TODO add option to sort ASC/DESC by task timestamp
110
+ project_config = resolve_and_authenticate_project(project_name=project)
111
+
112
+ task_history_response = make_authenticated_request(
113
+ method="GET",
114
+ divbase_base_url=project_config.divbase_url,
115
+ api_route=f"v1/task-history/projects/{project_config.name}",
116
+ )
117
+ task_history_data = [TaskHistoryResult(**item) for item in task_history_response.json()]
118
+
119
+ TaskHistoryDisplayManager(
120
+ task_items=task_history_data,
121
+ user_email=None,
122
+ project_name=project_config.name,
123
+ mode="project",
124
+ display_limit=limit,
125
+ format_output_as_tsv=format_output_as_tsv,
126
+ ).print_task_history()