slurm-cli 1.0.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,1360 @@
1
+ """Profile management for Slurm CLI output formatting.
2
+
3
+ Profiles define custom output templates for different resource types.
4
+ They can be loaded from:
5
+ - /etc/slurm/cli.profiles (system-wide)
6
+ - ~/.config/slurm-cli.profiles (user-specific)
7
+ - CLI option --profile-str (inline)
8
+ - CLI option --profile (named profile from file)
9
+
10
+ Profile file format (YAML-like):
11
+
12
+ ```
13
+ [profile:compact]
14
+ # Column-based format (table output)
15
+ accounts.columns = name,description
16
+ accounts.styles.name = cyan bold
17
+
18
+ # Template-based format (free-form output)
19
+ # Use {field} for field values, Rich markup for colors, \\n for newlines
20
+ accounts.template = [cyan]{name}[/cyan] - {description}
21
+
22
+ qos.template = [bold]{name}[/bold] Priority: [green]{priority}[/green]
23
+
24
+ reservations.template = [cyan bold]{name}[/cyan bold]\\n\
25
+ Time: {start_time} -> {end_time}\\n\
26
+ Users: [hot_pink]{users}[/hot_pink]
27
+ ```
28
+
29
+ Inline profile string format:
30
+ accounts.template=[cyan]{name}[/] - {description}
31
+
32
+ Template syntax:
33
+ - {field_name} - replaced with field value
34
+ - [color]text[/color] - Rich markup for styling
35
+ - \\n - newline (separates records visually)
36
+
37
+ """
38
+
39
+ import os
40
+ import re
41
+ from pathlib import Path
42
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
43
+
44
+ # Profile file locations (in order of precedence, later overrides earlier)
45
+ PROFILE_FILES = [
46
+ "/etc/slurm/cli.profiles",
47
+ str(Path.home() / ".config" / "slurm-cli.profiles"),
48
+ ]
49
+
50
+ # Available fields for each resource type (for autocomplete)
51
+ RESOURCE_FIELDS: Dict[str, List[str]] = {
52
+ "jobs": [
53
+ "job_id",
54
+ "name",
55
+ "user_name",
56
+ "account",
57
+ "partition",
58
+ "job_state",
59
+ "time_limit",
60
+ "endlimit",
61
+ "node_count",
62
+ "nodes",
63
+ "cpus",
64
+ "gres",
65
+ "submit_time",
66
+ "start_time",
67
+ "end_time",
68
+ "priority",
69
+ "reason",
70
+ "command",
71
+ "working_directory",
72
+ "standard_output",
73
+ "standard_error",
74
+ ],
75
+ "nodes": [
76
+ "name",
77
+ "state",
78
+ "cpus",
79
+ "real_memory",
80
+ "gres",
81
+ "partitions",
82
+ "features",
83
+ "reason",
84
+ "alloc_cpus",
85
+ "alloc_memory",
86
+ ],
87
+ "partitions": [
88
+ "partitionname",
89
+ "state",
90
+ "nodes",
91
+ "totalnodes",
92
+ "totalcpus",
93
+ "maxtime",
94
+ "default",
95
+ "defaulttime",
96
+ "defmempercpu",
97
+ "defmempernode",
98
+ "allowgroups",
99
+ "allowaccounts",
100
+ "allowqos",
101
+ "denyaccounts",
102
+ "denyqos",
103
+ "maxnodes",
104
+ "minnodes",
105
+ "maxcpuspernode",
106
+ "maxcpuspersocket",
107
+ "maxmempercpu",
108
+ "maxmempernode",
109
+ "prioritytier",
110
+ "priorityjobfactor",
111
+ "preemptmode",
112
+ "gracetime",
113
+ "oversubscribe",
114
+ "overtimelimit",
115
+ "qos",
116
+ "alternate",
117
+ "allocnodes",
118
+ "cpubind",
119
+ "disablerootjobs",
120
+ "exclusiveuser",
121
+ "hidden",
122
+ "jobdefaults",
123
+ "lln",
124
+ "powerdownonidle",
125
+ "reqresv",
126
+ "rootonly",
127
+ "shared",
128
+ "tresbillingweights",
129
+ ],
130
+ "accounts": [
131
+ "name",
132
+ "description",
133
+ "organization",
134
+ "coordinators",
135
+ "flags",
136
+ ],
137
+ "users": [
138
+ "name",
139
+ "default_account",
140
+ "admin_level",
141
+ "coordinators",
142
+ ],
143
+ "qos": [
144
+ "name",
145
+ "id",
146
+ "priority",
147
+ "max_wall",
148
+ "max_jobs",
149
+ "max_submit",
150
+ "flags",
151
+ "preempt",
152
+ "preempt_mode",
153
+ "grace_time",
154
+ ],
155
+ "reservations": [
156
+ "name",
157
+ "start_time",
158
+ "end_time",
159
+ "nodes",
160
+ "users",
161
+ "accounts",
162
+ "partition",
163
+ "state",
164
+ "flags",
165
+ ],
166
+ "associations": [
167
+ "account",
168
+ "user",
169
+ "cluster",
170
+ "partition",
171
+ "parent_account",
172
+ "qos",
173
+ "default_qos",
174
+ "shares",
175
+ "grp_jobs",
176
+ "grp_submit",
177
+ ],
178
+ "coordinators": [
179
+ "account",
180
+ "name",
181
+ ],
182
+ "events": [
183
+ "time",
184
+ "cluster",
185
+ "node",
186
+ "state",
187
+ "reason",
188
+ "user",
189
+ ],
190
+ }
191
+
192
+ # Default profile templates
193
+ DEFAULT_PROFILES: Dict[str, Dict[str, Any]] = {
194
+ "default": {
195
+ # Use dynamic columns (show all non-empty columns)
196
+ "accounts": {
197
+ "columns": "*",
198
+ "styles": {
199
+ "name": "cyan",
200
+ "description": "white",
201
+ "organization": "green",
202
+ "coordinators": "yellow",
203
+ },
204
+ },
205
+ "qos": {
206
+ "columns": "*",
207
+ "styles": {
208
+ "name": "cyan bold",
209
+ "id": "dim",
210
+ "priority": "green",
211
+ "flags": "yellow",
212
+ },
213
+ },
214
+ "partitions": {
215
+ "columns": "*",
216
+ "styles": {
217
+ "name": "cyan bold",
218
+ "state": "green",
219
+ "nodes": "yellow",
220
+ },
221
+ },
222
+ "nodes": {
223
+ "columns": "*",
224
+ "styles": {
225
+ "name": "cyan",
226
+ "state": "green",
227
+ },
228
+ },
229
+ "reservations": {
230
+ "columns": "*",
231
+ "styles": {
232
+ "name": "cyan bold",
233
+ "users": "hot_pink",
234
+ "accounts": "green",
235
+ },
236
+ },
237
+ "coordinators": {
238
+ "columns": "*",
239
+ "styles": {
240
+ "account": "cyan",
241
+ "name": "green",
242
+ },
243
+ },
244
+ "users": {
245
+ "columns": "*",
246
+ "styles": {
247
+ "name": "cyan",
248
+ },
249
+ },
250
+ "associations": {
251
+ "columns": "*",
252
+ "styles": {
253
+ "account": "cyan",
254
+ "user": "green",
255
+ "cluster": "yellow",
256
+ "partition": "magenta",
257
+ },
258
+ },
259
+ "jobs": {
260
+ "columns": [
261
+ "job_id",
262
+ "user_name",
263
+ "partition",
264
+ "job_state",
265
+ "start_time",
266
+ "endlimit",
267
+ "node_count",
268
+ "gres",
269
+ "reason",
270
+ ],
271
+ "styles": {
272
+ "job_id": "cyan bold",
273
+ "user_name": "blue",
274
+ "partition": "green",
275
+ "job_state": "yellow",
276
+ "start_time": "green",
277
+ "endlimit": "dim",
278
+ "node_count": "cyan",
279
+ "gres": "magenta",
280
+ },
281
+ },
282
+ },
283
+ "compact": {
284
+ "accounts": {
285
+ "columns": ["name", "description"],
286
+ "styles": {"name": "cyan bold"},
287
+ },
288
+ "qos": {
289
+ "columns": ["name", "priority", "max_wall"],
290
+ "styles": {"name": "cyan bold"},
291
+ },
292
+ "partitions": {
293
+ "columns": ["name", "state", "nodes"],
294
+ "styles": {"name": "cyan bold"},
295
+ },
296
+ "nodes": {
297
+ "columns": ["name", "state", "cpus", "real_memory", "gres"],
298
+ "styles": {"name": "cyan"},
299
+ },
300
+ "reservations": {
301
+ "columns": [
302
+ "name",
303
+ "start_time",
304
+ "end_time",
305
+ "nodes",
306
+ "users",
307
+ ],
308
+ "styles": {"name": "cyan bold", "users": "hot_pink"},
309
+ },
310
+ "coordinators": {
311
+ "columns": ["account", "name"],
312
+ "styles": {"account": "cyan"},
313
+ },
314
+ "users": {
315
+ "columns": ["name", "default_account"],
316
+ "styles": {"name": "cyan"},
317
+ },
318
+ "associations": {
319
+ "columns": ["account", "user", "cluster", "partition"],
320
+ "styles": {"account": "cyan"},
321
+ },
322
+ "jobs": {
323
+ "columns": [
324
+ "job_id",
325
+ "name",
326
+ "user_name",
327
+ "partition",
328
+ "job_state",
329
+ "endlimit",
330
+ "nodes",
331
+ ],
332
+ "styles": {"job_id": "cyan bold", "job_state": "yellow"},
333
+ },
334
+ },
335
+ "minimal": {
336
+ "accounts": {"columns": ["name"]},
337
+ "qos": {"columns": ["name"]},
338
+ "partitions": {"columns": ["name", "state"]},
339
+ "nodes": {"columns": ["name", "state", "gres"]},
340
+ "reservations": {"columns": ["name"]},
341
+ "coordinators": {"columns": ["account", "name"]},
342
+ "users": {"columns": ["name"]},
343
+ "associations": {"columns": ["account", "user"]},
344
+ "jobs": {"columns": ["job_id", "user_name", "job_state"]},
345
+ },
346
+ # Template-based profiles
347
+ "oneline": {
348
+ "accounts": {
349
+ "template": "[cyan]{name}[/cyan] - {description} ({organization})"
350
+ },
351
+ "qos": {
352
+ "template": (
353
+ "[cyan bold]{name}[/cyan bold] "
354
+ "priority=[green]{priority}[/green] "
355
+ "max_jobs/user={max_jobs_per_user} "
356
+ "max_active/user={max_jobs_active_per_user} "
357
+ "max_tres/job=[yellow]{max_tres_per_job}[/yellow] "
358
+ "max_tres/user=[yellow]{max_tres_per_user}[/yellow] "
359
+ "max_tres_total=[yellow]{max_tres_total}[/yellow]"
360
+ )
361
+ },
362
+ "partitions": {
363
+ "template": (
364
+ "[cyan bold]{PartitionName}[/cyan bold] "
365
+ "state=[green]{State}[/green] nodes={TotalNodes}"
366
+ )
367
+ },
368
+ "nodes": {
369
+ "template": (
370
+ "[cyan]{name}[/cyan] "
371
+ "state=[green]{state}[/green] "
372
+ "cpus={cpus} mem={real_memory} gres={gres}"
373
+ )
374
+ },
375
+ "reservations": {
376
+ "template": (
377
+ "[cyan bold]{name}[/cyan bold] "
378
+ "{start_time} -> {end_time} "
379
+ "users=[hot_pink]{users}[/hot_pink]"
380
+ )
381
+ },
382
+ "coordinators": {
383
+ "template": "[cyan]{account}[/cyan]: [green]{name}[/green]"
384
+ },
385
+ "users": {
386
+ "template": "[cyan]{name}[/cyan] ({default_account})"
387
+ },
388
+ "jobs": {
389
+ "template": (
390
+ "[cyan bold]{job_id}[/cyan bold] "
391
+ "[white]{name}[/white] "
392
+ "user=[blue]{user_name}[/blue] "
393
+ "state=[yellow]{job_state}[/yellow] "
394
+ "end=[dim]{endlimit}[/dim] "
395
+ "nodes={node_count}"
396
+ )
397
+ },
398
+ },
399
+ "detailed": {
400
+ "accounts": {
401
+ "template": (
402
+ "[bold cyan]{name}[/bold cyan]\\n"
403
+ " Description: {description}\\n"
404
+ " Organization: [green]{organization}[/green]\\n"
405
+ " Coordinators: [yellow]{coordinators}[/yellow]"
406
+ )
407
+ },
408
+ "reservations": {
409
+ "template": (
410
+ "[bold cyan]{name}[/bold cyan]\\n"
411
+ " Time: {start_time} → {end_time}\\n"
412
+ " Nodes: {node_list} ({node_count})\\n"
413
+ " Users: [hot_pink]{users}[/hot_pink]\\n"
414
+ " Accounts: [green]{accounts}[/green]"
415
+ )
416
+ },
417
+ "jobs": {
418
+ "template": (
419
+ "[bold cyan]{job_id}[/bold cyan] - {name}\\n"
420
+ " User: [blue]{user_name}[/blue] "
421
+ "Account: [green]{account}[/green]\\n"
422
+ " State: [yellow]{job_state}[/yellow] "
423
+ "Partition: [magenta]{partition}[/magenta]\\n"
424
+ " Nodes: {node_count} ({nodes}) "
425
+ "GRES: [magenta]{gres}[/magenta]\\n"
426
+ " Start: {start_time} End/Limit: {endlimit}\\n"
427
+ " Reason: {reason}"
428
+ )
429
+ },
430
+ },
431
+ }
432
+
433
+
434
+ class ProfileManager:
435
+ """Manages loading and parsing of output profiles."""
436
+
437
+ def __init__(self):
438
+ self._profiles: Dict[str, Dict[str, Any]] = {}
439
+ self._loaded = False
440
+
441
+ def _load_profiles(self) -> None:
442
+ """Load profiles from all profile files."""
443
+ if self._loaded:
444
+ return
445
+
446
+ # Start with default profiles
447
+ self._profiles = dict(DEFAULT_PROFILES)
448
+
449
+ # Load from profile files
450
+ for filepath in PROFILE_FILES:
451
+ if os.path.exists(filepath):
452
+ try:
453
+ file_profiles = self._parse_profile_file(filepath)
454
+ self._merge_profiles(file_profiles)
455
+ except Exception as e:
456
+ # Silently ignore parse errors in profile files
457
+ import sys
458
+
459
+ print(
460
+ f"Warning: Error parsing profile file {filepath}: {e}",
461
+ file=sys.stderr,
462
+ )
463
+
464
+ self._loaded = True
465
+
466
+ def _parse_profile_file(
467
+ self, filepath: str
468
+ ) -> Dict[str, Dict[str, Any]]:
469
+ """Parse a profile file.
470
+
471
+ Format:
472
+ ```
473
+ [profile:name]
474
+ resource.columns = col1,col2,col3
475
+ resource.styles.field = style
476
+ resource.template = [cyan]{name}[/] - {description}
477
+
478
+ # Multi-line templates with backslash continuation:
479
+ resource.template = [cyan]{name}[/] \\
480
+ Time: {start_time} \\
481
+ Users: {users}
482
+ ```
483
+ """
484
+ profiles: Dict[str, Dict[str, Any]] = {}
485
+ current_profile: Optional[str] = None
486
+
487
+ with open(filepath, "r") as f:
488
+ lines = f.readlines()
489
+
490
+ # Process lines with continuation support
491
+ i = 0
492
+ while i < len(lines):
493
+ line = lines[i].rstrip("\n\r")
494
+
495
+ # Handle line continuation (backslash at end)
496
+ while line.rstrip().endswith("\\") and i + 1 < len(lines):
497
+ # Remove trailing backslash and append next line
498
+ line = line.rstrip()[:-1]
499
+ i += 1
500
+ next_line = lines[i].rstrip("\n\r")
501
+ # Preserve some indentation as space
502
+ line += next_line.lstrip()
503
+
504
+ line = line.strip()
505
+ i += 1
506
+
507
+ # Skip empty lines and comments
508
+ if not line or line.startswith("#"):
509
+ continue
510
+
511
+ # Profile header
512
+ if line.startswith("[profile:") and line.endswith("]"):
513
+ current_profile = line[9:-1].strip()
514
+ if current_profile not in profiles:
515
+ profiles[current_profile] = {}
516
+ continue
517
+
518
+ # Setting line: resource.key = value
519
+ if "=" in line and current_profile:
520
+ key, value = line.split("=", 1)
521
+ key = key.strip()
522
+ value = value.strip()
523
+
524
+ self._set_nested_value(
525
+ profiles[current_profile], key, value
526
+ )
527
+
528
+ return profiles
529
+
530
+ def _set_nested_value(
531
+ self, target: Dict[str, Any], key: str, value: str
532
+ ) -> None:
533
+ """Set a nested value in a dictionary.
534
+
535
+ Key format: resource.columns, resource.styles.field,
536
+ or resource.template
537
+ """
538
+ parts = key.split(".")
539
+ current = target
540
+
541
+ for i, part in enumerate(parts[:-1]):
542
+ if part not in current:
543
+ current[part] = {}
544
+ current = current[part]
545
+
546
+ final_key = parts[-1]
547
+
548
+ # Parse value based on key type
549
+ if final_key == "columns":
550
+ if value == "*":
551
+ current[final_key] = "*"
552
+ else:
553
+ current[final_key] = [
554
+ v.strip() for v in value.split(",")
555
+ ]
556
+ elif final_key == "template":
557
+ # Keep template as-is, but convert escaped newlines
558
+ current[final_key] = value
559
+ else:
560
+ current[final_key] = value
561
+
562
+ def _merge_profiles(
563
+ self, new_profiles: Dict[str, Dict[str, Any]]
564
+ ) -> None:
565
+ """Merge new profiles into existing profiles."""
566
+ for name, profile in new_profiles.items():
567
+ if name in self._profiles:
568
+ self._deep_merge(self._profiles[name], profile)
569
+ else:
570
+ self._profiles[name] = profile
571
+
572
+ def _deep_merge(
573
+ self, base: Dict[str, Any], override: Dict[str, Any]
574
+ ) -> None:
575
+ """Deep merge override into base."""
576
+ for key, value in override.items():
577
+ if (
578
+ key in base
579
+ and isinstance(base[key], dict)
580
+ and isinstance(value, dict)
581
+ ):
582
+ self._deep_merge(base[key], value)
583
+ else:
584
+ base[key] = value
585
+
586
+ def get_profile(self, name: str) -> Optional[Dict[str, Any]]:
587
+ """Get a profile by name."""
588
+ self._load_profiles()
589
+ return self._profiles.get(name)
590
+
591
+ def get_resource_config(
592
+ self, profile_name: str, resource: str
593
+ ) -> Optional[Dict[str, Any]]:
594
+ """Get configuration for a specific resource from a profile."""
595
+ profile = self.get_profile(profile_name)
596
+ if profile:
597
+ return profile.get(resource)
598
+ return None
599
+
600
+ def list_profiles(self) -> List[str]:
601
+ """List all available profile names."""
602
+ self._load_profiles()
603
+ return list(self._profiles.keys())
604
+
605
+ def parse_profile_string(
606
+ self, profile_str: str
607
+ ) -> Dict[str, Dict[str, Any]]:
608
+ """Parse an inline profile string.
609
+
610
+ Format: resource.columns=col1,col2;resource.template=[cyan]{name}[/]
611
+
612
+ Note: Only splits on ';' when followed by a resource.key= pattern.
613
+ This allows templates to contain ';' characters.
614
+ """
615
+ profile: Dict[str, Any] = {}
616
+
617
+ # Smart split: only split on ';' followed by 'word.word='
618
+ # This preserves ';' inside template strings
619
+ parts = []
620
+ current = ""
621
+ i = 0
622
+ while i < len(profile_str):
623
+ if profile_str[i] == ";":
624
+ # Look ahead to see if this looks like a new setting
625
+ rest = profile_str[(i + 1) :].lstrip()
626
+ # Check if rest starts with word.word= pattern
627
+ if re.match(r"^\w+\.\w+=", rest):
628
+ # This is a separator between settings
629
+ if current.strip():
630
+ parts.append(current.strip())
631
+ current = ""
632
+ i += 1
633
+ continue
634
+ current += profile_str[i]
635
+ i += 1
636
+
637
+ if current.strip():
638
+ parts.append(current.strip())
639
+
640
+ for part in parts:
641
+ if "=" in part:
642
+ key, value = part.split("=", 1)
643
+ self._set_nested_value(
644
+ profile, key.strip(), value.strip()
645
+ )
646
+
647
+ return profile
648
+
649
+
650
+ # Global profile manager instance
651
+ _profile_manager: Optional[ProfileManager] = None
652
+
653
+
654
+ def get_profile_manager() -> ProfileManager:
655
+ """Get the global profile manager instance."""
656
+ global _profile_manager
657
+ if _profile_manager is None:
658
+ _profile_manager = ProfileManager()
659
+ return _profile_manager
660
+
661
+
662
+ def parse_columns_with_sort(
663
+ columns: Union[List[str], str, None]
664
+ ) -> Tuple[Optional[Union[List[str], str]], Optional[str], bool]:
665
+ """Parse column list and extract sort field if present.
666
+
667
+ Columns can have + or - suffix to indicate sort order:
668
+ - field+ means sort ascending by field
669
+ - field- means sort descending by field
670
+ Only the first field with a sort marker is used for sorting.
671
+
672
+ Args:
673
+ columns: Column list, "*", or None
674
+
675
+ Returns:
676
+ Tuple of (clean_columns, sort_field, sort_ascending)
677
+ - clean_columns: columns with sort markers removed
678
+ - sort_field: first field marked for sorting (or None)
679
+ - sort_ascending: True for +, False for -
680
+ """
681
+ if columns is None or columns == "*":
682
+ return columns, None, True
683
+
684
+ if isinstance(columns, str):
685
+ columns = [c.strip() for c in columns.split(",")]
686
+
687
+ clean_columns = []
688
+ sort_field = None
689
+ sort_ascending = True
690
+
691
+ for col in columns:
692
+ col = col.strip()
693
+ if col.endswith("+"):
694
+ clean_col = col[:-1]
695
+ if sort_field is None:
696
+ sort_field = clean_col
697
+ sort_ascending = True
698
+ clean_columns.append(clean_col)
699
+ elif col.endswith("-"):
700
+ clean_col = col[:-1]
701
+ if sort_field is None:
702
+ sort_field = clean_col
703
+ sort_ascending = False
704
+ clean_columns.append(clean_col)
705
+ else:
706
+ clean_columns.append(col)
707
+
708
+ return clean_columns, sort_field, sort_ascending
709
+
710
+
711
+ def get_columns_for_resource(
712
+ profile_name: str,
713
+ resource: str,
714
+ profile_str: Optional[str] = None,
715
+ ) -> Optional[Union[List[str], str]]:
716
+ """Get column configuration for a resource.
717
+
718
+ Args:
719
+ profile_name: Name of the profile to use
720
+ resource: Resource type (accounts, qos, etc.)
721
+ profile_str: Optional inline profile string (takes precedence)
722
+
723
+ Returns:
724
+ List of column names, "*" for all columns, or None if not specified
725
+ """
726
+ manager = get_profile_manager()
727
+
728
+ # Check inline profile string first
729
+ if profile_str:
730
+ inline_profile = manager.parse_profile_string(profile_str)
731
+ if resource in inline_profile:
732
+ columns = inline_profile[resource].get("columns")
733
+ if columns:
734
+ return columns
735
+
736
+ # Fall back to named profile
737
+ config = manager.get_resource_config(profile_name, resource)
738
+ if config:
739
+ return config.get("columns")
740
+
741
+ return None
742
+
743
+
744
+ def get_styles_for_resource(
745
+ profile_name: str,
746
+ resource: str,
747
+ profile_str: Optional[str] = None,
748
+ ) -> Dict[str, str]:
749
+ """Get style configuration for a resource.
750
+
751
+ Args:
752
+ profile_name: Name of the profile to use
753
+ resource: Resource type (accounts, qos, etc.)
754
+ profile_str: Optional inline profile string (takes precedence)
755
+
756
+ Returns:
757
+ Dictionary mapping field names to style strings
758
+ """
759
+ manager = get_profile_manager()
760
+ styles: Dict[str, str] = {}
761
+
762
+ # Get styles from named profile first
763
+ config = manager.get_resource_config(profile_name, resource)
764
+ if config:
765
+ styles.update(config.get("styles", {}))
766
+
767
+ # Override with inline profile string
768
+ if profile_str:
769
+ inline_profile = manager.parse_profile_string(profile_str)
770
+ if resource in inline_profile:
771
+ inline_styles = inline_profile[resource].get("styles", {})
772
+ styles.update(inline_styles)
773
+
774
+ return styles
775
+
776
+
777
+ def get_template_for_resource(
778
+ profile_name: str,
779
+ resource: str,
780
+ profile_str: Optional[str] = None,
781
+ ) -> Optional[str]:
782
+ """Get template string for a resource.
783
+
784
+ Args:
785
+ profile_name: Name of the profile to use
786
+ resource: Resource type (accounts, qos, etc.)
787
+ profile_str: Optional inline profile string (takes precedence)
788
+
789
+ Returns:
790
+ Template string or None if not specified
791
+ """
792
+ manager = get_profile_manager()
793
+
794
+ # Check inline profile string first
795
+ if profile_str:
796
+ inline_profile = manager.parse_profile_string(profile_str)
797
+ if resource in inline_profile:
798
+ template = inline_profile[resource].get("template")
799
+ if template:
800
+ return template
801
+
802
+ # Fall back to named profile
803
+ config = manager.get_resource_config(profile_name, resource)
804
+ if config:
805
+ return config.get("template")
806
+
807
+ return None
808
+
809
+
810
+ def _normalize_profile_str(
811
+ profile_str: Optional[str], resource: str
812
+ ) -> Optional[str]:
813
+ """Normalize profile string, adding resource prefix if missing.
814
+
815
+ Supports shorthand formats:
816
+ - "name,organization" -> "resource.columns=name,organization"
817
+ - "[cyan]{name}[/]" -> "resource.template=[cyan]{name}[/]"
818
+
819
+ Args:
820
+ profile_str: Raw profile string
821
+ resource: Current resource type
822
+
823
+ Returns:
824
+ Normalized profile string with proper resource prefix
825
+ """
826
+ if not profile_str:
827
+ return None
828
+
829
+ # Check if it's already in proper format (has resource.key= pattern)
830
+ # Look for pattern like "resource.columns=" or "resource.template="
831
+ if (
832
+ "." in profile_str.split("=")[0]
833
+ if "=" in profile_str
834
+ else False
835
+ ):
836
+ return profile_str
837
+
838
+ # Check if it starts with "columns=" or "template=" or "styles="
839
+ if profile_str.startswith(("columns=", "template=", "styles=")):
840
+ return f"{resource}.{profile_str}"
841
+
842
+ # Check if it looks like a column list (comma-separated words,
843
+ # no template markers like { [ or =)
844
+ if (
845
+ "," in profile_str
846
+ and "{" not in profile_str
847
+ and "[" not in profile_str
848
+ and "=" not in profile_str
849
+ ):
850
+ # Treat as column list
851
+ return f"{resource}.columns={profile_str}"
852
+
853
+ # Check if it's a single word without template markers (single column)
854
+ if (
855
+ "{" not in profile_str
856
+ and "[" not in profile_str
857
+ and "=" not in profile_str
858
+ and " " not in profile_str
859
+ ):
860
+ # Treat as single column
861
+ return f"{resource}.columns={profile_str}"
862
+
863
+ # No resource prefix - treat as raw template for current resource
864
+ return f"{resource}.template={profile_str}"
865
+
866
+
867
+ def get_profile_config(
868
+ profile_name: str,
869
+ resource: str,
870
+ profile_str: Optional[str] = None,
871
+ ) -> Tuple[
872
+ Optional[Union[List[str], str]],
873
+ Dict[str, str],
874
+ Optional[str],
875
+ Optional[str],
876
+ bool,
877
+ ]:
878
+ """Get full configuration for a resource.
879
+
880
+ Args:
881
+ profile_name: Name of the profile to use
882
+ resource: Resource type (accounts, qos, etc.)
883
+ profile_str: Optional inline profile string (takes precedence).
884
+ If no 'resource.' prefix, treated as template for
885
+ current resource.
886
+
887
+ Returns:
888
+ Tuple of (columns, styles, template, sort_field, sort_ascending)
889
+ - columns may be a list, "*", or None (with sort markers removed)
890
+ - styles is a dict mapping field names to style strings
891
+ - template is a string template or None
892
+ - sort_field is the field to sort by (or None)
893
+ - sort_ascending is True for ascending, False for descending
894
+ """
895
+ # Normalize profile_str - add resource prefix if missing
896
+ normalized_str = _normalize_profile_str(profile_str, resource)
897
+
898
+ columns = get_columns_for_resource(
899
+ profile_name, resource, normalized_str
900
+ )
901
+
902
+ # Parse columns for sort info
903
+ columns, sort_field, sort_ascending = parse_columns_with_sort(
904
+ columns
905
+ )
906
+
907
+ styles = get_styles_for_resource(
908
+ profile_name, resource, normalized_str
909
+ )
910
+ template = get_template_for_resource(
911
+ profile_name, resource, normalized_str
912
+ )
913
+ return columns, styles, template, sort_field, sort_ascending
914
+
915
+
916
+ # Default values for fields (field is "empty" if it equals default)
917
+ DEFAULT_FIELD_VALUES: Dict[str, Dict[str, Any]] = {
918
+ "reservations": {
919
+ "accounts": "",
920
+ "users": "",
921
+ "partition": "",
922
+ "flags": "",
923
+ "tres": "",
924
+ },
925
+ "accounts": {
926
+ "coordinators": [],
927
+ "description": "",
928
+ "organization": "",
929
+ },
930
+ "qos": {
931
+ "description": "",
932
+ "flags": [],
933
+ "preempt_list": [],
934
+ },
935
+ "nodes": {
936
+ "reason": "",
937
+ "comment": "",
938
+ },
939
+ "partitions": {
940
+ "allow_accounts": "ALL",
941
+ "deny_accounts": "",
942
+ "allow_qos": "ALL",
943
+ "deny_qos": "",
944
+ },
945
+ }
946
+
947
+
948
+ def is_field_empty(
949
+ field: str,
950
+ value: Any,
951
+ resource: Optional[str] = None,
952
+ ) -> bool:
953
+ """Check if a field value should be considered empty.
954
+
955
+ A field is empty if:
956
+ - Value is None
957
+ - Value is an empty string
958
+ - Value is an empty list
959
+ - Value equals the default value for that field/resource
960
+ - Value is "-"
961
+
962
+ Args:
963
+ field: Field name
964
+ value: Field value
965
+ resource: Optional resource type for default value lookup
966
+
967
+ Returns:
968
+ True if field should be considered empty
969
+ """
970
+ if value is None:
971
+ return True
972
+ if value == "":
973
+ return True
974
+ if value == "-":
975
+ return True
976
+ if isinstance(value, list) and len(value) == 0:
977
+ return True
978
+ if isinstance(value, dict):
979
+ # Handle set/number pattern - empty if not set
980
+ if "set" in value and not value.get("set"):
981
+ return True
982
+
983
+ # Check against default values
984
+ if resource and resource in DEFAULT_FIELD_VALUES:
985
+ defaults = DEFAULT_FIELD_VALUES[resource]
986
+ if field in defaults and value == defaults[field]:
987
+ return True
988
+
989
+ return False
990
+
991
+
992
+ def format_with_template(
993
+ template: str,
994
+ data: Dict[str, Any],
995
+ value_formatter: Optional[Callable[[str, Any], str]] = None,
996
+ resource: Optional[str] = None,
997
+ ) -> str:
998
+ """Format data using a template string.
999
+
1000
+ Args:
1001
+ template: Template string with {field} placeholders
1002
+ data: Dictionary of field values
1003
+ value_formatter: Optional function to format values
1004
+ resource: Optional resource type for default value lookup
1005
+
1006
+ Template syntax:
1007
+ {field} - replaced with field value
1008
+ {?field TEXT} - show TEXT only if field is not empty
1009
+ TEXT can contain {field} placeholders
1010
+
1011
+ Returns:
1012
+ Formatted string with Rich markup
1013
+ """
1014
+ # Convert escaped newlines to actual newlines
1015
+ result = template.replace("\\n", "\n")
1016
+
1017
+ # First, process conditional blocks {?field TEXT}
1018
+ # Pattern matches {?field_name any text including {field} until }
1019
+ # We need to handle nested braces carefully
1020
+ conditional_pattern = re.compile(
1021
+ r"\{\?(\w+)\s+([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}"
1022
+ )
1023
+
1024
+ def replace_conditional(match: re.Match) -> str:
1025
+ field = match.group(1)
1026
+ content = match.group(2)
1027
+ value = data.get(field)
1028
+
1029
+ # Check if field is empty
1030
+ if is_field_empty(field, value, resource):
1031
+ return ""
1032
+
1033
+ # Field is not empty, return the content (will be processed later)
1034
+ return content
1035
+
1036
+ result = conditional_pattern.sub(replace_conditional, result)
1037
+
1038
+ # Now process regular {field} placeholders
1039
+ field_pattern = re.compile(r"\{(\w+)\}")
1040
+
1041
+ def replace_field(match: re.Match) -> str:
1042
+ field = match.group(1)
1043
+ value = data.get(field)
1044
+
1045
+ if value is None:
1046
+ return "-"
1047
+
1048
+ # Format value
1049
+ if value_formatter:
1050
+ return value_formatter(field, value)
1051
+
1052
+ # Handle common types
1053
+ if isinstance(value, list):
1054
+ return ", ".join(str(v) for v in value) if value else "-"
1055
+ elif isinstance(value, dict):
1056
+ # Handle set/number pattern
1057
+ if value.get("set"):
1058
+ return str(value.get("number", "-"))
1059
+ elif value.get("infinite"):
1060
+ return "∞"
1061
+ return str(value)
1062
+
1063
+ return str(value) if value != "" else "-"
1064
+
1065
+ return field_pattern.sub(replace_field, result)
1066
+
1067
+
1068
+ def extract_fields_from_template(template: str) -> List[str]:
1069
+ """Extract field names from a template string.
1070
+
1071
+ Args:
1072
+ template: Template string with {field} placeholders
1073
+
1074
+ Returns:
1075
+ List of field names found in the template
1076
+ """
1077
+ # Match both regular {field} and conditional {?field ...}
1078
+ pattern = re.compile(r"\{(\w+)\}|\{\?(\w+)\s+")
1079
+ matches = pattern.findall(template)
1080
+ # Flatten and filter empty strings
1081
+ return [m[0] or m[1] for m in matches if m[0] or m[1]]
1082
+
1083
+
1084
+ def _get_resource_fields() -> Dict[str, Dict[str, str]]:
1085
+ """Build RESOURCE_FIELDS from resource classes.
1086
+
1087
+ Lazily imports resource classes to avoid circular imports.
1088
+ """
1089
+ # Import here to avoid circular imports
1090
+ from .accounts import Account
1091
+ from .associations import Association
1092
+ from .coordinators import Coordinator
1093
+ from .events import Event
1094
+ from .jobs import Job
1095
+ from .nodes import Node
1096
+ from .partitions import Partition
1097
+ from .qos import Qos
1098
+ from .reservations import Reservation
1099
+ from .users import User
1100
+
1101
+ return {
1102
+ "accounts": Account.get_profile_fields(),
1103
+ "associations": Association.get_profile_fields(),
1104
+ "coordinators": Coordinator.get_profile_fields(),
1105
+ "events": Event.get_profile_fields(),
1106
+ "jobs": Job.get_profile_fields(),
1107
+ "nodes": Node.get_profile_fields(),
1108
+ "partitions": Partition.get_profile_fields(),
1109
+ "qos": Qos.get_profile_fields(),
1110
+ "reservations": Reservation.get_profile_fields(),
1111
+ "users": User.get_profile_fields(),
1112
+ }
1113
+
1114
+
1115
+ # Available fields for each resource type (for --profile-str=help)
1116
+ # Lazily initialized to avoid circular imports
1117
+ _RESOURCE_FIELDS: Optional[Dict[str, Dict[str, str]]] = None
1118
+
1119
+
1120
+ def get_resource_fields() -> Dict[str, Dict[str, str]]:
1121
+ """Get available fields for each resource type."""
1122
+ global _RESOURCE_FIELDS
1123
+ if _RESOURCE_FIELDS is None:
1124
+ _RESOURCE_FIELDS = _get_resource_fields()
1125
+ return _RESOURCE_FIELDS
1126
+
1127
+
1128
+ def show_profile_help(resource: str) -> bool:
1129
+ """Show available fields for a resource.
1130
+
1131
+ Args:
1132
+ resource: Resource type name (can be short form like 'res')
1133
+
1134
+ Returns:
1135
+ True if help was shown, False otherwise
1136
+ """
1137
+ # Map short resource names to full names
1138
+ resource_map = {
1139
+ "res": "reservations",
1140
+ "acc": "accounts",
1141
+ "assoc": "associations",
1142
+ "part": "partitions",
1143
+ "node": "nodes",
1144
+ "user": "users",
1145
+ "coord": "coordinators",
1146
+ "conf": "config",
1147
+ "job": "jobs",
1148
+ "event": "events",
1149
+ }
1150
+
1151
+ # Try to match by prefix
1152
+ full_resource = resource
1153
+ for prefix, full_name in resource_map.items():
1154
+ if resource.startswith(prefix):
1155
+ full_resource = full_name
1156
+ break
1157
+
1158
+ resource_fields = get_resource_fields()
1159
+ if full_resource not in resource_fields:
1160
+ print(f"No field documentation for resource: {resource}")
1161
+ print(
1162
+ f"Available resources: {', '.join(resource_fields.keys())}"
1163
+ )
1164
+ return True
1165
+
1166
+ fields = resource_fields[full_resource]
1167
+ print(f"\nAvailable fields for '{full_resource}':\n")
1168
+ print(" Field Description")
1169
+ print(" " + "-" * 55)
1170
+ for field, desc in sorted(fields.items()):
1171
+ print(f" {field:<24} {desc}")
1172
+ print()
1173
+ print("Template syntax:")
1174
+ print(" {field} - Show field value")
1175
+ print(" {?field TEXT} - Show TEXT only if field is not empty")
1176
+ print(" [color]...[/] - Rich markup for colors")
1177
+ print(" \\n - Newline")
1178
+ print()
1179
+ print("Example:")
1180
+ print(' --profile-str "[cyan]{name}[/] - description"')
1181
+ print()
1182
+ return True
1183
+
1184
+
1185
+ def is_profile_help(profile_str: Optional[str]) -> bool:
1186
+ """Check if profile_str is a help request."""
1187
+ return profile_str is not None and profile_str.lower() == "help"
1188
+
1189
+
1190
+ def show_all_profile_fields() -> None:
1191
+ """Show available fields for all resources."""
1192
+ resource_fields = get_resource_fields()
1193
+
1194
+ print("\nAvailable profile fields by resource:\n")
1195
+ print("=" * 70)
1196
+
1197
+ for resource in sorted(resource_fields.keys()):
1198
+ fields = resource_fields[resource]
1199
+ print(f"\n[{resource}]")
1200
+ print("-" * 40)
1201
+ for field, desc in sorted(fields.items()):
1202
+ print(f" {field:<24} {desc}")
1203
+
1204
+ print("\n" + "=" * 70)
1205
+ print("\nSorting:")
1206
+ print(" field+ - Sort ascending by field")
1207
+ print(" field- - Sort descending by field")
1208
+ print("\nTemplate syntax:")
1209
+ print(" {field} - Show field value")
1210
+ print(
1211
+ " {?field TEXT} - Show TEXT only if field is not empty"
1212
+ )
1213
+ print(" [color]...[/] - Rich markup for colors")
1214
+ print(" \\n - Newline")
1215
+ print("\nExample:")
1216
+ print(' --profile-str "name+,description"')
1217
+ print(' --profile-str "[cyan]{name}[/] - {description}"')
1218
+ print()
1219
+
1220
+
1221
+ def sort_data(
1222
+ data: List[Dict[str, Any]],
1223
+ sort_field: Optional[str],
1224
+ ascending: bool = True,
1225
+ ) -> List[Dict[str, Any]]:
1226
+ """Sort a list of dictionaries by a field.
1227
+
1228
+ Handles mixed types (strings, numbers, None) gracefully.
1229
+
1230
+ Args:
1231
+ data: List of dictionaries to sort
1232
+ sort_field: Field name to sort by (None for no sorting)
1233
+ ascending: True for ascending, False for descending
1234
+
1235
+ Returns:
1236
+ Sorted list (or original if sort_field is None)
1237
+ """
1238
+ if not sort_field or not data:
1239
+ return data
1240
+
1241
+ def sort_key(item: Dict[str, Any]) -> Any:
1242
+ value = item.get(sort_field)
1243
+ # Handle None values - sort them last
1244
+ if value is None or value == "-" or value == "":
1245
+ return (1, "")
1246
+ # Try to convert to number for proper numeric sorting
1247
+ try:
1248
+ return (0, float(value))
1249
+ except (ValueError, TypeError):
1250
+ # Fall back to string comparison
1251
+ return (0, str(value).lower())
1252
+
1253
+ return sorted(data, key=sort_key, reverse=not ascending)
1254
+
1255
+
1256
+ def sort_hierarchical_data(
1257
+ data: List[Dict[str, Any]],
1258
+ sort_field: Optional[str],
1259
+ ascending: bool = True,
1260
+ depth_key: str = "_depth",
1261
+ parent_key: str = "parent_account",
1262
+ id_key: str = "account",
1263
+ ) -> List[Dict[str, Any]]:
1264
+ """Sort hierarchical data, preserving parent-child relationships.
1265
+
1266
+ Within each hierarchy level, items are sorted independently.
1267
+
1268
+ Args:
1269
+ data: List of dictionaries with hierarchy info
1270
+ sort_field: Field name to sort by (None for no sorting)
1271
+ ascending: True for ascending, False for descending
1272
+ depth_key: Key that stores the depth level
1273
+ parent_key: Key that stores the parent reference
1274
+ id_key: Key that stores the item's identifier
1275
+
1276
+ Returns:
1277
+ Hierarchically sorted list
1278
+ """
1279
+ if not sort_field or not data:
1280
+ return data
1281
+
1282
+ # Check if data has depth info (already structured hierarchically)
1283
+ if depth_key in data[0]:
1284
+ # Data is already structured with depth - need to sort within groups
1285
+ return _sort_with_depth(
1286
+ data, sort_field, ascending, depth_key, parent_key, id_key
1287
+ )
1288
+
1289
+ # Simple flat sort
1290
+ return sort_data(data, sort_field, ascending)
1291
+
1292
+
1293
+ def _sort_with_depth(
1294
+ data: List[Dict[str, Any]],
1295
+ sort_field: str,
1296
+ ascending: bool,
1297
+ depth_key: str,
1298
+ parent_key: str,
1299
+ id_key: str,
1300
+ ) -> List[Dict[str, Any]]:
1301
+ """Sort data that already has depth information.
1302
+
1303
+ Args:
1304
+ data: List of dicts with depth info
1305
+ sort_field: Field to sort by
1306
+ ascending: Sort direction
1307
+ depth_key: Key for depth level
1308
+ parent_key: Key for parent reference
1309
+ id_key: Key for item identifier
1310
+
1311
+ Returns:
1312
+ Sorted list preserving hierarchy
1313
+ """
1314
+ # Build a map of parent -> children
1315
+ from collections import defaultdict
1316
+
1317
+ parent_children: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
1318
+ roots: List[Dict[str, Any]] = []
1319
+
1320
+ for item in data:
1321
+ # Use _parent_id if available (for user associations), else parent_key
1322
+ parent = item.get("_parent_id") or item.get(parent_key, "")
1323
+ depth = item.get(depth_key, 0)
1324
+ if depth == 0 or not parent:
1325
+ roots.append(item)
1326
+ else:
1327
+ parent_children[parent].append(item)
1328
+
1329
+ def sort_key(item: Dict[str, Any]) -> Any:
1330
+ # Account associations (with _is_account=True or empty user) come first
1331
+ is_account = item.get("_is_account", not item.get("user"))
1332
+ value = item.get(sort_field)
1333
+ if value is None or value == "-" or value == "":
1334
+ # Empty values: accounts first (0), then sorted to end (1)
1335
+ return (0 if is_account else 1, 1, "")
1336
+ try:
1337
+ return (0 if is_account else 1, 0, float(value))
1338
+ except (ValueError, TypeError):
1339
+ return (0 if is_account else 1, 0, str(value).lower())
1340
+
1341
+ def add_sorted_subtree(
1342
+ items: List[Dict[str, Any]]
1343
+ ) -> List[Dict[str, Any]]:
1344
+ result = []
1345
+ sorted_items = sorted(
1346
+ items, key=sort_key, reverse=not ascending
1347
+ )
1348
+ for item in sorted_items:
1349
+ result.append(item)
1350
+ # Only account items can have children (not user items)
1351
+ is_account = item.get("_is_account", not item.get("user"))
1352
+ if is_account:
1353
+ item_id = item.get(id_key, "")
1354
+ if item_id in parent_children:
1355
+ result.extend(
1356
+ add_sorted_subtree(parent_children[item_id])
1357
+ )
1358
+ return result
1359
+
1360
+ return add_sorted_subtree(roots)