divbase-cli 0.1.0.dev4__py3-none-any.whl → 0.1.1__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.
divbase_cli/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.1.0.dev4"
1
+ __version__ = "0.1.1"
@@ -3,44 +3,57 @@ CLI subcommand for managing user auth with DivBase server.
3
3
  """
4
4
 
5
5
  import logging
6
- from datetime import datetime
6
+ import time
7
7
 
8
8
  import typer
9
9
  from pydantic import SecretStr
10
- from typing_extensions import Annotated
10
+ from rich import print
11
11
 
12
12
  from divbase_cli.cli_config import cli_settings
13
- from divbase_cli.cli_exceptions import AuthenticationError, DivBaseAPIConnectionError, DivBaseAPIError
13
+ from divbase_cli.cli_exceptions import (
14
+ DivBaseAPIConnectionError,
15
+ DivBaseAPIError,
16
+ InvalidPersonalAccessTokenError,
17
+ PersonalAccessTokenAlreadyExistsError,
18
+ )
19
+ from divbase_cli.config_resolver import resolve_url_for_non_project_specific_commands
14
20
  from divbase_cli.services.announcements import get_and_display_announcements
15
21
  from divbase_cli.user_auth import (
22
+ PERSONAL_ACCESS_TOKEN_EXPIRED_MESSAGE,
23
+ PATData,
16
24
  check_existing_session,
25
+ delete_stored_pat,
26
+ load_stored_user_pat,
17
27
  login_to_divbase,
18
28
  logout_of_divbase,
19
29
  make_authenticated_request,
20
30
  )
21
31
  from divbase_cli.user_config import load_user_config
32
+ from divbase_lib.divbase_constants import PAT_TOKEN_PREFIX
33
+ from divbase_lib.utils import format_unix_timestamp_for_cli
22
34
 
23
35
  logger = logging.getLogger(__name__)
24
36
 
37
+ divbase_home_url = cli_settings.DIVBASE_API_URL.replace("/api", "")
38
+
25
39
  auth_app = typer.Typer(
26
- no_args_is_help=True, help="Login/logout of DivBase server. To register, visit https://divbase.scilifelab.se/."
40
+ no_args_is_help=True,
41
+ help=f"Log in/out of DivBase and manage your personal access tokens. To register, visit {divbase_home_url}.",
27
42
  )
28
43
 
29
44
 
30
45
  @auth_app.command("login")
31
46
  def login(
32
47
  email: str,
33
- password: Annotated[str, typer.Option(prompt=True, hide_input=True)],
34
48
  divbase_url: str = typer.Option(cli_settings.DIVBASE_API_URL, help="DivBase server URL to connect to."),
35
- force: bool = typer.Option(False, "--force", "-f", help="Force login again even if already logged in"),
49
+ force: bool = typer.Option(False, "--force", "-f", help="Log in again even if already logged in."),
36
50
  ):
37
51
  """
38
- Log in to the DivBase server.
52
+ Log in to DivBase.
39
53
 
40
- TODO - think abit more about already logged in validation and UX.
41
- One thing to consider would be use case of very close to refresh token expiry, that could be bad UX.
42
- (But that is dependent on whether we will allow renewal of refresh tokens...)
54
+ You'll be prompted for your password after running the command.
43
55
  """
56
+ password: str = typer.prompt("please enter your password", hide_input=True, confirmation_prompt=False)
44
57
  secret_password = SecretStr(password)
45
58
  del password # avoid user passwords showing up in error messages etc...
46
59
 
@@ -49,8 +62,8 @@ def login(
49
62
  if not force:
50
63
  session_expires_at = check_existing_session(divbase_url=divbase_url, config=config)
51
64
  if session_expires_at:
52
- print(f"Already logged in to {divbase_url}")
53
- print(f"Session expires: {datetime.fromtimestamp(session_expires_at)}")
65
+ print(f"Already logged in to {divbase_url} with email: {config.logged_in_email}.")
66
+ print(f"Session expires: {format_unix_timestamp_for_cli(unix_timestamp=session_expires_at)}")
54
67
 
55
68
  if not typer.confirm("Do you want to login again? This will replace your current session."):
56
69
  print("Login cancelled.")
@@ -62,7 +75,7 @@ def login(
62
75
  get_and_display_announcements(divbase_base_url=divbase_url)
63
76
  except (DivBaseAPIError, DivBaseAPIConnectionError):
64
77
  # 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)
78
+ logger.info("Failed to get announcements after login. Error was: ", exc_info=True)
66
79
 
67
80
  print(f"Logged in successfully as: {email}")
68
81
 
@@ -70,27 +83,104 @@ def login(
70
83
  @auth_app.command("logout")
71
84
  def logout():
72
85
  """
73
- Log out of the DivBase server.
86
+ Log out of DivBase.
87
+
88
+ Removes your locally stored credentials and invalidates the server-side refresh token.
74
89
  """
75
90
  logout_of_divbase()
76
91
  print("Logged out successfully.")
77
92
 
78
93
 
94
+ @auth_app.command("add-pat")
95
+ def add_pat(
96
+ name: str = typer.Argument(..., help="Name of the personal access token (PAT), e.g. 'work-laptop-pat'."),
97
+ expires_unix_timestamp: int | None = typer.Option(
98
+ None,
99
+ "--expires",
100
+ "-e",
101
+ help="When the personal access token (PAT) expires (if it does), as a Unix timestamp.",
102
+ min=1,
103
+ ),
104
+ overwrite_existing: bool = typer.Option(
105
+ False, "--overwrite-existing", "-o", help="Overwrite the existing stored PAT if one already exists."
106
+ ),
107
+ ):
108
+ """
109
+ Add a personal access token (PAT) to your device for authentication with DivBase.
110
+
111
+ PATs are used for authenticating with DivBase instead of using your password, and are recommended for use in scripts and pipelines.
112
+ See https://scilifelabdatacentre.github.io/divbase/user-guides/using-divbase-programmatically/ for more details on how to create a personal access token.
113
+ You can only store one personal access token at a time.
114
+ """
115
+ existing = load_stored_user_pat()
116
+ if existing and not overwrite_existing:
117
+ raise PersonalAccessTokenAlreadyExistsError(
118
+ f"A personal access token named '{existing.name}' is already stored on your device \n"
119
+ f"It is due to expire on: {existing.pat_expiry_formatted()} \n"
120
+ "Append the flag --overwrite-existing (-o) to this command if you want to replace it. \n"
121
+ "You can only store one PAT at a time."
122
+ )
123
+
124
+ if expires_unix_timestamp and expires_unix_timestamp < time.time():
125
+ raise InvalidPersonalAccessTokenError(
126
+ "The expiry time you entered is in the past. Please enter a valid expiry time for the PAT."
127
+ )
128
+
129
+ pat = SecretStr(
130
+ typer.prompt("please paste your personal access token now", hide_input=True, confirmation_prompt=False)
131
+ )
132
+ if not pat.get_secret_value().startswith(PAT_TOKEN_PREFIX):
133
+ raise InvalidPersonalAccessTokenError(
134
+ "It looks like the token you entered is not a valid personal access token. "
135
+ f"Please make sure you copied the entire token, including the '{PAT_TOKEN_PREFIX}' prefix."
136
+ )
137
+
138
+ pat_data = PATData(name=name, pat=pat, pat_expires_at=expires_unix_timestamp)
139
+ pat_data.dump_pat_data()
140
+ print(f"Personal access token '{name}' stored successfully.")
141
+
142
+
143
+ @auth_app.command("rm-pat")
144
+ def rm_pat():
145
+ """
146
+ Remove the stored personal access token from your device.
147
+
148
+ If no such token exists the command will still succeed.
149
+ """
150
+ delete_stored_pat()
151
+ print("If a personal access token was stored, it has now been removed.")
152
+
153
+
154
+ @auth_app.command("pat-info")
155
+ def pat_info():
156
+ """
157
+ Display information about the personal access token stored on this device, if any.
158
+
159
+ The token will not be displayed for security reasons, but the name and expiry time will be shown.
160
+ """
161
+ pat_data = load_stored_user_pat()
162
+ if not pat_data:
163
+ print("No personal access token stored on this device.")
164
+ return
165
+
166
+ print(f"Name: {pat_data.name}")
167
+ print(f"Expires: {pat_data.pat_expiry_formatted()}")
168
+
169
+ if pat_data.is_pat_expired():
170
+ print("[red bold]Warning [/red bold]")
171
+ print(PERSONAL_ACCESS_TOKEN_EXPIRED_MESSAGE)
172
+
173
+
79
174
  @auth_app.command("whoami")
80
175
  def whoami():
81
176
  """
82
- Return information about the currently logged-in user.
177
+ Show information about the account you are currently logged in with.
83
178
  """
84
- config = load_user_config()
85
- logged_in_url = config.logged_in_url
86
-
87
- # TODO - move logged in check to the make_authenticated_request function?
88
- if not logged_in_url:
89
- raise AuthenticationError("You are not logged in. Please log in with 'divbase-cli auth login [EMAIL]'.")
179
+ divbase_url = resolve_url_for_non_project_specific_commands()
90
180
 
91
181
  request = make_authenticated_request(
92
182
  method="GET",
93
- divbase_base_url=logged_in_url,
183
+ divbase_base_url=divbase_url,
94
184
  api_route="v1/auth/whoami",
95
185
  )
96
186
 
@@ -1,27 +1,32 @@
1
1
  import csv
2
2
  import logging
3
+ from datetime import datetime
3
4
  from pathlib import Path
4
5
 
5
6
  import typer
6
7
  import yaml
7
8
  from rich import print
9
+ from rich.table import Table
8
10
 
9
11
  from divbase_cli.cli_commands.shared_args_options import PROJECT_NAME_OPTION
10
- from divbase_cli.config_resolver import resolve_project
12
+ from divbase_cli.config_resolver import resolve_and_authenticate_project
11
13
  from divbase_cli.user_auth import make_authenticated_request
14
+ from divbase_cli.utils import print_rich_table_as_tsv
12
15
  from divbase_lib.api_schemas.vcf_dimensions import (
13
16
  DimensionsSamplesResult,
14
17
  DimensionsScaffoldsResult,
15
18
  DimensionsShowResult,
19
+ DimensionsVCFFilesResult,
16
20
  )
17
21
  from divbase_lib.metadata_validator import SharedMetadataValidator
22
+ from divbase_lib.utils import format_datetime_for_cli
18
23
 
19
24
  logger = logging.getLogger(__name__)
20
25
 
21
26
 
22
27
  dimensions_app = typer.Typer(
23
28
  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",
29
+ help="Create and inspect dimensions (number of samples, number of variants, scaffold names) of the VCF files in a project, and create/validate sample metadata files.",
25
30
  )
26
31
 
27
32
 
@@ -29,10 +34,8 @@ dimensions_app = typer.Typer(
29
34
  def update_dimensions_index(
30
35
  project: str | None = PROJECT_NAME_OPTION,
31
36
  ) -> 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
-
37
+ """Calculate and add the dimensions of all VCF files in the project to the dimensions cache in the project."""
38
+ project_config = resolve_and_authenticate_project(project_name=project)
36
39
  response = make_authenticated_request(
37
40
  method="PUT",
38
41
  divbase_base_url=project_config.divbase_url,
@@ -40,7 +43,9 @@ def update_dimensions_index(
40
43
  )
41
44
 
42
45
  task_id = response.json()
43
- print(f"Job submitted successfully with task id: {task_id}")
46
+ print(
47
+ 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}"
48
+ )
44
49
 
45
50
 
46
51
  @dimensions_app.command("show")
@@ -54,14 +59,21 @@ def show_dimensions_index(
54
59
  typer.Option(
55
60
  False,
56
61
  "--unique-scaffolds",
57
- help="If set, will show all unique scaffold names found across all the VCF files in the project.",
62
+ help="If set, will show all unique scaffold names found across all the VCF files in the project's VCF dimensions cache.",
58
63
  )
59
64
  ),
60
65
  unique_samples: bool = (
61
66
  typer.Option(
62
67
  False,
63
68
  "--unique-samples",
64
- help="If set, will show all unique sample names found across all the VCF files in the project.",
69
+ help="If set, will show all unique sample names found across all the VCF files in the project's VCF dimensions cache.",
70
+ )
71
+ ),
72
+ unique_vcf_files: bool = (
73
+ typer.Option(
74
+ False,
75
+ "--cached-vcf-files",
76
+ help="If set, will show all VCF file entries (filename and version ID) found in the project's VCF dimensions cache.",
65
77
  )
66
78
  ),
67
79
  sample_names_limit: int = typer.Option(
@@ -84,18 +96,13 @@ def show_dimensions_index(
84
96
  project: str | None = PROJECT_NAME_OPTION,
85
97
  ) -> None:
86
98
  """
87
- Show the dimensions index file for a project.
99
+ Show the dimensions cache file for a project.
88
100
  When running --unique-scaffolds, the sorting separates between numeric and non-numeric scaffold names.
89
101
  """
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
102
  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)
103
+ raise typer.BadParameter("Use only one of --sample-names-output or --sample-names-stdout.")
98
104
 
105
+ project_config = resolve_and_authenticate_project(project_name=project)
99
106
  if unique_samples:
100
107
  response = make_authenticated_request(
101
108
  method="GET",
@@ -141,6 +148,28 @@ def show_dimensions_index(
141
148
  )
142
149
  return
143
150
 
151
+ if unique_vcf_files:
152
+ response = make_authenticated_request(
153
+ method="GET",
154
+ divbase_base_url=project_config.divbase_url,
155
+ api_route=f"v1/vcf-dimensions/projects/{project_config.name}/vcf-files",
156
+ )
157
+ unique_vcf_files_with_versions = DimensionsVCFFilesResult(**response.json()).unique_vcf_files
158
+ unique_vcf_files_with_versions = sorted(
159
+ unique_vcf_files_with_versions,
160
+ key=lambda entry: entry.vcf_file_s3_key,
161
+ )
162
+
163
+ table = Table()
164
+ table.add_column("Filename")
165
+ table.add_column("S3 version ID")
166
+
167
+ for entry in unique_vcf_files_with_versions:
168
+ table.add_row(entry.vcf_file_s3_key, entry.s3_version_id)
169
+
170
+ print_rich_table_as_tsv(table=table)
171
+ return
172
+
144
173
  response = make_authenticated_request(
145
174
  method="GET",
146
175
  divbase_base_url=project_config.divbase_url,
@@ -205,7 +234,7 @@ def _format_api_response_for_display_in_terminal(api_response: DimensionsShowRes
205
234
  dimensions_entry = {
206
235
  "filename": entry["vcf_file_s3_key"],
207
236
  "file_version_ID_in_bucket": entry["s3_version_id"],
208
- "last_updated": entry.get("updated_at"),
237
+ "last_updated": format_datetime_for_cli(datetime.fromisoformat(entry["updated_at"])),
209
238
  "dimensions": {
210
239
  "scaffold_count": len(sorted_scaffolds),
211
240
  "scaffolds": sorted_scaffolds,
@@ -245,14 +274,9 @@ def create_metadata_template_with_project_samples_names(
245
274
  project: str | None = PROJECT_NAME_OPTION,
246
275
  ) -> None:
247
276
  """
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.
277
+ 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 are up-to-date.
249
278
  """
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
-
279
+ project_config = resolve_and_authenticate_project(project_name=project)
256
280
  response = make_authenticated_request(
257
281
  method="GET",
258
282
  divbase_base_url=project_config.divbase_url,
@@ -266,12 +290,14 @@ def create_metadata_template_with_project_samples_names(
266
290
  )
267
291
 
268
292
  if sample_count == 0:
269
- # Fallback in case there are no samples in the dimensions index. If no dimensions entry for the project
293
+ # Fallback in case there are no samples in the dimensions cache. If no dimensions entry for the project
270
294
  # VCFDimensionsEntryMissingError will be returned. But for some reason, there are no samples in the VCF, this will catch that.
271
295
  print("No samples found for this project. No file written.")
272
296
  return
273
297
 
274
- # Check if file exists and prompt user for confirmation
298
+ if output_path is None:
299
+ output_path = Path.cwd() / f"sample_metadata_{project_config.name}.tsv"
300
+
275
301
  if output_path.exists():
276
302
  overwrite = typer.confirm(f"File '{output_path}' already exists. Do you want to overwrite it?")
277
303
  if not overwrite:
@@ -311,10 +337,8 @@ def validate_metadata_template_versus_dimensions_and_formatting_constraints(
311
337
  """
312
338
  # Client-side validation of a sidecar metadata TSV file, intended to be run before upload to DivBase.
313
339
  # 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
-
340
+ # in the TSV file match the sample names in the dimensions cache for the project
341
+ project_config = resolve_and_authenticate_project(project_name=project)
318
342
  print(f"Validating local metadata file: {input_path}")
319
343
  print(f"Project: {project_config.name}\n")
320
344
 
@@ -388,7 +412,8 @@ def validate_metadata_template_versus_dimensions_and_formatting_constraints(
388
412
 
389
413
  if not errors and not warnings:
390
414
  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'"
415
+ "[green bold]Validation passed![/green bold] The metadata file meets all DivBase requirements. "
416
+ f"The file is ready to be uploaded to your DivBase project with the command:\n 'divbase-cli files upload {input_path}'"
392
417
  )
393
418
  elif errors:
394
419
  print("[red bold]Validation failed![/red bold] Please fix the errors above before uploading.")
@@ -396,8 +421,6 @@ def validate_metadata_template_versus_dimensions_and_formatting_constraints(
396
421
  else:
397
422
  print("[yellow bold]Validation passed with warnings![/yellow bold] Review the warnings above.")
398
423
 
399
- # TODO: Add information about how to upload the validated metadata file to DivBase
400
-
401
424
 
402
425
  def _truncate_sample_names_in_entry(entry: dict, sample_names_limit: int) -> None:
403
426
  """