das-cli 1.5.271__tar.gz → 1.6.0__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 (43) hide show
  1. {das_cli-1.5.271/das_cli.egg-info → das_cli-1.6.0}/PKG-INFO +89 -4
  2. {das_cli-1.5.271 → das_cli-1.6.0}/README.md +89 -4
  3. {das_cli-1.5.271 → das_cli-1.6.0}/das/authentication/auth.py +23 -5
  4. {das_cli-1.5.271 → das_cli-1.6.0}/das/cli.py +64 -5
  5. das_cli-1.6.0/das/common/api.py +177 -0
  6. {das_cli-1.5.271 → das_cli-1.6.0}/das/common/config.py +188 -2
  7. {das_cli-1.5.271 → das_cli-1.6.0}/das/common/enums.py +14 -0
  8. das_cli-1.6.0/das/common/errors.py +93 -0
  9. {das_cli-1.5.271 → das_cli-1.6.0}/das/managers/digital_objects_manager.py +81 -15
  10. {das_cli-1.5.271 → das_cli-1.6.0}/das/managers/entries_manager.py +78 -21
  11. {das_cli-1.5.271 → das_cli-1.6.0}/das/managers/search_manager.py +30 -6
  12. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/attributes.py +4 -3
  13. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/cache.py +4 -3
  14. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/das_elastic_search.py +2 -5
  15. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/digital_objects.py +59 -30
  16. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/downloads.py +4 -6
  17. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/entries.py +2 -9
  18. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/entry_fields.py +2 -5
  19. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/hangfire.py +2 -1
  20. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/search.py +2 -4
  21. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/users.py +2 -1
  22. {das_cli-1.5.271 → das_cli-1.6.0/das_cli.egg-info}/PKG-INFO +89 -4
  23. {das_cli-1.5.271 → das_cli-1.6.0}/das_cli.egg-info/SOURCES.txt +1 -0
  24. {das_cli-1.5.271 → das_cli-1.6.0}/pyproject.toml +1 -1
  25. das_cli-1.5.271/das/common/api.py +0 -120
  26. {das_cli-1.5.271 → das_cli-1.6.0}/LICENSE +0 -0
  27. {das_cli-1.5.271 → das_cli-1.6.0}/MANIFEST.in +0 -0
  28. {das_cli-1.5.271 → das_cli-1.6.0}/das/__init__.py +0 -0
  29. {das_cli-1.5.271 → das_cli-1.6.0}/das/ai/plugins/dasai.py +0 -0
  30. {das_cli-1.5.271 → das_cli-1.6.0}/das/ai/plugins/entries/entries_plugin.py +0 -0
  31. {das_cli-1.5.271 → das_cli-1.6.0}/das/app.py +0 -0
  32. {das_cli-1.5.271 → das_cli-1.6.0}/das/authentication/oauth.py +0 -0
  33. {das_cli-1.5.271 → das_cli-1.6.0}/das/authentication/secure_input.py +0 -0
  34. {das_cli-1.5.271 → das_cli-1.6.0}/das/common/entry_fields_constants.py +0 -0
  35. {das_cli-1.5.271 → das_cli-1.6.0}/das/common/file_utils.py +0 -0
  36. {das_cli-1.5.271 → das_cli-1.6.0}/das/managers/__init__.py +0 -0
  37. {das_cli-1.5.271 → das_cli-1.6.0}/das/managers/download_manager.py +0 -0
  38. {das_cli-1.5.271 → das_cli-1.6.0}/das/services/service_base.py +0 -0
  39. {das_cli-1.5.271 → das_cli-1.6.0}/das_cli.egg-info/dependency_links.txt +0 -0
  40. {das_cli-1.5.271 → das_cli-1.6.0}/das_cli.egg-info/entry_points.txt +0 -0
  41. {das_cli-1.5.271 → das_cli-1.6.0}/das_cli.egg-info/requires.txt +0 -0
  42. {das_cli-1.5.271 → das_cli-1.6.0}/das_cli.egg-info/top_level.txt +0 -0
  43. {das_cli-1.5.271 → das_cli-1.6.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: das-cli
3
- Version: 1.5.271
3
+ Version: 1.6.0
4
4
  Summary: DAS api client.
5
5
  Author: Royal Netherlands Institute for Sea Research
6
6
  License-Expression: MIT
@@ -28,9 +28,9 @@ Dynamic: license-file
28
28
  - a Python package for scripts, automations, and integrations.
29
29
 
30
30
  This README is organized around how people actually use the project:
31
- 1. [CLI workflows](#cli-usage)
32
- 2. [Programmatic workflows](#programmatic-usage-python)
33
- 3. [Manager-layer API reference with examples](#manager-layer-api-reference-domain-layer) — all methods of `EntryManager`, `SearchManager`, `DownloadManager`, and `DigitalObjectsManager`
31
+ 1. [CLI workflows](#cli-usage) — [Authentication](#authentication) · [Search and Read](#search-and-read) · [Entries](#entries) · [Digital Objects](#digital-objects) · [Downloads](#downloads) · [Other CLI groups](#other-cli-groups)
32
+ 2. [Programmatic workflows](#programmatic-usage-python) — [Pattern A](#pattern-a-login-once-with-cli-then-use-managers-in-python) · [Pattern B](#pattern-b-authenticate-in-python-with-das)
33
+ 3. [Manager-layer API reference](#manager-layer-api-reference-domain-layer) — [`EntryManager`](#entrymanager) · [`SearchManager`](#searchmanager) · [`DownloadManager`](#downloadmanager) · [`DigitalObjectsManager`](#digitalobjectsmanager)
34
34
 
35
35
  ## Install
36
36
 
@@ -67,6 +67,20 @@ das entry get --code zb.b.1ub
67
67
 
68
68
  ## CLI Usage
69
69
 
70
+ - [Authentication](#authentication)
71
+ - [Username/password](#usernamepassword)
72
+ - [API key](#api-key)
73
+ - [OAuth / Azure Entra](#oauth--azure-entra)
74
+ - [Search and Read](#search-and-read)
75
+ - [Entries](#entries)
76
+ - [Create entries](#create-entries)
77
+ - [Update entries](#update-entries)
78
+ - [Logs and ownership](#logs-and-ownership)
79
+ - [Digital Objects](#digital-objects)
80
+ - [Downloads](#downloads)
81
+ - [Other CLI groups](#other-cli-groups)
82
+ - [Logging](#logging)
83
+
70
84
  ### Authentication
71
85
 
72
86
  #### Username/password
@@ -201,12 +215,49 @@ das config ssl-verify true
201
215
  das config ssl-status
202
216
  das config show
203
217
  das config reset --force
218
+
219
+ # Logging
220
+ das config log-level DEBUG # TRACE, DEBUG, INFO, WARN (default), ERROR, FATAL
221
+ das config log-file C:\logs\das.log # also write logs to a file
222
+ das config log-file --clear # back to console only
223
+ ```
224
+
225
+ #### Logging
226
+
227
+ The CLI logs diagnostics (HTTP requests and error details) through the `das`
228
+ logger. Control how much is shown and where it goes:
229
+
230
+ - **Level** — from most to least verbose: `TRACE`, `DEBUG`, `INFO`, `WARN`
231
+ (default), `ERROR`, `FATAL`. Set with `das config log-level <LEVEL>` or the
232
+ `DAS_LOG_LEVEL` environment variable.
233
+ - **Destination** — logs go to the console by default. Also write them to a file
234
+ with `das config log-file <path>` (parent folders are created automatically)
235
+ or the `DAS_LOG_FILE` environment variable; use `das config log-file --clear`
236
+ to go back to console-only. The file log includes timestamps and logger names
237
+ while the console stays terse.
238
+
239
+ ```bash
240
+ # Verbose troubleshooting session written to a file
241
+ das config log-level DEBUG
242
+ das config log-file C:\logs\das.log
243
+ das search entries --attribute Cruise --query "cruisecode(*64PE*)"
204
244
  ```
205
245
 
246
+ > Tip: this is the diagnostic log for the CLI itself. For an entry's
247
+ > change/audit history, use [`das entry logs`](#logs-and-ownership) instead.
248
+
206
249
  ## Programmatic Usage (Python)
207
250
 
208
251
  Two common patterns are supported.
209
252
 
253
+ - [Pattern A: login once with CLI, then use managers in Python](#pattern-a-login-once-with-cli-then-use-managers-in-python)
254
+ - [Pattern B: authenticate in Python with `Das`](#pattern-b-authenticate-in-python-with-das)
255
+ - Managers — full API reference below:
256
+ - [`EntryManager`](#entrymanager)
257
+ - [`SearchManager`](#searchmanager)
258
+ - [`DownloadManager`](#downloadmanager)
259
+ - [`DigitalObjectsManager`](#digitalobjectsmanager)
260
+
210
261
  ### Pattern A: login once with CLI, then use managers in Python
211
262
 
212
263
  ```python
@@ -253,6 +304,30 @@ entries = EntryManager() # reads API URL + token from stored config
253
304
 
254
305
  All managers raise `ValueError` when the API URL is not configured or when required parameters are missing.
255
306
 
307
+ - [`EntryManager`](#entrymanager)
308
+ - [`get` / `get_entry`](#get--get_entry--fetch-one-entry)
309
+ - [`create`](#create--create-one-or-many-entries)
310
+ - [`update`](#update--update-one-or-many-entries)
311
+ - [`delete`](#delete--delete-one-entry)
312
+ - [`create_from_file`](#create_from_file--bulk-create-from-file)
313
+ - [`chown`](#chown--transfer-ownership)
314
+ - [`get_entry_logs`](#get_entry_logs--audit--change-history)
315
+ - [`get_direct_relations`](#get_direct_relations--related-entries)
316
+ - [`SearchManager`](#searchmanager)
317
+ - [`search_entries`](#search_entries--search-within-an-attribute)
318
+ - [`DownloadManager`](#downloadmanager)
319
+ - [`create_download_request`](#create_download_request--request-files-for-download)
320
+ - [`get_my_requests`](#get_my_requests--list-your-download-requests)
321
+ - [`delete_download_request`](#delete_download_request--remove-a-request)
322
+ - [`download_files`](#download_files--get-streaming-response)
323
+ - [`save_download`](#save_download--download-and-save-in-one-step)
324
+ - [`DigitalObjectsManager`](#digitalobjectsmanager)
325
+ - [`upload_digital_object`](#upload_digital_object--upload-file-and-link-to-entry)
326
+ - [`link_existing_digital_objects`](#link_existing_digital_objects--link-or-unlink-by-codes)
327
+ - [`download_digital_object`](#download_digital_object--download-by-digital-object-code-or-id)
328
+ - [`direct_download_digital_object`](#direct_download_digital_object--download-from-a-specific-entry)
329
+ - [Complete end-to-end script](#complete-end-to-end-script)
330
+
256
331
  ---
257
332
 
258
333
  ### `EntryManager`
@@ -729,6 +804,10 @@ DAS_API_URL=https://api.das-dev.nioz.nl
729
804
  DAS_API_KEY=
730
805
  VERIFY_SSL=True
731
806
 
807
+ # Logging
808
+ DAS_LOG_LEVEL=WARN
809
+ DAS_LOG_FILE=
810
+
732
811
  # Test credentials (for integration tests)
733
812
  API_URL=https://api.das-dev.nioz.nl
734
813
  USER_NAME=
@@ -742,6 +821,8 @@ OPEN_AI_MODEL_ID=gpt-4o-mini
742
821
  - `DAS_API_URL`: default API URL for app/managers when no explicit URL is provided.
743
822
  - `DAS_API_KEY`: API key auth (takes precedence over stored token in auth layer).
744
823
  - `VERIFY_SSL`: TLS verification (`True`/`False`).
824
+ - `DAS_LOG_LEVEL`: diagnostic log level (`TRACE`/`DEBUG`/`INFO`/`WARN`/`ERROR`/`FATAL`); overrides `das config log-level`.
825
+ - `DAS_LOG_FILE`: path to also write logs to a file; overrides `das config log-file`.
745
826
  - `API_URL`, `USER_NAME`, `USER_PASSWORD`: used by integration tests.
746
827
 
747
828
  ## Unit Tests and Integration Tests
@@ -775,6 +856,10 @@ The tests are a good source of realistic payload examples, especially:
775
856
  - prefer double quotes around query arguments containing `*`, `;`, and parentheses.
776
857
  - No API URL configured:
777
858
  - set `DAS_API_URL`, pass URL to `Das(...)`, or run `das login --api-url ...`.
859
+ - Need more detail on any error:
860
+ - raise verbosity with `das config log-level DEBUG` (optionally
861
+ `das config log-file <path>`) to see the full HTTP requests and error
862
+ details. See [Logging](#logging).
778
863
 
779
864
  ## Contributing
780
865
 
@@ -5,9 +5,9 @@
5
5
  - a Python package for scripts, automations, and integrations.
6
6
 
7
7
  This README is organized around how people actually use the project:
8
- 1. [CLI workflows](#cli-usage)
9
- 2. [Programmatic workflows](#programmatic-usage-python)
10
- 3. [Manager-layer API reference with examples](#manager-layer-api-reference-domain-layer) — all methods of `EntryManager`, `SearchManager`, `DownloadManager`, and `DigitalObjectsManager`
8
+ 1. [CLI workflows](#cli-usage) — [Authentication](#authentication) · [Search and Read](#search-and-read) · [Entries](#entries) · [Digital Objects](#digital-objects) · [Downloads](#downloads) · [Other CLI groups](#other-cli-groups)
9
+ 2. [Programmatic workflows](#programmatic-usage-python) — [Pattern A](#pattern-a-login-once-with-cli-then-use-managers-in-python) · [Pattern B](#pattern-b-authenticate-in-python-with-das)
10
+ 3. [Manager-layer API reference](#manager-layer-api-reference-domain-layer) — [`EntryManager`](#entrymanager) · [`SearchManager`](#searchmanager) · [`DownloadManager`](#downloadmanager) · [`DigitalObjectsManager`](#digitalobjectsmanager)
11
11
 
12
12
  ## Install
13
13
 
@@ -44,6 +44,20 @@ das entry get --code zb.b.1ub
44
44
 
45
45
  ## CLI Usage
46
46
 
47
+ - [Authentication](#authentication)
48
+ - [Username/password](#usernamepassword)
49
+ - [API key](#api-key)
50
+ - [OAuth / Azure Entra](#oauth--azure-entra)
51
+ - [Search and Read](#search-and-read)
52
+ - [Entries](#entries)
53
+ - [Create entries](#create-entries)
54
+ - [Update entries](#update-entries)
55
+ - [Logs and ownership](#logs-and-ownership)
56
+ - [Digital Objects](#digital-objects)
57
+ - [Downloads](#downloads)
58
+ - [Other CLI groups](#other-cli-groups)
59
+ - [Logging](#logging)
60
+
47
61
  ### Authentication
48
62
 
49
63
  #### Username/password
@@ -178,12 +192,49 @@ das config ssl-verify true
178
192
  das config ssl-status
179
193
  das config show
180
194
  das config reset --force
195
+
196
+ # Logging
197
+ das config log-level DEBUG # TRACE, DEBUG, INFO, WARN (default), ERROR, FATAL
198
+ das config log-file C:\logs\das.log # also write logs to a file
199
+ das config log-file --clear # back to console only
200
+ ```
201
+
202
+ #### Logging
203
+
204
+ The CLI logs diagnostics (HTTP requests and error details) through the `das`
205
+ logger. Control how much is shown and where it goes:
206
+
207
+ - **Level** — from most to least verbose: `TRACE`, `DEBUG`, `INFO`, `WARN`
208
+ (default), `ERROR`, `FATAL`. Set with `das config log-level <LEVEL>` or the
209
+ `DAS_LOG_LEVEL` environment variable.
210
+ - **Destination** — logs go to the console by default. Also write them to a file
211
+ with `das config log-file <path>` (parent folders are created automatically)
212
+ or the `DAS_LOG_FILE` environment variable; use `das config log-file --clear`
213
+ to go back to console-only. The file log includes timestamps and logger names
214
+ while the console stays terse.
215
+
216
+ ```bash
217
+ # Verbose troubleshooting session written to a file
218
+ das config log-level DEBUG
219
+ das config log-file C:\logs\das.log
220
+ das search entries --attribute Cruise --query "cruisecode(*64PE*)"
181
221
  ```
182
222
 
223
+ > Tip: this is the diagnostic log for the CLI itself. For an entry's
224
+ > change/audit history, use [`das entry logs`](#logs-and-ownership) instead.
225
+
183
226
  ## Programmatic Usage (Python)
184
227
 
185
228
  Two common patterns are supported.
186
229
 
230
+ - [Pattern A: login once with CLI, then use managers in Python](#pattern-a-login-once-with-cli-then-use-managers-in-python)
231
+ - [Pattern B: authenticate in Python with `Das`](#pattern-b-authenticate-in-python-with-das)
232
+ - Managers — full API reference below:
233
+ - [`EntryManager`](#entrymanager)
234
+ - [`SearchManager`](#searchmanager)
235
+ - [`DownloadManager`](#downloadmanager)
236
+ - [`DigitalObjectsManager`](#digitalobjectsmanager)
237
+
187
238
  ### Pattern A: login once with CLI, then use managers in Python
188
239
 
189
240
  ```python
@@ -230,6 +281,30 @@ entries = EntryManager() # reads API URL + token from stored config
230
281
 
231
282
  All managers raise `ValueError` when the API URL is not configured or when required parameters are missing.
232
283
 
284
+ - [`EntryManager`](#entrymanager)
285
+ - [`get` / `get_entry`](#get--get_entry--fetch-one-entry)
286
+ - [`create`](#create--create-one-or-many-entries)
287
+ - [`update`](#update--update-one-or-many-entries)
288
+ - [`delete`](#delete--delete-one-entry)
289
+ - [`create_from_file`](#create_from_file--bulk-create-from-file)
290
+ - [`chown`](#chown--transfer-ownership)
291
+ - [`get_entry_logs`](#get_entry_logs--audit--change-history)
292
+ - [`get_direct_relations`](#get_direct_relations--related-entries)
293
+ - [`SearchManager`](#searchmanager)
294
+ - [`search_entries`](#search_entries--search-within-an-attribute)
295
+ - [`DownloadManager`](#downloadmanager)
296
+ - [`create_download_request`](#create_download_request--request-files-for-download)
297
+ - [`get_my_requests`](#get_my_requests--list-your-download-requests)
298
+ - [`delete_download_request`](#delete_download_request--remove-a-request)
299
+ - [`download_files`](#download_files--get-streaming-response)
300
+ - [`save_download`](#save_download--download-and-save-in-one-step)
301
+ - [`DigitalObjectsManager`](#digitalobjectsmanager)
302
+ - [`upload_digital_object`](#upload_digital_object--upload-file-and-link-to-entry)
303
+ - [`link_existing_digital_objects`](#link_existing_digital_objects--link-or-unlink-by-codes)
304
+ - [`download_digital_object`](#download_digital_object--download-by-digital-object-code-or-id)
305
+ - [`direct_download_digital_object`](#direct_download_digital_object--download-from-a-specific-entry)
306
+ - [Complete end-to-end script](#complete-end-to-end-script)
307
+
233
308
  ---
234
309
 
235
310
  ### `EntryManager`
@@ -706,6 +781,10 @@ DAS_API_URL=https://api.das-dev.nioz.nl
706
781
  DAS_API_KEY=
707
782
  VERIFY_SSL=True
708
783
 
784
+ # Logging
785
+ DAS_LOG_LEVEL=WARN
786
+ DAS_LOG_FILE=
787
+
709
788
  # Test credentials (for integration tests)
710
789
  API_URL=https://api.das-dev.nioz.nl
711
790
  USER_NAME=
@@ -719,6 +798,8 @@ OPEN_AI_MODEL_ID=gpt-4o-mini
719
798
  - `DAS_API_URL`: default API URL for app/managers when no explicit URL is provided.
720
799
  - `DAS_API_KEY`: API key auth (takes precedence over stored token in auth layer).
721
800
  - `VERIFY_SSL`: TLS verification (`True`/`False`).
801
+ - `DAS_LOG_LEVEL`: diagnostic log level (`TRACE`/`DEBUG`/`INFO`/`WARN`/`ERROR`/`FATAL`); overrides `das config log-level`.
802
+ - `DAS_LOG_FILE`: path to also write logs to a file; overrides `das config log-file`.
722
803
  - `API_URL`, `USER_NAME`, `USER_PASSWORD`: used by integration tests.
723
804
 
724
805
  ## Unit Tests and Integration Tests
@@ -752,6 +833,10 @@ The tests are a good source of realistic payload examples, especially:
752
833
  - prefer double quotes around query arguments containing `*`, `;`, and parentheses.
753
834
  - No API URL configured:
754
835
  - set `DAS_API_URL`, pass URL to `Das(...)`, or run `das login --api-url ...`.
836
+ - Need more detail on any error:
837
+ - raise verbosity with `das config log-level DEBUG` (optionally
838
+ `das config log-file <path>`) to see the full HTTP requests and error
839
+ details. See [Logging](#logging).
755
840
 
756
841
  ## Contributing
757
842
 
@@ -762,4 +847,4 @@ For bugs or feature requests, use the project issue tracker:
762
847
 
763
848
  ## License
764
849
 
765
- MIT License
850
+ MIT License
@@ -1,5 +1,6 @@
1
1
  from das.common.api import post_data
2
2
  from das.common.config import save_token
3
+ from das.common.errors import extract_api_error
3
4
 
4
5
 
5
6
  class Auth:
@@ -15,9 +16,18 @@ class Auth:
15
16
  def authenticate(self, password):
16
17
  """
17
18
  Authenticate the user and obtain an access token.
18
-
19
+
19
20
  Args:
20
21
  password (str): The password to authenticate with
22
+
23
+ Returns:
24
+ str: The access token on success.
25
+
26
+ Raises:
27
+ ValueError: With a descriptive message when authentication fails —
28
+ distinguishing bad credentials (the API's message) from
29
+ connection-level problems such as an untrusted TLS certificate
30
+ or an unreachable host.
21
31
  """
22
32
  url = f"{self.base_url}/api/TokenAuth/Authenticate"
23
33
  data = {
@@ -25,14 +35,22 @@ class Auth:
25
35
  "password": password
26
36
  }
27
37
  response = post_data(url, data=data)
28
- if response.get("error"):
29
- print(f"Authentication failed: {response['error']}")
30
- else:
31
- self.token = response.get("result").get("accessToken")
38
+
39
+ if not isinstance(response, dict):
40
+ raise ValueError("Unexpected response from the authentication endpoint.")
41
+
42
+ result = response.get("result") if response.get("success") is True else None
43
+ token = result.get("accessToken") if isinstance(result, dict) else None
44
+
45
+ if token:
46
+ self.token = token
32
47
  save_token(self.token)
33
48
  # Return silently, let the CLI handle success messages
34
49
  return self.token
35
50
 
51
+ # Failure: surface the real reason (API message, SSL/cert or connection error).
52
+ raise ValueError(extract_api_error(response, "Authentication failed."))
53
+
36
54
  if __name__ == "__main__":
37
55
  # Example for testing authentication
38
56
  import getpass
@@ -9,8 +9,10 @@ from das.common.config import (
9
9
  load_openai_api_key, save_openai_api_key, clear_openai_api_key,
10
10
  clear_token, _config_dir,
11
11
  save_oauth_config, load_oauth_config, get_auth_type, set_auth_type,
12
- save_token, save_token_expiry, save_refresh_token, clear_refresh_token
12
+ save_token, save_token_expiry, save_refresh_token, clear_refresh_token,
13
+ save_log_level, load_log_level, save_log_file, load_log_file, configure_logging,
13
14
  )
15
+ from das.common.enums import LogLevel
14
16
 
15
17
  from das.app import Das
16
18
  from das.managers.download_manager import DownloadManager
@@ -166,8 +168,13 @@ def login(das_ctx, api_url, username, password, use_oauth, api_key, debug):
166
168
  if not password:
167
169
  password = click.prompt("Password", hide_input=True)
168
170
 
169
- client = das_ctx.get_client()
170
- token = client.authenticate(username, password)
171
+ try:
172
+ client = das_ctx.get_client()
173
+ token = client.authenticate(username, password)
174
+ except Exception as e:
175
+ click.secho(f"❌ Authentication failed: {e}", fg="red")
176
+ return
177
+
171
178
  if not token:
172
179
  click.secho("❌ Authentication failed. Please check your credentials.", fg="red")
173
180
  return
@@ -273,7 +280,8 @@ def search_help():
273
280
  click.echo(" --max-results <n> Number of results per page (default: 10)")
274
281
 
275
282
  click.secho("\nSorting:", fg="blue", bold=True)
276
- click.echo(" --sort-by <field> Field to sort by (default: Name)")
283
+ click.echo(" --sort-by <field> Field to sort by (default: none — the server decides the order)")
284
+ click.echo(" Note: not every attribute has a 'Name' field (e.g. Cruise).")
277
285
  click.echo(" --sort-order <order> Sort order: 'asc' or 'desc' (default: asc)")
278
286
  click.echo("\n")
279
287
 
@@ -282,7 +290,7 @@ def search_help():
282
290
  @click.option('--query', required=True, help='Search query string')
283
291
  @click.option('--max-results', default=10, help='Maximum number of results to return')
284
292
  @click.option('--page', default=1, help='Page number for paginated results')
285
- @click.option('--sort-by', default='Name', help='Field to sort by (default: Name)')
293
+ @click.option('--sort-by', default='', help='Field to sort by (default: none — the server decides the order)')
286
294
  @click.option('--sort-order', default='asc', type=click.Choice(['asc', 'desc']), help='Sort order (asc or desc)')
287
295
  @click.option('--format', 'output_format', default='table', type=click.Choice(['table', 'json', 'compact']), help='Output format (table, json, or compact)')
288
296
  @click.option('--raw', is_flag=True, help='Show raw response from API')
@@ -1141,6 +1149,48 @@ def get_ssl_status():
1141
1149
  status = "enabled" if VERIFY_SSL else "disabled"
1142
1150
  click.echo(f"SSL certificate verification is currently {status}")
1143
1151
 
1152
+ @config.command("log-level")
1153
+ @click.argument('level', type=click.Choice([l.name for l in LogLevel], case_sensitive=False), required=True)
1154
+ def set_log_level(level):
1155
+ """Set the diagnostic log level.
1156
+
1157
+ Levels (most to least verbose): TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
1158
+
1159
+ \b
1160
+ Example:
1161
+ das config log-level DEBUG
1162
+ """
1163
+ save_log_level(level)
1164
+ configure_logging()
1165
+ click.secho(f"✓ Log level set to {level.upper()}", fg="green")
1166
+
1167
+ @config.command("log-file")
1168
+ @click.argument('path', required=False)
1169
+ @click.option('--clear', 'clear_path', is_flag=True, help='Stop writing logs to a file (console only)')
1170
+ def set_log_file(path, clear_path):
1171
+ """Set (or clear) the file logs are written to.
1172
+
1173
+ \b
1174
+ Examples:
1175
+ # Write logs to a file
1176
+ das config log-file C:\\logs\\das.log
1177
+
1178
+ \b
1179
+ # Log to the console only
1180
+ das config log-file --clear
1181
+ """
1182
+ if clear_path:
1183
+ save_log_file(None)
1184
+ configure_logging()
1185
+ click.secho("✓ File logging disabled (console only).", fg="green")
1186
+ return
1187
+ if not path:
1188
+ raise click.UsageError("Provide a file path, or use --clear to disable file logging.")
1189
+ save_log_file(path)
1190
+ configure_logging()
1191
+ resolved = load_log_file()
1192
+ click.secho(f"✓ Logs will be written to: {resolved}", fg="green")
1193
+
1144
1194
  @config.command("show")
1145
1195
  def config_show():
1146
1196
  """Show all current persistent settings"""
@@ -1168,10 +1218,19 @@ def config_show():
1168
1218
  click.secho("Current settings", bold=True)
1169
1219
  click.echo("─" * 40)
1170
1220
 
1221
+ # Logging
1222
+ log_level = load_log_level().name
1223
+ log_file = load_log_file() or "(console only)"
1224
+
1171
1225
  click.secho(" Connection", fg="blue", bold=True)
1172
1226
  click.echo(f" API URL : {api_url}")
1173
1227
  click.echo(f" SSL verify : {'enabled' if ssl else 'disabled'}")
1174
1228
 
1229
+ click.echo("")
1230
+ click.secho(" Logging", fg="blue", bold=True)
1231
+ click.echo(f" Log level : {log_level}")
1232
+ click.echo(f" Log file : {log_file}")
1233
+
1175
1234
  click.echo("")
1176
1235
  click.secho(" Authentication", fg="blue", bold=True)
1177
1236
  click.echo(f" Auth type : {auth_type}")
@@ -0,0 +1,177 @@
1
+ import json
2
+ import logging
3
+ import requests
4
+ from das.common.config import load_verify_ssl
5
+ from das.common.errors import describe_request_exception
6
+
7
+ logger = logging.getLogger("das")
8
+
9
+ # Default network timeout (connect, read) in seconds. Prevents the CLI from
10
+ # hanging indefinitely on an unreachable host.
11
+ DEFAULT_TIMEOUT = (10, 60)
12
+
13
+
14
+ def _process_response(response, action: str):
15
+ """Turn a ``requests.Response`` into a parsed dict or a structured error dict.
16
+
17
+ On a successful JSON parse the body is returned as-is (so ABP envelopes with
18
+ ``success``/``error`` flow through to the services). When the HTTP status is
19
+ an error the status code is attached so callers can build a descriptive
20
+ message. A non-JSON body is reported with its status code and a snippet.
21
+ """
22
+ # ``status_code`` is the authoritative error signal; ``response.ok`` is a
23
+ # derived convenience flag (``status_code < 400``). Prefer the former so the
24
+ # behaviour does not depend on ``.ok`` being populated.
25
+ is_http_error = response.status_code >= 400
26
+
27
+ try:
28
+ data = response.json()
29
+ except json.JSONDecodeError as json_err:
30
+ # Not JSON. If the status is an error, surface that clearly.
31
+ if is_http_error:
32
+ message = (
33
+ f"The server returned HTTP {response.status_code} "
34
+ f"({response.reason}) while trying to {action}."
35
+ )
36
+ logger.error("%s Response body: %s", message, response.text[:500])
37
+ return {
38
+ "error": message,
39
+ "status_code": response.status_code,
40
+ "raw_content": response.text[:500],
41
+ }
42
+ logger.error("Error decoding JSON response: %s", json_err)
43
+ return {
44
+ "error": f"Invalid JSON response: {json_err}",
45
+ "status_code": response.status_code,
46
+ "raw_content": response.text[:500],
47
+ }
48
+
49
+ if isinstance(data, dict) and is_http_error:
50
+ # ABP usually returns 200 even for logical errors, but when the HTTP
51
+ # status itself is an error make sure the code travels with the body.
52
+ data.setdefault("status_code", response.status_code)
53
+ logger.debug(
54
+ "%s returned HTTP %s: %s", action, response.status_code, data.get("error")
55
+ )
56
+ return data
57
+
58
+
59
+ def get_data(url, headers=None, params=None):
60
+ """
61
+ Fetch data from a REST API endpoint.
62
+
63
+ Args:
64
+ url (str): The API endpoint URL.
65
+ headers (dict, optional): Headers to include in the request.
66
+ params (dict, optional): Query parameters for the request.
67
+
68
+ Returns:
69
+ dict: The JSON response from the API or an error message.
70
+ """
71
+ logger.debug("GET %s", url)
72
+ try:
73
+ response = requests.get(
74
+ url, headers=headers, params=params,
75
+ verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
76
+ )
77
+ return _process_response(response, "fetch data")
78
+ except requests.RequestException as e:
79
+ message = describe_request_exception(e, url)
80
+ logger.error("Error fetching API data: %s", message)
81
+ return {"error": message}
82
+
83
+ def get_binary_response(url, headers=None, params=None, stream=True):
84
+ """
85
+ Perform a GET request expected to return binary content.
86
+
87
+ Returns the raw requests.Response so callers can inspect headers
88
+ and stream content to disk.
89
+ """
90
+ logger.debug("GET (binary) %s", url)
91
+ try:
92
+ response = requests.get(
93
+ url,
94
+ headers=headers,
95
+ params=params,
96
+ verify=load_verify_ssl(),
97
+ stream=stream,
98
+ timeout=DEFAULT_TIMEOUT,
99
+ )
100
+ response.raise_for_status()
101
+ return response
102
+ except requests.RequestException as e:
103
+ message = describe_request_exception(e, url)
104
+ logger.error("Error fetching binary API data: %s", message)
105
+ return {"error": message}
106
+
107
+ def post_data(url, headers=None, data=None):
108
+ """
109
+ Send data to a REST API endpoint.
110
+
111
+ Args:
112
+ url (str): The API endpoint URL.
113
+ headers (dict, optional): Headers to include in the request.
114
+ data (dict, optional): The data to send in the request body.
115
+
116
+ Returns:
117
+ dict: The JSON response from the API or an error message.
118
+ """
119
+ logger.debug("POST %s", url)
120
+ try:
121
+ response = requests.post(
122
+ url, headers=headers, json=data,
123
+ verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
124
+ )
125
+ return _process_response(response, "post data")
126
+ except requests.RequestException as e:
127
+ message = describe_request_exception(e, url)
128
+ logger.error("Error posting API data: %s", message)
129
+ return {"error": message}
130
+
131
+ def put_data(url, headers=None, data=None):
132
+ """
133
+ Update data at a REST API endpoint.
134
+
135
+ Args:
136
+ url (str): The API endpoint URL.
137
+ headers (dict, optional): Headers to include in the request.
138
+ data (dict, optional): The data to send in the request body.
139
+
140
+ Returns:
141
+ dict: The JSON response from the API or an error message.
142
+ """
143
+ logger.debug("PUT %s", url)
144
+ try:
145
+ response = requests.put(
146
+ url, headers=headers, json=data,
147
+ verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
148
+ )
149
+ return _process_response(response, "update data")
150
+ except requests.RequestException as e:
151
+ message = describe_request_exception(e, url)
152
+ logger.error("Error updating API data: %s", message)
153
+ return {"error": message}
154
+
155
+ def delete_data(url, headers=None, data=None):
156
+ """
157
+ Delete data from a REST API endpoint.
158
+
159
+ Args:
160
+ url (str): The API endpoint URL.
161
+ headers (dict, optional): Headers to include in the request.
162
+ data (dict, optional): The data to send in the request body.
163
+
164
+ Returns:
165
+ dict: The JSON response from the API or an error message.
166
+ """
167
+ logger.debug("DELETE %s", url)
168
+ try:
169
+ response = requests.delete(
170
+ url, headers=headers, json=data,
171
+ verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
172
+ )
173
+ return _process_response(response, "delete data")
174
+ except requests.RequestException as e:
175
+ message = describe_request_exception(e, url)
176
+ logger.error("Error deleting API data: %s", message)
177
+ return {"error": message}