roundtripper 0.2.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,743 @@
1
+ """Interactive configuration menu for roundtripper.
2
+
3
+ Adapted from confluence-markdown-exporter by Sebastian Penhouet.
4
+ https://github.com/Spenhouet/confluence-markdown-exporter
5
+ """
6
+
7
+ # pragma: exclude file
8
+
9
+ from pathlib import Path
10
+ from typing import Any, Literal, get_args, get_origin
11
+
12
+ import jmespath
13
+ import questionary
14
+ from pydantic import BaseModel, SecretStr, ValidationError
15
+ from questionary import Choice, Style
16
+
17
+ from roundtripper.config import ConfigModel
18
+ from roundtripper.config_store import (
19
+ get_app_config_path,
20
+ get_settings,
21
+ reset_to_defaults,
22
+ set_setting,
23
+ )
24
+
25
+ custom_style = Style(
26
+ [
27
+ ("key", "fg:#00b8d4 bold"), # cyan bold for key
28
+ ("value", "fg:#888888 italic"), # gray italic for value
29
+ ("pointer", "fg:#00b8d4 bold"),
30
+ ("highlighted", "fg:#00b8d4 bold"),
31
+ ]
32
+ )
33
+
34
+
35
+ def _get_field_type(model: type[BaseModel], key: str) -> type | None:
36
+ """Get the type annotation for a field in a Pydantic model.
37
+
38
+ Parameters
39
+ ----------
40
+ model
41
+ The Pydantic model class.
42
+ key
43
+ The field name.
44
+
45
+ Returns
46
+ -------
47
+ type | None
48
+ The type annotation, or None if not found.
49
+ """
50
+ if hasattr(model, "model_fields"): # Pydantic v2
51
+ return model.model_fields[key].annotation
52
+ return model.__annotations__[key]
53
+
54
+
55
+ def _get_submodel(model: type[BaseModel], key: str) -> type[BaseModel] | None:
56
+ """Get the submodel type for a nested field.
57
+
58
+ Parameters
59
+ ----------
60
+ model
61
+ The Pydantic model class.
62
+ key
63
+ The field name.
64
+
65
+ Returns
66
+ -------
67
+ type[BaseModel] | None
68
+ The submodel type if the field is a BaseModel, None otherwise.
69
+ """
70
+ if hasattr(model, "model_fields"):
71
+ sub = model.model_fields[key].annotation
72
+ else:
73
+ sub = model.__annotations__[key]
74
+ # Only return submodel if it's a subclass of BaseModel
75
+ if isinstance(sub, type):
76
+ try:
77
+ if issubclass(sub, BaseModel):
78
+ return sub
79
+ except TypeError:
80
+ # sub is not a class or not suitable for issubclass
81
+ return None
82
+ return None
83
+
84
+
85
+ def _get_field_metadata(model: type[BaseModel], key: str) -> dict:
86
+ """Get metadata for a field (title, description, examples).
87
+
88
+ Parameters
89
+ ----------
90
+ model
91
+ The Pydantic model class.
92
+ key
93
+ The field name.
94
+
95
+ Returns
96
+ -------
97
+ dict
98
+ Dictionary with title, description, and examples keys.
99
+ """
100
+ # Support jmespath-style dot-separated paths for nested fields
101
+ if "." in key:
102
+ keys = key.split(".")
103
+ key = keys[-1]
104
+
105
+ # Returns dict with title, description, examples for a field
106
+ if hasattr(model, "model_fields"): # Pydantic v2
107
+ field = model.model_fields[key]
108
+ return {
109
+ "title": getattr(field, "title", None),
110
+ "description": getattr(field, "description", None),
111
+ "examples": getattr(field, "examples", None),
112
+ }
113
+ # Pydantic v1 fallback
114
+ field = model.model_fields[key]
115
+ return {
116
+ "title": getattr(field, "title", None),
117
+ "description": getattr(field, "description", None),
118
+ "examples": getattr(field, "example", None),
119
+ }
120
+
121
+
122
+ def _format_prompt_message(key_name: str, model: type[BaseModel]) -> str:
123
+ """Format a prompt message with field metadata.
124
+
125
+ Parameters
126
+ ----------
127
+ key_name
128
+ The field name.
129
+ model
130
+ The Pydantic model class.
131
+
132
+ Returns
133
+ -------
134
+ str
135
+ Formatted prompt message.
136
+ """
137
+ meta = _get_field_metadata(model, key_name)
138
+ lines = []
139
+ # Title
140
+ if meta["title"]:
141
+ lines.append(f"{meta['title']}\n")
142
+ else:
143
+ lines.append(f"{key_name}\n")
144
+
145
+ # Description
146
+ if meta["description"]:
147
+ lines.append(meta["description"])
148
+
149
+ # Examples
150
+ if meta["examples"]:
151
+ ex = meta["examples"]
152
+ if isinstance(ex, list | tuple) and ex:
153
+ lines.append("\nExamples:")
154
+ lines.extend(f" • {example}" for example in ex)
155
+ # Instruction
156
+ lines.append(f"\nChange {meta['title'] or key_name} to:")
157
+ return "\n".join(lines)
158
+
159
+
160
+ def _validate_int(val: str) -> bool | str:
161
+ """Validate that a string is an integer.
162
+
163
+ Parameters
164
+ ----------
165
+ val
166
+ The value to validate.
167
+
168
+ Returns
169
+ -------
170
+ bool | str
171
+ True if valid, error message string otherwise.
172
+ """
173
+ return val.isdigit() or "Must be an integer"
174
+
175
+
176
+ def _validate_pydantic(val: Any, model: type[BaseModel], key_name: str) -> bool | str:
177
+ """Validate a value against a Pydantic model field.
178
+
179
+ Parameters
180
+ ----------
181
+ val
182
+ The value to validate.
183
+ model
184
+ The Pydantic model class.
185
+ key_name
186
+ The field name.
187
+
188
+ Returns
189
+ -------
190
+ bool | str
191
+ True if valid, error message string otherwise.
192
+ """
193
+ try:
194
+ data = model().model_dump()
195
+ data[key_name] = val
196
+ model(**data)
197
+ except ValidationError as e:
198
+ return str(e.errors()[0]["msg"])
199
+ else:
200
+ return True
201
+
202
+
203
+ def _prompt_literal(prompt_message: str, field_type: type, current_value: Any) -> Any:
204
+ """Prompt for a Literal value using select menu.
205
+
206
+ Parameters
207
+ ----------
208
+ prompt_message
209
+ The prompt message.
210
+ field_type
211
+ The field type (Literal).
212
+ current_value
213
+ Current value to use as default.
214
+
215
+ Returns
216
+ -------
217
+ Any
218
+ Selected value.
219
+ """
220
+ options = list(get_args(field_type))
221
+ return questionary.select(
222
+ prompt_message,
223
+ choices=[str(opt) for opt in options],
224
+ default=str(current_value),
225
+ style=custom_style,
226
+ ).ask()
227
+
228
+
229
+ def _prompt_bool(prompt_message: str, current_value: Any) -> bool:
230
+ """Prompt for a boolean value.
231
+
232
+ Parameters
233
+ ----------
234
+ prompt_message
235
+ The prompt message.
236
+ current_value
237
+ Current value to use as default.
238
+
239
+ Returns
240
+ -------
241
+ bool
242
+ Boolean value.
243
+ """
244
+ return questionary.confirm(
245
+ prompt_message, default=bool(current_value), style=custom_style
246
+ ).ask()
247
+
248
+
249
+ def _prompt_path(
250
+ prompt_message: str,
251
+ current_value: Any,
252
+ model: type[BaseModel],
253
+ key_name: str,
254
+ ) -> Any:
255
+ """Prompt for a Path value.
256
+
257
+ Parameters
258
+ ----------
259
+ prompt_message
260
+ The prompt message.
261
+ current_value
262
+ Current value to use as default.
263
+ model
264
+ The Pydantic model class for validation.
265
+ key_name
266
+ The field name.
267
+
268
+ Returns
269
+ -------
270
+ object
271
+ Path value.
272
+ """
273
+ return questionary.path(
274
+ prompt_message,
275
+ default=str(current_value),
276
+ validate=lambda val: _validate_pydantic(val, model, key_name),
277
+ style=custom_style,
278
+ ).ask()
279
+
280
+
281
+ def _prompt_int(prompt_message: str, current_value: Any) -> int | None:
282
+ """Prompt for an integer value.
283
+
284
+ Parameters
285
+ ----------
286
+ prompt_message
287
+ The prompt message.
288
+ current_value
289
+ Current value to use as default.
290
+
291
+ Returns
292
+ -------
293
+ int
294
+ Integer value or None if cancelled.
295
+ """
296
+ answer = questionary.text(
297
+ prompt_message,
298
+ default=str(current_value),
299
+ validate=_validate_int,
300
+ style=custom_style,
301
+ ).ask()
302
+ if answer is not None:
303
+ try:
304
+ return int(answer)
305
+ except ValueError:
306
+ questionary.print("Invalid integer value.")
307
+ return None
308
+
309
+
310
+ def _prompt_list(prompt_message: str, current_value: Any) -> list[Any] | None:
311
+ """Prompt for a list value (comma-separated).
312
+
313
+ Parameters
314
+ ----------
315
+ prompt_message
316
+ The prompt message.
317
+ current_value
318
+ Current value to use as default.
319
+
320
+ Returns
321
+ -------
322
+ list[Any] | None
323
+ List value or None if cancelled.
324
+ """
325
+ default_val = ""
326
+ val_type = str
327
+ if isinstance(current_value, list):
328
+ default_val = ",".join(map(str, current_value))
329
+ if len(current_value) > 0:
330
+ val_type = type(current_value[0])
331
+ answer = questionary.text(
332
+ prompt_message + " (comma-separated)",
333
+ default=default_val,
334
+ style=custom_style,
335
+ ).ask()
336
+ if answer is not None:
337
+ answer = answer.strip().lstrip("[").rstrip("]").strip(",").replace(" ", "")
338
+ try:
339
+ return [val_type(x.strip()) for x in answer.split(",") if x.strip()]
340
+ except ValueError:
341
+ questionary.print("Input should be a list (e.g. 1,2,3 or [1,2,3]).")
342
+ return None
343
+
344
+
345
+ def _prompt_str(
346
+ prompt_message: str,
347
+ current_value: Any,
348
+ model: type[BaseModel],
349
+ key_name: str,
350
+ ) -> str | None:
351
+ """Prompt for a string value.
352
+
353
+ Parameters
354
+ ----------
355
+ prompt_message
356
+ The prompt message.
357
+ current_value
358
+ Current value to use as default.
359
+ model
360
+ The Pydantic model class for validation.
361
+ key_name
362
+ The field name.
363
+
364
+ Returns
365
+ -------
366
+ str | None
367
+ String value.
368
+ """
369
+ return questionary.text(
370
+ prompt_message,
371
+ default=str(current_value),
372
+ validate=lambda val: _validate_pydantic(val, model, key_name),
373
+ style=custom_style,
374
+ ).ask()
375
+
376
+
377
+ def get_model_by_path(model: type[BaseModel], path: str) -> type[BaseModel]:
378
+ """Traverse a Pydantic model class using a dot-separated path.
379
+
380
+ Parameters
381
+ ----------
382
+ model
383
+ The root Pydantic model class.
384
+ path
385
+ Dot-separated path to the submodel.
386
+
387
+ Returns
388
+ -------
389
+ type[BaseModel]
390
+ The submodel class at the given path.
391
+ """
392
+ keys = path.split(".")
393
+ for key in keys:
394
+ sub = _get_submodel(model, key)
395
+ if sub is not None:
396
+ model = sub
397
+ else:
398
+ break
399
+ return model
400
+
401
+
402
+ def _main_config_menu(settings: dict, default: tuple[str, bool] | None = None) -> tuple:
403
+ """Display the main configuration menu.
404
+
405
+ Parameters
406
+ ----------
407
+ settings
408
+ Current settings dictionary.
409
+ default : tuple[str, bool] | None
410
+ Default selection (key, is_submenu).
411
+
412
+ Returns
413
+ -------
414
+ tuple
415
+ Selected (key, is_submenu) tuple.
416
+ """
417
+ choices = []
418
+ for k, v in settings.items():
419
+ meta = _get_field_metadata(ConfigModel, k)
420
+ display_title = meta["title"] if meta and meta["title"] else k
421
+ if isinstance(v, dict):
422
+ choices.append(
423
+ Choice(
424
+ title=[
425
+ ("class:key", str(display_title)),
426
+ ("class:value", " [submenu]"),
427
+ ],
428
+ value=(k, True),
429
+ )
430
+ )
431
+ else:
432
+ display_val = "Not set" if isinstance(v, str | SecretStr) and str(v) == "" else v
433
+ choices.append(
434
+ Choice(
435
+ title=[
436
+ ("class:key", str(display_title)),
437
+ ("class:value", f" {display_val}"),
438
+ ],
439
+ value=(k, False),
440
+ )
441
+ )
442
+ choices.append(Choice(title="[Reset config to defaults]", value=("__reset__", False)))
443
+ choices.append(Choice(title="[Exit]", value=("__exit__", False)))
444
+ # Find the matching Choice value for default
445
+ default_value = None
446
+ if default is not None:
447
+ for c in choices:
448
+ if hasattr(c, "value") and c.value == default:
449
+ default_value = c.value
450
+ break
451
+ return questionary.select(
452
+ f"Config file location: {get_app_config_path()}\n\nSelect a config to change (or reset):",
453
+ choices=choices,
454
+ style=custom_style,
455
+ default=default_value,
456
+ ).ask() or (None, False)
457
+
458
+
459
+ def _prompt_for_new_value(
460
+ key_name: str,
461
+ current_value: Any,
462
+ model: type[BaseModel],
463
+ ) -> Any:
464
+ """Prompt user for a new value based on field type.
465
+
466
+ Parameters
467
+ ----------
468
+ key_name
469
+ The field name.
470
+ current_value
471
+ Current value.
472
+ model
473
+ The Pydantic model class.
474
+
475
+ Returns
476
+ -------
477
+ Any
478
+ New value or None if cancelled.
479
+ """
480
+ field_type = _get_field_type(model, key_name)
481
+ origin = get_origin(field_type)
482
+ prompt_message = _format_prompt_message(key_name, model)
483
+ if field_type is None:
484
+ field_type = str # Default to string if no type found
485
+ if origin is Literal:
486
+ return _prompt_literal(prompt_message, field_type, current_value)
487
+ if field_type is bool:
488
+ return _prompt_bool(prompt_message, current_value)
489
+ if field_type is Path:
490
+ return _prompt_path(prompt_message, current_value, model, key_name)
491
+ if field_type is int:
492
+ return _prompt_int(prompt_message, current_value)
493
+ if field_type is list or origin is list:
494
+ return _prompt_list(prompt_message, current_value)
495
+ if isinstance(current_value, SecretStr):
496
+ return _prompt_str(prompt_message, current_value.get_secret_value(), model, key_name)
497
+ return _prompt_str(prompt_message, current_value, model, key_name)
498
+
499
+
500
+ def _reset_and_reload(parent_key: str | None, display_title: str | None = None) -> None:
501
+ """Reset config section and reload from disk, with confirmation.
502
+
503
+ Parameters
504
+ ----------
505
+ parent_key : str | None
506
+ The config path to reset, or None to reset all.
507
+ display_title : str | None
508
+ Display title for the section being reset.
509
+ """
510
+ if parent_key is None:
511
+ confirm_msg = "Are you sure you want to reset all config to defaults?"
512
+ else:
513
+ confirm_msg = f"Are you sure you want to reset section '{display_title}' to defaults?"
514
+ confirm = questionary.confirm(confirm_msg, style=custom_style).ask()
515
+ if not confirm:
516
+ return
517
+ reset_to_defaults(parent_key if parent_key else None)
518
+ if display_title:
519
+ questionary.print(f"Section '{display_title}' reset to defaults.")
520
+ else:
521
+ questionary.print("Config reset to defaults.")
522
+
523
+
524
+ def _get_choices(config_dict: dict, model: type[BaseModel]) -> list:
525
+ """Get menu choices for a config section.
526
+
527
+ Parameters
528
+ ----------
529
+ config_dict
530
+ Configuration dictionary.
531
+ model
532
+ The Pydantic model class.
533
+
534
+ Returns
535
+ -------
536
+ list
537
+ List of Choice objects.
538
+ """
539
+ choices = []
540
+ for k, v in config_dict.items():
541
+ if v is None:
542
+ continue
543
+ meta = _get_field_metadata(model, k)
544
+ display_title = meta["title"] if meta and meta["title"] else k
545
+ if isinstance(v, dict):
546
+ choices.append(
547
+ Choice(
548
+ title=[
549
+ ("class:key", str(display_title)),
550
+ ("class:value", " [submenu]"),
551
+ ],
552
+ value=k,
553
+ )
554
+ )
555
+ else:
556
+ display_val = "Not set" if isinstance(v, str | SecretStr) and str(v) == "" else v
557
+ choices.append(
558
+ Choice(
559
+ title=[
560
+ ("class:key", str(display_title)),
561
+ ("class:value", f" {display_val}"),
562
+ ],
563
+ value=k,
564
+ )
565
+ )
566
+ choices.append(Choice(title="[Reset this group to defaults]", value="__reset_section__"))
567
+ choices.append(Choice(title="[Back]", value="__back__"))
568
+ return choices
569
+
570
+
571
+ def _edit_dict_config_loop(
572
+ config_dict: dict,
573
+ model: type[BaseModel],
574
+ parent_key: str,
575
+ parent_model: type[BaseModel],
576
+ last_selected: str | None = None,
577
+ ) -> str | None:
578
+ """Edit a configuration section with a menu loop.
579
+
580
+ Parameters
581
+ ----------
582
+ config_dict
583
+ Configuration dictionary for this section.
584
+ model
585
+ The Pydantic model for this section.
586
+ parent_key
587
+ The config path for this section.
588
+ parent_model
589
+ The parent Pydantic model.
590
+ last_selected : str | None
591
+ Last selected key (for cursor positioning).
592
+
593
+ Returns
594
+ -------
595
+ str | None
596
+ Last selected key or None.
597
+ """
598
+ selected_key = last_selected
599
+ while True:
600
+ choices = _get_choices(config_dict, model)
601
+ meta = None
602
+ if hasattr(parent_model, "model_fields") and parent_key:
603
+ meta = _get_field_metadata(parent_model, parent_key)
604
+ display_title = meta["title"] if meta and meta["title"] else parent_key
605
+ key = questionary.select(
606
+ f"Edit options for '{display_title}':",
607
+ choices=choices,
608
+ style=custom_style,
609
+ default=selected_key,
610
+ ).ask()
611
+ if key == "__back__" or key is None:
612
+ return selected_key
613
+ if key == "__reset_section__":
614
+ _reset_and_reload(parent_key, display_title)
615
+ # Reload the updated config_dict for this section from disk
616
+ updated = get_settings().model_dump()
617
+ if parent_key:
618
+ # Traverse to the correct nested dict for jmespath/dot-paths
619
+ keys = parent_key.split(".")
620
+ sub = updated
621
+ for k in keys:
622
+ sub = sub[k]
623
+ config_dict.clear()
624
+ config_dict.update(sub)
625
+ else:
626
+ config_dict.clear()
627
+ config_dict.update(updated)
628
+ selected_key = None
629
+ continue
630
+ current_value = config_dict[key] if key else None
631
+ submodel = _get_submodel(model, key)
632
+ if isinstance(current_value, dict) and submodel is not None:
633
+ # Always set selected_key to the submenu key after returning
634
+ _edit_dict_config_loop(
635
+ current_value,
636
+ submodel,
637
+ f"{parent_key}.{key}" if parent_key else key,
638
+ model,
639
+ last_selected=None,
640
+ )
641
+ selected_key = key
642
+ else:
643
+ while True:
644
+ value_cast = _prompt_for_new_value(key, current_value, model)
645
+ if value_cast is not None:
646
+ try:
647
+ set_setting(f"{parent_key}.{key}" if parent_key else key, value_cast)
648
+ config_dict[key] = value_cast
649
+ questionary.print(f"{parent_key}.{key} updated to {value_cast}.")
650
+ selected_key = key
651
+ break
652
+ except (ValueError, TypeError) as e:
653
+ questionary.print(f"Error: {e}")
654
+ retry = questionary.confirm("Try again?", style=custom_style).ask()
655
+ if not retry:
656
+ break
657
+ else:
658
+ break
659
+ # After editing, keep cursor at this entry
660
+ selected_key = key
661
+
662
+
663
+ def _edit_dict_config(
664
+ config_dict: dict,
665
+ model: type[BaseModel],
666
+ parent_key: str,
667
+ parent_model: type[BaseModel],
668
+ last_selected: str | None = None,
669
+ ) -> str | None:
670
+ """Edit a configuration section.
671
+
672
+ Parameters
673
+ ----------
674
+ config_dict
675
+ Configuration dictionary for this section.
676
+ model
677
+ The Pydantic model for this section.
678
+ parent_key
679
+ The config path for this section.
680
+ parent_model
681
+ The parent Pydantic model.
682
+ last_selected : str | None
683
+ Last selected key (for cursor positioning).
684
+
685
+ Returns
686
+ -------
687
+ str | None
688
+ Last selected key or None.
689
+ """
690
+ return _edit_dict_config_loop(config_dict, model, parent_key, parent_model, last_selected)
691
+
692
+
693
+ def main_config_menu_loop(jump_to: str | None = None) -> None:
694
+ """Run the main configuration menu loop.
695
+
696
+ Parameters
697
+ ----------
698
+ jump_to : str | None
699
+ Optional config path to jump to directly (e.g., "auth.confluence").
700
+ """
701
+ settings = get_settings().model_dump()
702
+ if jump_to:
703
+ submenu = jmespath.search(jump_to, settings)
704
+ submodel = get_model_by_path(ConfigModel, jump_to)
705
+ parent_path = jump_to.rsplit(".", 1)[0] if "." in jump_to else None
706
+ parent_model = get_model_by_path(ConfigModel, parent_path) if parent_path else ConfigModel
707
+ _edit_dict_config(submenu, submodel, jump_to, parent_model)
708
+ return
709
+ last_selected = None
710
+ while True:
711
+ settings = get_settings().model_dump()
712
+ key, is_dict = _main_config_menu(settings, default=last_selected)
713
+ if key == "__reset__":
714
+ _reset_and_reload(None)
715
+ last_selected = None
716
+ continue
717
+ if key == "__exit__" or key is None:
718
+ break
719
+ last_selected = (key, is_dict)
720
+ current_value = settings[key]
721
+ if is_dict:
722
+ submodel = _get_submodel(ConfigModel, key)
723
+ if submodel is not None:
724
+ returned_key = _edit_dict_config(
725
+ current_value, submodel, key, ConfigModel, last_selected=None
726
+ )
727
+ last_selected = (key, is_dict) if returned_key is None else (returned_key, True)
728
+ else:
729
+ while True:
730
+ value_cast = _prompt_for_new_value(key, current_value, ConfigModel)
731
+ if value_cast is None or value_cast == current_value:
732
+ # User cancelled or made no change: do not update config
733
+ break
734
+ try:
735
+ set_setting(key, value_cast)
736
+ questionary.print(f"{key} updated to {value_cast}.")
737
+ last_selected = (key, is_dict)
738
+ break
739
+ except (ValueError, TypeError) as e:
740
+ questionary.print(f"Error: {e}")
741
+ retry = questionary.confirm("Try again?", style=custom_style).ask()
742
+ if not retry:
743
+ break