meerschaum 2.5.0__py3-none-any.whl → 2.6.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.
Files changed (45) hide show
  1. meerschaum/_internal/arguments/_parser.py +6 -1
  2. meerschaum/_internal/entry.py +16 -5
  3. meerschaum/actions/edit.py +6 -6
  4. meerschaum/actions/sql.py +12 -11
  5. meerschaum/api/dash/pages/login.py +17 -17
  6. meerschaum/api/dash/pipes.py +104 -13
  7. meerschaum/api/routes/_pipes.py +58 -40
  8. meerschaum/api/routes/_webterm.py +1 -0
  9. meerschaum/config/_edit.py +46 -19
  10. meerschaum/config/_read_config.py +20 -9
  11. meerschaum/config/_version.py +1 -1
  12. meerschaum/config/stack/__init__.py +1 -1
  13. meerschaum/config/static/__init__.py +1 -0
  14. meerschaum/connectors/api/_APIConnector.py +1 -0
  15. meerschaum/connectors/api/_pipes.py +39 -8
  16. meerschaum/connectors/sql/_SQLConnector.py +4 -3
  17. meerschaum/connectors/sql/_pipes.py +511 -118
  18. meerschaum/connectors/sql/_sql.py +55 -15
  19. meerschaum/connectors/valkey/_ValkeyConnector.py +3 -2
  20. meerschaum/connectors/valkey/_pipes.py +11 -5
  21. meerschaum/core/Pipe/__init__.py +27 -9
  22. meerschaum/core/Pipe/_attributes.py +181 -18
  23. meerschaum/core/Pipe/_clear.py +10 -8
  24. meerschaum/core/Pipe/_copy.py +2 -0
  25. meerschaum/core/Pipe/_data.py +65 -17
  26. meerschaum/core/Pipe/_deduplicate.py +30 -28
  27. meerschaum/core/Pipe/_dtypes.py +4 -4
  28. meerschaum/core/Pipe/_fetch.py +12 -10
  29. meerschaum/core/Pipe/_sync.py +28 -11
  30. meerschaum/core/Pipe/_verify.py +52 -49
  31. meerschaum/utils/dataframe.py +64 -34
  32. meerschaum/utils/dtypes/__init__.py +25 -6
  33. meerschaum/utils/dtypes/sql.py +76 -33
  34. meerschaum/utils/misc.py +57 -24
  35. meerschaum/utils/packages/_packages.py +2 -1
  36. meerschaum/utils/schedule.py +7 -5
  37. meerschaum/utils/sql.py +697 -44
  38. {meerschaum-2.5.0.dist-info → meerschaum-2.6.0.dist-info}/METADATA +5 -3
  39. {meerschaum-2.5.0.dist-info → meerschaum-2.6.0.dist-info}/RECORD +45 -45
  40. {meerschaum-2.5.0.dist-info → meerschaum-2.6.0.dist-info}/WHEEL +1 -1
  41. {meerschaum-2.5.0.dist-info → meerschaum-2.6.0.dist-info}/LICENSE +0 -0
  42. {meerschaum-2.5.0.dist-info → meerschaum-2.6.0.dist-info}/NOTICE +0 -0
  43. {meerschaum-2.5.0.dist-info → meerschaum-2.6.0.dist-info}/entry_points.txt +0 -0
  44. {meerschaum-2.5.0.dist-info → meerschaum-2.6.0.dist-info}/top_level.txt +0 -0
  45. {meerschaum-2.5.0.dist-info → meerschaum-2.6.0.dist-info}/zip-safe +0 -0
@@ -90,8 +90,13 @@ def parse_datetime(dt_str: str) -> Union[datetime, int, str]:
90
90
  except Exception as e:
91
91
  dt = None
92
92
  if dt is None:
93
- from meerschaum.utils.warnings import warn, error
93
+ from meerschaum.utils.warnings import error
94
94
  error(f"'{dt_str}' is not a valid datetime format.", stack=False)
95
+
96
+ if isinstance(dt, datetime):
97
+ from meerschaum.utils.dtypes import coerce_timezone
98
+ dt = coerce_timezone(dt)
99
+
95
100
  return dt
96
101
 
97
102
 
@@ -13,6 +13,7 @@ import os
13
13
  import sys
14
14
  import pathlib
15
15
 
16
+ import meerschaum as mrsm
16
17
  from meerschaum.utils.typing import SuccessTuple, List, Optional, Dict, Callable, Any
17
18
  from meerschaum.config.static import STATIC_CONFIG as _STATIC_CONFIG
18
19
 
@@ -229,7 +230,7 @@ def entry_with_args(
229
230
  _ = get_shell(**kw).cmdloop()
230
231
  return True, "Success"
231
232
 
232
- skip_schedule = False
233
+ _skip_schedule = False
233
234
 
234
235
  executor_keys = kw.get('executor_keys', None)
235
236
  if executor_keys is None:
@@ -246,7 +247,7 @@ def entry_with_args(
246
247
  api_label = executor_keys.split(':')[-1]
247
248
  kw['action'].insert(0, 'api')
248
249
  kw['action'].insert(1, api_label)
249
- skip_schedule = True
250
+ _skip_schedule = True
250
251
 
251
252
  ### If the `--daemon` flag is present, prepend 'start job'.
252
253
  if kw.get('daemon', False) and kw['action'][0] != 'stack':
@@ -271,7 +272,7 @@ def entry_with_args(
271
272
  and kw['action'][0] == 'start'
272
273
  and kw['action'][1] in ('job', 'jobs')
273
274
  ):
274
- skip_schedule = True
275
+ _skip_schedule = True
275
276
 
276
277
  kw['action'] = remove_leading_action(kw['action'], _actions=_actions)
277
278
 
@@ -279,10 +280,11 @@ def entry_with_args(
279
280
  _do_action_wrapper,
280
281
  action_function,
281
282
  plugin_name,
283
+ _skip_schedule=_skip_schedule,
282
284
  **kw
283
285
  )
284
286
 
285
- if kw.get('schedule', None) and not skip_schedule:
287
+ if kw.get('schedule', None) and not _skip_schedule:
286
288
  from meerschaum.utils.schedule import schedule_function
287
289
  from meerschaum.utils.misc import interval_str
288
290
  import time
@@ -304,7 +306,12 @@ def entry_with_args(
304
306
  return result
305
307
 
306
308
 
307
- def _do_action_wrapper(action_function, plugin_name, **kw):
309
+ def _do_action_wrapper(
310
+ action_function,
311
+ plugin_name,
312
+ _skip_schedule: bool = False,
313
+ **kw
314
+ ):
308
315
  from meerschaum.plugins import Plugin
309
316
  from meerschaum.utils.venv import Venv
310
317
  from meerschaum.utils.misc import filter_keywords
@@ -328,6 +335,10 @@ def _do_action_wrapper(action_function, plugin_name, **kw):
328
335
  )
329
336
  except KeyboardInterrupt:
330
337
  result = False, f"Cancelled action `{action_name.lstrip()}`."
338
+
339
+ if kw.get('schedule', None) and not _skip_schedule:
340
+ mrsm.pprint(result)
341
+
331
342
  return result
332
343
 
333
344
  _shells = []
@@ -65,24 +65,24 @@ def _complete_edit(
65
65
  from meerschaum._internal.shell import default_action_completer
66
66
  return default_action_completer(action=(['edit'] + action), **kw)
67
67
 
68
- def _edit_config(action : Optional[List[str]] = None, **kw : Any) -> SuccessTuple:
68
+
69
+ def _edit_config(action: Optional[List[str]] = None, **kw : Any) -> SuccessTuple:
69
70
  """
70
71
  Edit Meerschaum configuration files.
71
-
72
+
72
73
  Specify a specific configuration key to edit.
73
74
  Defaults to editing `meerschaum` configuration (connectors, instance, etc.).
74
-
75
+
75
76
  Examples:
76
77
  ```
77
78
  ### Edit the main 'meerschaum' configuration.
78
79
  edit config
79
-
80
+
80
81
  ### Edit 'system' configuration.
81
82
  edit config system
82
-
83
+
83
84
  ### Create a new configuration file called 'myconfig'.
84
85
  edit config myconfig
85
-
86
86
  ```
87
87
  """
88
88
  from meerschaum.config._edit import edit_config
meerschaum/actions/sql.py CHANGED
@@ -14,6 +14,7 @@ exec_methods = {
14
14
  'exec',
15
15
  }
16
16
 
17
+
17
18
  def sql(
18
19
  action: Optional[List[str]] = None,
19
20
  gui: bool = False,
@@ -22,40 +23,40 @@ def sql(
22
23
  **kw: Any
23
24
  ):
24
25
  """Execute a SQL query or launch an interactive CLI. All positional arguments are optional.
25
-
26
+
26
27
  Usage:
27
28
  `sql {label} {method} {query / table}`
28
-
29
+
29
30
  Options:
30
31
  - `sql {label}`
31
32
  Launch an interactive CLI. If {label} is omitted, use 'main'.
32
-
33
+
33
34
  - `sql {label} read [query / table]`
34
35
  Read a table or query as a pandas DataFrame and print the result.
35
-
36
+
36
37
  - `sql {label} exec [query]`
37
38
  Execute a query and print the success status.
38
-
39
+
39
40
  Examples:
40
41
  - `sql`
41
42
  Open an interactive CLI for `sql:main`.
42
-
43
+
43
44
  - `sql local`
44
45
  Open an interactive CLI for `sql:local`.
45
-
46
+
46
47
  - `sql table`
47
48
  Read from `table` on `sql:main`
48
49
  (translates to `SELECT * FROM table`).
49
-
50
+
50
51
  - `sql local table`
51
52
  Read from `table` on `sql:local`.
52
-
53
+
53
54
  - `sql local read table`
54
55
  Read from `table` on `sql:local`.
55
-
56
+
56
57
  - `sql "SELECT * FROM table WHERE id = 1"`
57
58
  Execute the above query on `sql:main` and print the results.
58
-
59
+
59
60
  - `sql local exec "INSERT INTO table (id) VALUES (1)"
60
61
  Execute the above query on `sql:local`.
61
62
  """
@@ -19,13 +19,13 @@ allow_user_registration = permissions_config['registration']['users']
19
19
 
20
20
  registration_div = html.Div(
21
21
  id = 'registration-div',
22
- style = {'height' : '100%'},
23
- children = (
22
+ style={'height' : '100%'},
23
+ children=(
24
24
  [
25
25
  dcc.Link(
26
26
  'No account? Create one here.',
27
- href = (dash_endpoint + '/register'),
28
- refresh = False
27
+ href=(dash_endpoint + '/register'),
28
+ refresh=False
29
29
  ),
30
30
  ] if allow_user_registration
31
31
  else [
@@ -36,12 +36,12 @@ registration_div = html.Div(
36
36
  dbc.Button(
37
37
  'More information.',
38
38
  id = 'show-user-registration-disabled-button',
39
- color = 'link',
40
- size = 'sm',
39
+ color='link',
40
+ size='sm',
41
41
  ),
42
42
  dbc.Collapse(
43
- id = 'user-registration-disabled-collapse',
44
- children = [
43
+ id='user-registration-disabled-collapse',
44
+ children=[
45
45
  dcc.Markdown(
46
46
  "For example, to register user `newuser` on instance `sql:main`:"
47
47
  ),
@@ -60,10 +60,10 @@ registration_div = html.Div(
60
60
  html.Pre(
61
61
  html.Code(
62
62
  json.dumps({
63
- 'api' : {
64
- 'permissions' : {
65
- 'registration' : {
66
- 'users' : True,
63
+ 'api': {
64
+ 'permissions': {
65
+ 'registration': {
66
+ 'users': True,
67
67
  },
68
68
  }
69
69
  }
@@ -112,11 +112,11 @@ layout = dbc.Container([
112
112
  dbc.Row([
113
113
  dbc.Col([
114
114
  html.Button(
115
- children = 'Login',
116
- n_clicks = 0,
117
- type = 'submit',
118
- id = 'login-button',
119
- className = 'btn btn-primary btn-lg'
115
+ children='Login',
116
+ n_clicks=0,
117
+ type='submit',
118
+ id='login-button',
119
+ className='btn btn-primary btn-lg'
120
120
  ),
121
121
  ]),
122
122
  ]),
@@ -33,6 +33,11 @@ html, dcc = import_html(check_update=CHECK_UPDATE), import_dcc(check_update=CHEC
33
33
  humanfriendly = attempt_import('humanfriendly', check_update=CHECK_UPDATE)
34
34
  pd = import_pandas()
35
35
 
36
+ INDEX_PREFIX_EMOJI: Dict[str, str] = {
37
+ 'datetime': '🕓',
38
+ 'primary': '🔑',
39
+ }
40
+
36
41
 
37
42
  def pipe_from_ctx(ctx, trigger_property: str = 'n_clicks') -> Union[mrsm.Pipe, None]:
38
43
  """
@@ -346,6 +351,8 @@ def accordion_items_from_pipe(
346
351
  for item in skip_items:
347
352
  _ = items_titles.pop(item, None)
348
353
 
354
+ pipe_meta_str = json.dumps(pipe.meta, sort_keys=True)
355
+
349
356
  ### Only generate items if they're in the `active_items` list.
350
357
  items_bodies = {}
351
358
  if 'overview' in active_items:
@@ -358,22 +365,107 @@ def accordion_items_from_pipe(
358
365
  html.Tr([html.Td("Instance"), html.Td(html.Pre(f"{pipe.instance_keys}"))]),
359
366
  html.Tr([html.Td("Target Table"), html.Td(html.Pre(f"{pipe.target}"))]),
360
367
  ]
361
- columns = pipe.columns.copy()
362
- if columns:
363
- datetime_index = columns.pop('datetime', None)
364
- columns_items = []
365
- if datetime_index:
366
- columns_items.append(html.Li(f"{datetime_index} (datetime)"))
367
- columns_items.extend([
368
- html.Li(f"{col}")
369
- for col_key, col in columns.items()
370
- ])
368
+
369
+ indices_header = [
370
+ html.Thead(
371
+ html.Tr(
372
+ [
373
+ html.Th(
374
+ html.Span(
375
+ "Key",
376
+ id={'type': 'key-table-header', 'id': pipe_meta_str},
377
+ style={"textDecoration": "underline", "cursor": "pointer"},
378
+ ),
379
+ ),
380
+ html.Th(
381
+ html.Span(
382
+ "Column",
383
+ id={'type': 'column-table-header', 'id': pipe_meta_str},
384
+ style={"textDecoration": "underline", "cursor": "pointer"},
385
+ ),
386
+ ),
387
+ html.Th(
388
+ html.Span(
389
+ "Index",
390
+ id={'type': 'index-table-header', 'id': pipe_meta_str},
391
+ style={"textDecoration": "underline", "cursor": "pointer"},
392
+ ),
393
+ ),
394
+ html.Th(
395
+ html.Span(
396
+ "Is Composite",
397
+ id={'type': 'is-composite-table-header', 'id': pipe_meta_str},
398
+ style={"textDecoration": "underline", "cursor": "pointer"},
399
+ ),
400
+ ),
401
+ dbc.Tooltip(
402
+ "Unique reference name for the index "
403
+ "(e.g. `datetime` for the range axis)",
404
+ target={'type': 'key-table-header', 'id': pipe_meta_str},
405
+ ),
406
+ dbc.Tooltip(
407
+ "The actual column (field name) in the target dataset.",
408
+ target={'type': 'column-table-header', 'id': pipe_meta_str},
409
+ ),
410
+ dbc.Tooltip(
411
+ "The name of the index created on the given columns.",
412
+ target={'type': 'index-table-header', 'id': pipe_meta_str},
413
+ ),
414
+ dbc.Tooltip(
415
+ "Whether the column is used in the composite primary key "
416
+ "to determine updates.",
417
+ target={'type': 'is-composite-table-header', 'id': pipe_meta_str},
418
+ ),
419
+ ]
420
+ )
421
+ )
422
+ ]
423
+
424
+ indices = pipe.indices
425
+ columns = pipe.columns
426
+ index_column_names = pipe.get_indices()
427
+ indices_rows = []
428
+ for ix_key, ix_cols in indices.items():
429
+ col = columns.get(ix_key, None)
430
+ ix_name = index_column_names.get(ix_key, None)
431
+ if not col and not ix_cols:
432
+ continue
433
+ if not isinstance(ix_cols, (list, tuple)):
434
+ ix_cols = [ix_cols]
435
+ if col:
436
+ col_item = html.Pre(col)
437
+ elif len(ix_cols) == 1:
438
+ col_item = html.Pre(ix_cols[0])
439
+ else:
440
+ col_item = html.Pre(html.Ul([html.Li(_c) for _c in ix_cols]))
441
+ is_composite_item = "✅" if col else ""
442
+ ix_key_item = html.Pre(
443
+ INDEX_PREFIX_EMOJI.get(ix_key, '')
444
+ + (' ' if ix_key in INDEX_PREFIX_EMOJI else '')
445
+ + ix_key
446
+ )
447
+ indices_rows.append(
448
+ html.Tr([
449
+ html.Td(ix_key_item),
450
+ html.Td(col_item),
451
+ html.Td(html.Pre(ix_name or '')),
452
+ html.Td(is_composite_item),
453
+ ])
454
+ )
455
+ indices_table = dbc.Table(
456
+ indices_header + [html.Tbody(indices_rows)],
457
+ bordered=True,
458
+ hover=False,
459
+ striped=True,
460
+ )
461
+ if indices_rows:
371
462
  overview_rows.append(
372
463
  html.Tr([
373
- html.Td("Indices" if len(columns_items) != 1 else "Index"),
374
- html.Td(html.Pre(html.Ul(columns_items))),
464
+ html.Td("Indices" if len(indices_rows) != 1 else "Index"),
465
+ html.Td(indices_table),
375
466
  ])
376
467
  )
468
+
377
469
  tags = pipe.tags
378
470
  if tags:
379
471
  tags_items = html.Ul([
@@ -420,7 +512,6 @@ def accordion_items_from_pipe(
420
512
  if newest_time is not None:
421
513
  stats_rows.append(html.Tr([html.Td("Newest time"), html.Td(str(newest_time))]))
422
514
 
423
-
424
515
  items_bodies['stats'] = dbc.Table(stats_header + [html.Tbody(stats_rows)], hover=True)
425
516
 
426
517
  if 'columns' in active_items:
@@ -558,7 +558,7 @@ def get_pipe_id(
558
558
  curr_user = (
559
559
  fastapi.Depends(manager) if not no_auth else None
560
560
  ),
561
- ) -> int:
561
+ ) -> Union[int, str]:
562
562
  """
563
563
  Get a Pipe's ID.
564
564
  """
@@ -573,36 +573,36 @@ def get_pipe_id(
573
573
  tags = ['Pipes']
574
574
  )
575
575
  def get_pipe_attributes(
576
- connector_keys : str,
577
- metric_key : str,
578
- location_key : str,
579
- curr_user = (
580
- fastapi.Depends(manager) if not no_auth else None
581
- ),
582
- ) -> Dict[str, Any]:
576
+ connector_keys: str,
577
+ metric_key: str,
578
+ location_key: str,
579
+ curr_user=(
580
+ fastapi.Depends(manager) if not no_auth else None
581
+ ),
582
+ ) -> Dict[str, Any]:
583
583
  """Get a Pipe's attributes."""
584
584
  return get_pipe(connector_keys, metric_key, location_key).attributes
585
585
 
586
586
 
587
587
  @app.get(pipes_endpoint + '/{connector_keys}/{metric_key}/{location_key}/exists', tags=['Pipes'])
588
588
  def get_pipe_exists(
589
- connector_keys: str,
590
- metric_key: str,
591
- location_key: str,
592
- curr_user = (
593
- fastapi.Depends(manager) if not no_auth else None
594
- ),
595
- ) -> bool:
589
+ connector_keys: str,
590
+ metric_key: str,
591
+ location_key: str,
592
+ curr_user = (
593
+ fastapi.Depends(manager) if not no_auth else None
594
+ ),
595
+ ) -> bool:
596
596
  """Determine whether a Pipe exists."""
597
597
  return get_pipe(connector_keys, metric_key, location_key).exists()
598
598
 
599
599
 
600
600
  @app.post(endpoints['metadata'], tags=['Pipes'])
601
601
  def create_metadata(
602
- curr_user = (
603
- fastapi.Depends(manager) if not no_auth else None
604
- ),
605
- ) -> bool:
602
+ curr_user = (
603
+ fastapi.Depends(manager) if not no_auth else None
604
+ ),
605
+ ) -> bool:
606
606
  """Create Pipe metadata tables"""
607
607
  from meerschaum.connectors.sql.tables import get_tables
608
608
  try:
@@ -614,16 +614,16 @@ def create_metadata(
614
614
 
615
615
  @app.get(pipes_endpoint + '/{connector_keys}/{metric_key}/{location_key}/rowcount', tags=['Pipes'])
616
616
  def get_pipe_rowcount(
617
- connector_keys: str,
618
- metric_key: str,
619
- location_key: str,
620
- begin: Union[str, int, None] = None,
621
- end: Union[str, int, None] = None,
622
- params: Optional[Dict[str, Any]] = None,
623
- curr_user = (
624
- fastapi.Depends(manager) if not no_auth else None
625
- ),
626
- ) -> int:
617
+ connector_keys: str,
618
+ metric_key: str,
619
+ location_key: str,
620
+ begin: Union[str, int, None] = None,
621
+ end: Union[str, int, None] = None,
622
+ params: Optional[Dict[str, Any]] = None,
623
+ curr_user = (
624
+ fastapi.Depends(manager) if not no_auth else None
625
+ ),
626
+ ) -> int:
627
627
  """
628
628
  Return a pipe's rowcount.
629
629
  """
@@ -632,10 +632,10 @@ def get_pipe_rowcount(
632
632
  if is_int(end):
633
633
  end = int(end)
634
634
  return get_pipe(connector_keys, metric_key, location_key).get_rowcount(
635
- begin = begin,
636
- end = end,
637
- params = params,
638
- debug = debug
635
+ begin=begin,
636
+ end=end,
637
+ params=params,
638
+ debug=debug,
639
639
  )
640
640
 
641
641
 
@@ -644,13 +644,13 @@ def get_pipe_rowcount(
644
644
  tags=['Pipes']
645
645
  )
646
646
  def get_pipe_columns_types(
647
- connector_keys: str,
648
- metric_key: str,
649
- location_key: str,
650
- curr_user = (
651
- fastapi.Depends(manager) if not no_auth else None
652
- ),
653
- ) -> Dict[str, str]:
647
+ connector_keys: str,
648
+ metric_key: str,
649
+ location_key: str,
650
+ curr_user=(
651
+ fastapi.Depends(manager) if not no_auth else None
652
+ ),
653
+ ) -> Dict[str, str]:
654
654
  """
655
655
  Return a dictionary of column names and types.
656
656
 
@@ -663,3 +663,21 @@ def get_pipe_columns_types(
663
663
  ```
664
664
  """
665
665
  return get_pipe(connector_keys, metric_key, location_key).dtypes
666
+
667
+
668
+ @app.get(
669
+ pipes_endpoint + '/{connector_keys}/{metric_key}/{location_key}/columns/indices',
670
+ tags=['Pipes']
671
+ )
672
+ def get_pipe_columns_indices(
673
+ connector_keys: str,
674
+ metric_key: str,
675
+ location_key: str,
676
+ curr_user=(
677
+ fastapi.Depends(manager) if not no_auth else None
678
+ ),
679
+ ) -> Dict[str, List[Dict[str, str]]]:
680
+ """
681
+ Return a dictionary of column names and related indices.
682
+ """
683
+ return get_pipe(connector_keys, metric_key, location_key).get_columns_indices()
@@ -13,6 +13,7 @@ from meerschaum.utils.packages import attempt_import
13
13
  from meerschaum.api.dash.sessions import is_session_authenticated
14
14
  fastapi, fastapi_responses = attempt_import('fastapi', 'fastapi.responses')
15
15
  import starlette
16
+ httpcore = attempt_import('httpcore')
16
17
  httpx = attempt_import('httpx')
17
18
  websockets = attempt_import('websockets')
18
19
  Request = fastapi.Request
@@ -7,44 +7,71 @@ Functions for editing the configuration file
7
7
  """
8
8
 
9
9
  from __future__ import annotations
10
- import sys
11
10
  import pathlib
12
11
  from meerschaum.utils.typing import Optional, Any, SuccessTuple, Mapping, Dict, List, Union
13
12
 
13
+
14
14
  def edit_config(
15
- keys : Optional[List[str]] = None,
16
- params : Optional[Dict[str, Any]] = None,
17
- debug : bool = False,
18
- **kw : Any
19
- ) -> SuccessTuple:
15
+ keys: Optional[List[str]] = None,
16
+ params: Optional[Dict[str, Any]] = None,
17
+ debug: bool = False,
18
+ **kw: Any
19
+ ) -> SuccessTuple:
20
20
  """Edit the configuration files."""
21
21
  from meerschaum.config import get_config, config
22
- from meerschaum.config._read_config import get_keyfile_path
22
+ from meerschaum.config._read_config import get_keyfile_path, read_config
23
23
  from meerschaum.config._paths import CONFIG_DIR_PATH
24
24
  from meerschaum.utils.packages import reload_meerschaum
25
25
  from meerschaum.utils.misc import edit_file
26
- from meerschaum.utils.debug import dprint
26
+ from meerschaum.utils.warnings import warn, dprint
27
+ from meerschaum.utils.prompt import prompt
27
28
 
28
29
  if keys is None:
29
30
  keys = []
30
31
 
31
- for k in keys:
32
- ### If defined in default, create the config file.
33
- if isinstance(config, dict) and k in config:
34
- del config[k]
35
- get_config(k, write_missing=True, warn=False)
36
- edit_file(get_keyfile_path(k, create_new=True))
32
+ def _edit_key(key: str):
33
+ while True:
34
+ ### If defined in default, create the config file.
35
+ key_config = config.pop(key, None)
36
+ keyfile_path = get_keyfile_path(key, create_new=True)
37
+ get_config(key, write_missing=True, warn=False)
38
+
39
+ edit_file(get_keyfile_path(key, create_new=True))
40
+
41
+ ### TODO: verify that the file is valid. Retry if not.
42
+ try:
43
+ new_key_config = read_config(
44
+ CONFIG_DIR_PATH,
45
+ [key],
46
+ write_missing=False,
47
+ raise_parsing_errors=True,
48
+ )
49
+ except Exception:
50
+ if key_config:
51
+ config[key] = key_config
52
+ warn(f"Could not parse key '{key}'.", stack=False)
53
+ _ = prompt(f"Press [Enter] to edit '{keyfile_path}', [CTRL+C] to exit.")
54
+ continue
55
+
56
+ if new_key_config:
57
+ break
58
+
59
+ try:
60
+ for k in keys:
61
+ _edit_key(k)
62
+ except KeyboardInterrupt:
63
+ return False, f""
37
64
 
38
65
  reload_meerschaum(debug=debug)
39
66
  return (True, "Success")
40
67
 
41
68
 
42
69
  def write_config(
43
- config_dict: Optional[Dict[str, Any]] = None,
44
- directory: Union[str, pathlib.Path, None] = None,
45
- debug: bool = False,
46
- **kw : Any
47
- ) -> bool:
70
+ config_dict: Optional[Dict[str, Any]] = None,
71
+ directory: Union[str, pathlib.Path, None] = None,
72
+ debug: bool = False,
73
+ **kw: Any
74
+ ) -> bool:
48
75
  """Write YAML and JSON files to the configuration directory.
49
76
 
50
77
  Parameters