dmlops 0.2.10__py3-none-win_amd64.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.
dmlops/_tui.py ADDED
@@ -0,0 +1,668 @@
1
+ """Minimal stdlib terminal UI for interactive login (no dependencies).
2
+
3
+ Mirrors the CLI ``mlops auth login`` wizard: arrow-key select, ghost-prefilled
4
+ server/email inputs, masked password. All rendering goes to stderr; results
5
+ are returned to the caller. Every prompt returns ``None`` on cancel
6
+ (Esc / Ctrl+C), after printing the matching ``Cancelled by user`` line.
7
+
8
+ Platform matrix:
9
+
10
+ - Linux / macOS: ``termios``/``tty.setcbreak`` + ANSI escapes. cbreak keeps
11
+ ISIG, so Ctrl+C raises ``KeyboardInterrupt`` naturally.
12
+ - Windows: ``msvcrt.getwch()`` (wide chars) + ANSI escapes; virtual-terminal
13
+ processing is enabled on the stderr and stdout console handles at
14
+ ``available()`` time. ``'\\x03'`` from ``getwch`` is normalized to
15
+ ``KeyboardInterrupt``.
16
+
17
+ Output is always ``sys.stderr.write(str)`` — never byte-level ``os.write`` —
18
+ so Windows consoles go through ``WriteConsoleW`` and the glyphs (``✔ › ❯``)
19
+ render regardless of the console code page.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ import sys
26
+ from contextlib import contextmanager
27
+
28
+ if sys.platform == "win32": # pragma: no cover — platform guard
29
+ try:
30
+ import ctypes
31
+ import msvcrt
32
+ except ImportError:
33
+ ctypes = None # type: ignore[assignment]
34
+ msvcrt = None # type: ignore[assignment]
35
+ _select = None
36
+ _termios = None
37
+ _tty = None
38
+ else:
39
+ ctypes = None # type: ignore[assignment]
40
+ msvcrt = None # type: ignore[assignment]
41
+ try:
42
+ import select as _select
43
+ import termios as _termios
44
+ import tty as _tty
45
+ except ImportError: # pragma: no cover — non-POSIX oddballs
46
+ _select = None
47
+ _termios = None
48
+ _tty = None
49
+
50
+ # Second code of a Windows extended key (after \x00 / \xe0 prefix). Pure data
51
+ # so it is testable on any platform.
52
+ _WIN_KEYMAP = {
53
+ "H": "up",
54
+ "P": "down",
55
+ "K": "left",
56
+ "M": "right",
57
+ "G": "home",
58
+ "O": "end",
59
+ "S": "delete",
60
+ }
61
+
62
+ _ENABLE_VT_PROCESSING = 0x4
63
+ _STD_OUTPUT_HANDLE = -11
64
+ _STD_ERROR_HANDLE = -12
65
+
66
+ _RESET = "\x1b[0m"
67
+ _YELLOW = "33"
68
+ _GREEN = "32"
69
+ _RED = "31"
70
+ _BOLD = "1"
71
+ _GRAY = "90"
72
+ _LINK = "94"
73
+ _UNDERLINE = "4"
74
+
75
+ CANCELLED_ESC = "Cancelled by user (Esc)."
76
+ CANCELLED_CTRL_C = "Cancelled by user (Ctrl+C)."
77
+
78
+ TIPS_SERVER = "Tips: Esc back · Tab accept · Enter confirm · Ctrl+U clear · Ctrl+C quit"
79
+ TIPS_EMAIL = (
80
+ "Tips: Esc back · Tab accept · Enter confirm · @ custom address · Ctrl+U clear · Ctrl+C quit"
81
+ )
82
+ TIPS_PASSWORD = "Tips: Esc back · Enter confirm · Ctrl+C quit"
83
+ TIPS_SELECT = "Tips: ↑/↓ move · Enter confirm · Esc quit"
84
+
85
+
86
+ def _c(code: str, text: str) -> str:
87
+ return f"\x1b[{code}m{text}{_RESET}"
88
+
89
+
90
+ def _err(text: str) -> None:
91
+ sys.stderr.write(text)
92
+ sys.stderr.flush()
93
+
94
+
95
+ # --- availability ------------------------------------------------------------
96
+
97
+
98
+ def _enable_windows_vt() -> bool:
99
+ """Enable VT processing on the stderr and stdout console handles."""
100
+ if ctypes is None:
101
+ return False
102
+ try:
103
+ kernel32 = ctypes.windll.kernel32
104
+ for handle_id in (_STD_ERROR_HANDLE, _STD_OUTPUT_HANDLE):
105
+ handle = kernel32.GetStdHandle(handle_id)
106
+ if not handle:
107
+ return False
108
+ mode = ctypes.c_ulong()
109
+ if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
110
+ return False
111
+ if not kernel32.SetConsoleMode(handle, mode.value | _ENABLE_VT_PROCESSING):
112
+ return False
113
+ return True
114
+ except Exception: # noqa: BLE001 — any console failure → plain-text fallback
115
+ return False
116
+
117
+
118
+ _available_cache: bool | None = None
119
+
120
+
121
+ def available() -> bool:
122
+ """True when the interactive TUI can run (TTY + platform support)."""
123
+ global _available_cache
124
+ if _available_cache is not None:
125
+ return _available_cache
126
+ ok = False
127
+ try:
128
+ if sys.stdin.isatty() and sys.stderr.isatty():
129
+ if sys.platform == "win32":
130
+ ok = msvcrt is not None and _enable_windows_vt()
131
+ else:
132
+ ok = _termios is not None and _tty is not None and _select is not None
133
+ except Exception: # noqa: BLE001 — isatty on a closed stream, etc.
134
+ ok = False
135
+ _available_cache = ok
136
+ return ok
137
+
138
+
139
+ # --- key input ----------------------------------------------------------------
140
+
141
+
142
+ def _read_key_unix() -> str | tuple[str, str]:
143
+ fd = sys.stdin.fileno()
144
+ first = os.read(fd, 1)
145
+ if not first:
146
+ return "esc" # EOF — treat as cancel
147
+ byte = first[0]
148
+ if byte == 0x1B:
149
+ # Bare Esc vs. escape sequence: wait briefly for follow-up bytes.
150
+ if not _select.select([fd], [], [], 0.025)[0]:
151
+ return "esc"
152
+ seq = os.read(fd, 1)
153
+ if seq not in (b"[", b"O"):
154
+ return "other" # Alt+key etc.
155
+ body = b""
156
+ while True:
157
+ nxt = os.read(fd, 1)
158
+ if not nxt:
159
+ return "esc"
160
+ body += nxt
161
+ if nxt == b"~" or (0x40 <= nxt[0] <= 0x7E):
162
+ break
163
+ if body in (b"A",):
164
+ return "up"
165
+ if body in (b"B",):
166
+ return "down"
167
+ if body in (b"C",):
168
+ return "right"
169
+ if body in (b"D",):
170
+ return "left"
171
+ if body in (b"H", b"1~", b"7~"):
172
+ return "home"
173
+ if body in (b"F", b"4~", b"8~"):
174
+ return "end"
175
+ if body == b"3~":
176
+ return "delete"
177
+ return "other"
178
+ if byte in (0x7F, 0x08):
179
+ return "backspace"
180
+ if byte == 0x09:
181
+ return "tab"
182
+ if byte in (0x0D, 0x0A):
183
+ return "enter"
184
+ if byte == 0x15:
185
+ return "ctrl_u"
186
+ if byte >= 0x20:
187
+ if byte < 0x80:
188
+ return ("char", chr(byte))
189
+ # UTF-8 multibyte: gather continuation bytes.
190
+ length = 2 if byte < 0xE0 else 3 if byte < 0xF0 else 4
191
+ rest = os.read(fd, length - 1)
192
+ try:
193
+ return ("char", (first + rest).decode("utf-8"))
194
+ except UnicodeDecodeError:
195
+ return "other"
196
+ return "other"
197
+
198
+
199
+ def _read_key_win() -> str | tuple[str, str]: # pragma: no cover — Windows only
200
+ ch = msvcrt.getwch()
201
+ if ch in ("\x00", "\xe0"):
202
+ return _WIN_KEYMAP.get(msvcrt.getwch(), "other")
203
+ if ch == "\x03":
204
+ raise KeyboardInterrupt
205
+ if ch == "\x1b":
206
+ return "esc"
207
+ if ch == "\r":
208
+ return "enter"
209
+ if ch == "\t":
210
+ return "tab"
211
+ if ch == "\x08":
212
+ return "backspace"
213
+ if ch == "\x15":
214
+ return "ctrl_u"
215
+ if ch >= " ":
216
+ return ("char", ch)
217
+ return "other"
218
+
219
+
220
+ def _read_key() -> str | tuple[str, str]:
221
+ if sys.platform == "win32":
222
+ return _read_key_win()
223
+ return _read_key_unix()
224
+
225
+
226
+ @contextmanager
227
+ def _raw_terminal():
228
+ """cbreak mode on POSIX (ISIG kept → Ctrl+C raises). No-op on Windows."""
229
+ if sys.platform == "win32" or _termios is None:
230
+ yield
231
+ return
232
+ fd = sys.stdin.fileno()
233
+ old = _termios.tcgetattr(fd)
234
+ try:
235
+ _tty.setcbreak(fd)
236
+ yield
237
+ finally:
238
+ _termios.tcsetattr(fd, _termios.TCSADRAIN, old)
239
+
240
+
241
+ # --- rendering ----------------------------------------------------------------
242
+
243
+
244
+ class _Frame:
245
+ """Tracks an on-screen frame so redraws rewind to its first row."""
246
+
247
+ def __init__(self) -> None:
248
+ self.rows = 0
249
+ self.cursor_row = 0
250
+
251
+ def draw(self, lines: list[str], cursor_row: int, cursor_col: int) -> None:
252
+ out: list[str] = []
253
+ if self.rows:
254
+ if self.cursor_row:
255
+ out.append(f"\x1b[{self.cursor_row}A")
256
+ out.append("\r\x1b[0J")
257
+ for i, line in enumerate(lines):
258
+ out.append(line)
259
+ if i != len(lines) - 1:
260
+ out.append("\n")
261
+ up = len(lines) - 1 - cursor_row
262
+ if up > 0:
263
+ out.append(f"\x1b[{up}A")
264
+ out.append("\r")
265
+ if cursor_col:
266
+ out.append(f"\x1b[{cursor_col}C")
267
+ _err("".join(out))
268
+ self.rows = len(lines)
269
+ self.cursor_row = cursor_row
270
+
271
+ def _rewind(self) -> str:
272
+ out = ""
273
+ if self.rows:
274
+ if self.cursor_row:
275
+ out += f"\x1b[{self.cursor_row}A"
276
+ out += "\r\x1b[0J"
277
+ self.rows = 0
278
+ self.cursor_row = 0
279
+ return out
280
+
281
+ def finish(self, line: str) -> None:
282
+ """Clear the frame and print a final line in its place."""
283
+ _err(self._rewind() + line + "\n")
284
+
285
+ def clear(self) -> None:
286
+ """Remove the frame without printing anything (wizard back-step)."""
287
+ _err(self._rewind())
288
+
289
+
290
+ def _title_line(title: str, content: str) -> str:
291
+ return f"{_c(_YELLOW, '?')} {_c(_BOLD, title)} {_c(_GRAY, '›')} {content}"
292
+
293
+
294
+ def _done_line(title: str, value: str) -> str:
295
+ return f"{_c(_GREEN, '✔')} {_c(_BOLD, title)} {_c(_GRAY, '·')} {_c(_GREEN, value)}"
296
+
297
+
298
+ def _error_line(title: str, message: str) -> str:
299
+ return f"{_c(_RED, '✘')} {_c(_BOLD, title)} {_c(_GRAY, '·')} {_c(_RED, message)}"
300
+
301
+
302
+ def _prefix_len(title: str) -> int:
303
+ return len(title) + 5 # "? " + title + " › "
304
+
305
+
306
+ # --- line editor --------------------------------------------------------------
307
+
308
+
309
+ class _LineBuffer:
310
+ def __init__(self) -> None:
311
+ self.buf: list[str] = []
312
+ self.cursor = 0
313
+
314
+ @property
315
+ def text(self) -> str:
316
+ return "".join(self.buf)
317
+
318
+ @property
319
+ def at_end(self) -> bool:
320
+ return self.cursor == len(self.buf)
321
+
322
+ def insert(self, ch: str) -> None:
323
+ self.buf.insert(self.cursor, ch)
324
+ self.cursor += 1
325
+
326
+ def append(self, text: str) -> None:
327
+ self.buf.extend(text)
328
+ self.cursor = len(self.buf)
329
+
330
+ def backspace(self) -> None:
331
+ if self.cursor > 0:
332
+ del self.buf[self.cursor - 1]
333
+ self.cursor -= 1
334
+
335
+ def delete(self) -> None:
336
+ if self.cursor < len(self.buf):
337
+ del self.buf[self.cursor]
338
+
339
+ def clear(self) -> None:
340
+ self.buf.clear()
341
+ self.cursor = 0
342
+
343
+ def set(self, text: str) -> None:
344
+ self.buf = list(text)
345
+ self.cursor = len(self.buf)
346
+
347
+ def left(self) -> None:
348
+ self.cursor = max(0, self.cursor - 1)
349
+
350
+ def right(self) -> None:
351
+ self.cursor = min(len(self.buf), self.cursor + 1)
352
+
353
+ def home(self) -> None:
354
+ self.cursor = 0
355
+
356
+ def end(self) -> None:
357
+ self.cursor = len(self.buf)
358
+
359
+
360
+ # --- widgets ------------------------------------------------------------------
361
+
362
+
363
+ def _prompt(
364
+ title: str,
365
+ footer: str,
366
+ ghost_fn,
367
+ on_tab,
368
+ on_enter,
369
+ done_value_fn,
370
+ mask: bool = False,
371
+ ) -> str | None:
372
+ """Shared input-widget loop.
373
+
374
+ ghost_fn(text, at_end) -> (dim_ghost, normal_ghost)
375
+ on_tab(line_buffer) -> None
376
+ on_enter(text) -> (value | None, error | None); value None → keep editing
377
+ done_value_fn(value) -> text shown in the ✔ line
378
+ """
379
+ lb = _LineBuffer()
380
+ frame = _Frame()
381
+ error: str | None = None
382
+ with _raw_terminal():
383
+ while True:
384
+ dim_ghost, normal_ghost = ghost_fn(lb.text, lb.at_end)
385
+ shown = "*" * len(lb.buf) if mask else lb.text
386
+ content = shown + _c("2", dim_ghost) + normal_ghost
387
+ lines = [_title_line(title, content)]
388
+ if error:
389
+ lines.append(_error_line(title, error))
390
+ lines += ["", "", _c(_GRAY, footer)]
391
+ frame.draw(lines, 0, _prefix_len(title) + lb.cursor)
392
+ try:
393
+ key = _read_key()
394
+ except KeyboardInterrupt:
395
+ frame.finish(CANCELLED_CTRL_C)
396
+ return None
397
+ error = None
398
+ if key == "esc":
399
+ frame.clear()
400
+ return None
401
+ if key == "enter":
402
+ value, error = on_enter(lb.text)
403
+ if value is not None:
404
+ frame.finish(_done_line(title, done_value_fn(value)))
405
+ return value
406
+ continue
407
+ if key == "tab":
408
+ on_tab(lb)
409
+ elif key == "backspace":
410
+ lb.backspace()
411
+ elif key == "delete":
412
+ lb.delete()
413
+ elif key == "left":
414
+ lb.left()
415
+ elif key == "right":
416
+ lb.right()
417
+ elif key == "home":
418
+ lb.home()
419
+ elif key == "end":
420
+ lb.end()
421
+ elif key == "ctrl_u":
422
+ lb.clear()
423
+ elif isinstance(key, tuple) and key[0] == "char":
424
+ lb.insert(key[1])
425
+
426
+
427
+ def prompt_server(default_host: str) -> str | None:
428
+ """Server host prompt; ghost-prefills ``default_host`` and ``:13080``."""
429
+ suffix = "" if (":" in default_host or "/" in default_host) else ":13080"
430
+
431
+ def ghost_fn(text: str, at_end: bool) -> tuple[str, str]:
432
+ if not at_end:
433
+ return "", ""
434
+ if not text:
435
+ return default_host + suffix, ""
436
+ if ":" not in text and "/" not in text:
437
+ return ":13080", ""
438
+ return "", ""
439
+
440
+ def on_tab(lb: _LineBuffer) -> None:
441
+ if not lb.text:
442
+ lb.set(default_host + suffix)
443
+ elif ":" not in lb.text and "/" not in lb.text:
444
+ lb.append(":13080")
445
+
446
+ def on_enter(text: str) -> tuple[str | None, str | None]:
447
+ if not text:
448
+ return None, "cannot be empty"
449
+ if ":" not in text and "/" not in text:
450
+ return text + ":13080", None
451
+ return text, None
452
+
453
+ return _prompt(
454
+ "Server",
455
+ TIPS_SERVER,
456
+ ghost_fn,
457
+ on_tab,
458
+ on_enter,
459
+ lambda value: value,
460
+ )
461
+
462
+
463
+ def prompt_email(default_local: str, domain: str) -> str | None:
464
+ """Email prompt; ``domain`` includes the leading ``@``."""
465
+
466
+ def ghost_fn(text: str, at_end: bool) -> tuple[str, str]:
467
+ if not at_end or "@" in text:
468
+ return "", ""
469
+ if not text:
470
+ return default_local, domain
471
+ return domain, ""
472
+
473
+ def on_tab(lb: _LineBuffer) -> None:
474
+ if not lb.text:
475
+ lb.set(default_local)
476
+ elif "@" not in lb.text:
477
+ lb.append(domain)
478
+
479
+ def on_enter(text: str) -> tuple[str | None, str | None]:
480
+ if "@" in text:
481
+ local, _, host = text.partition("@")
482
+ if not local:
483
+ return None, "cannot be empty"
484
+ if not host:
485
+ return None, "invalid email"
486
+ return text, None
487
+ if not text:
488
+ return None, "cannot be empty"
489
+ return text + domain, None
490
+
491
+ return _prompt(
492
+ "Email",
493
+ TIPS_EMAIL,
494
+ ghost_fn,
495
+ on_tab,
496
+ on_enter,
497
+ lambda value: value,
498
+ )
499
+
500
+
501
+ def prompt_password(title: str = "Password") -> str | None:
502
+ """Masked password prompt; empty Enter is ignored, echo is ``********``."""
503
+
504
+ def ghost_fn(text: str, at_end: bool) -> tuple[str, str]:
505
+ return "", ""
506
+
507
+ def on_tab(lb: _LineBuffer) -> None:
508
+ return None
509
+
510
+ def on_enter(text: str) -> tuple[str | None, str | None]:
511
+ if not text:
512
+ return None, None
513
+ return text, None
514
+
515
+ return _prompt(
516
+ title,
517
+ TIPS_PASSWORD,
518
+ ghost_fn,
519
+ on_tab,
520
+ on_enter,
521
+ lambda _value: "********",
522
+ mask=True,
523
+ )
524
+
525
+
526
+ def select(title: str, options: list[str]) -> int | None:
527
+ """Arrow-key single-choice list; wraps around, Esc/Ctrl+C cancel."""
528
+ idx = 0
529
+ frame = _Frame()
530
+ with _raw_terminal():
531
+ while True:
532
+ lines = [f"{_c(_YELLOW, '?')} {_c(_BOLD, title)} {_c(_GRAY, '›')}"]
533
+ for i, option in enumerate(options):
534
+ if i == idx:
535
+ lines.append(f"{_c(_GREEN, '❯')} {_c(_BOLD, option)}")
536
+ else:
537
+ lines.append(f" {option}")
538
+ lines += ["", "", _c(_GRAY, TIPS_SELECT)]
539
+ frame.draw(lines, len(lines) - 1, 0)
540
+ try:
541
+ key = _read_key()
542
+ except KeyboardInterrupt:
543
+ frame.finish(CANCELLED_CTRL_C)
544
+ return None
545
+ if key in ("up",) or key == ("char", "k"):
546
+ idx = (idx - 1) % len(options)
547
+ elif key in ("down",) or key == ("char", "j"):
548
+ idx = (idx + 1) % len(options)
549
+ elif key == "enter":
550
+ frame.finish(_done_line(title, options[idx]))
551
+ return idx
552
+ elif key == "esc":
553
+ frame.finish(CANCELLED_ESC)
554
+ return None
555
+
556
+
557
+ # --- brand header (stderr, same channel as widget frames) ---------------------
558
+
559
+
560
+ def print_brand_header() -> None:
561
+ """One-line brand header printed before the interactive login UI."""
562
+ color = sys.stderr.isatty()
563
+ mark = _c(_YELLOW, "◆") if color else "◆"
564
+ name = _c(_BOLD, "MLOPS Platform") if color else "MLOPS Platform"
565
+ suffix = "— sign in to continue"
566
+ _err(f"{mark} {name} {_c(_GRAY, suffix) if color else suffix}\n")
567
+
568
+
569
+ def print_login_failure(message: str) -> None:
570
+ """One-line login failure notice on stderr (mirrors _error_line style)."""
571
+ color = sys.stderr.isatty()
572
+ mark = _c(_RED, "✘") if color else "✘"
573
+ sep = _c(_GRAY, "·") if color else "·"
574
+ _err(f"{mark} Login failed {sep} {message}\n")
575
+
576
+
577
+ # --- stdout summary blocks (CLI-mirrored) -------------------------------------
578
+
579
+
580
+ def _out(text: str = "") -> None:
581
+ sys.stdout.write(text + "\n")
582
+ sys.stdout.flush()
583
+
584
+
585
+ def _label(s: str, color: bool) -> str:
586
+ """Fixed-width dim label for ``key: value`` lines (CLI ``label()``)."""
587
+ padded = f"{s:<12}"
588
+ return _c(_GRAY, padded) if color else padded
589
+
590
+
591
+ def print_device_instructions(*, user_code: str, url: str, expires_in: int) -> None:
592
+ """Print device authorization instructions to stdout."""
593
+ color = sys.stdout.isatty()
594
+ dot = _c(_GREEN, "●") if color else "●"
595
+ minutes = max(1, expires_in // 60)
596
+ waiting = f"Waiting for authorization… (expires in {minutes} minutes)"
597
+ if color:
598
+ shown_url = f"\x1b]8;;{url}\x1b\\{_c(f'{_LINK};{_UNDERLINE}', url)}\x1b]8;;\x1b\\"
599
+ shown_code = _c(_BOLD, user_code)
600
+ else:
601
+ shown_url = url
602
+ shown_code = user_code
603
+ _out()
604
+ _out(f"{dot} Authorize this device in your browser")
605
+ _out()
606
+ _out(f" {_label('Code', color)}{shown_code}")
607
+ _out(f" {_label('URL', color)}{shown_url}")
608
+ _out()
609
+ _out(_c(_GRAY, waiting) if color else waiting)
610
+
611
+
612
+ def print_login_success(*, display_name: str, email: str) -> None:
613
+ """Print the one-line login success message to stdout."""
614
+ color = sys.stdout.isatty()
615
+ dot = _c(_GREEN, "●") if color else "●"
616
+ name = _c(_BOLD, display_name) if color else display_name
617
+ _out()
618
+ _out(f"{dot} Logged in to MLOPS Platform as {name} ({email})")
619
+ _out()
620
+
621
+
622
+ def print_experiment_created(url: str) -> None:
623
+ """One-line experiment link after create_experiment; TTY only."""
624
+ if not sys.stdout.isatty():
625
+ return
626
+ shown = f"\x1b]8;;{url}\x1b\\{_c(f'{_LINK};{_UNDERLINE}', url)}\x1b]8;;\x1b\\"
627
+ _out()
628
+ _out(f"{_c(_GREEN, '●')} Experiment created: {shown}")
629
+ _out()
630
+
631
+
632
+ def print_profile(
633
+ *,
634
+ display_name: str,
635
+ email: str,
636
+ roles: list[str],
637
+ permissions: list[str],
638
+ server: str,
639
+ ) -> None:
640
+ """Print the CLI-style whoami profile block to stdout."""
641
+ color = sys.stdout.isatty()
642
+
643
+ def header(s: str) -> str:
644
+ return _c(_BOLD, s) if color else s
645
+
646
+ dot = _c(_GREEN, "●") if color else "●"
647
+ _out()
648
+ _out(f"{dot} Logged in as {email}")
649
+ _out()
650
+ _out(header("Server"))
651
+ _out(f" {_label('API base', color)}{server}")
652
+ _out()
653
+ _out(header("Account"))
654
+ _out(f" {_label('Name', color)}{display_name} ({email})")
655
+ _out(f" {_label('Roles', color)}{', '.join(roles)}")
656
+ if permissions:
657
+ per_line = 4
658
+ preview = permissions[:12]
659
+ more = len(permissions) - len(preview)
660
+ for i in range(0, len(preview), per_line):
661
+ chunk = ", ".join(preview[i : i + per_line])
662
+ if i == 0:
663
+ _out(f" {_label('Permissions', color)}{chunk}")
664
+ else:
665
+ _out(f" {'':<12}{chunk}")
666
+ if more > 0:
667
+ _out(f" {'':<12}… and {more} more")
668
+ _out()