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,854 @@
1
+ """Utilities for managing Slurm jobs."""
2
+
3
+ import json
4
+ import subprocess
5
+ from datetime import datetime
6
+ from typing import Any, Dict, List, Optional, Union
7
+
8
+ from rich.box import SIMPLE_HEAVY
9
+ from rich.table import Table
10
+
11
+ from .base_resource import BaseSlurmResource
12
+ from .profiles import (
13
+ format_with_template,
14
+ get_profile_config,
15
+ sort_data,
16
+ )
17
+ from .utils import console
18
+
19
+
20
+ def _format_timestamp(epoch: int, default: str = "-") -> str:
21
+ """Format Unix timestamp as YYYY-MM-DDTHH:MM:SS."""
22
+ if not epoch or epoch <= 0:
23
+ return default
24
+ try:
25
+ dt = datetime.fromtimestamp(epoch)
26
+ return dt.strftime("%Y-%m-%dT%H:%M:%S")
27
+ except (ValueError, OSError):
28
+ return default
29
+
30
+
31
+ def _format_duration(minutes: int) -> str:
32
+ """Format duration in minutes as DDD-HH:MM:SS (leading zeros ignored)."""
33
+ if not minutes or minutes <= 0:
34
+ return ""
35
+ hours, mins = divmod(minutes, 60)
36
+ days, hours = divmod(hours, 24)
37
+ if days:
38
+ return f"{days}-{hours:02d}:{mins:02d}:00"
39
+ elif hours:
40
+ return f"{hours}:{mins:02d}:00"
41
+ else:
42
+ return f"{mins}:00"
43
+
44
+
45
+ class Job(BaseSlurmResource):
46
+ """Slurm job resource handler."""
47
+
48
+ # Job states for filtering (in Slurm order)
49
+ JOB_STATES = [
50
+ "pending",
51
+ "running",
52
+ "cancelled",
53
+ "completing",
54
+ "completed",
55
+ "boot_fail",
56
+ "configuring",
57
+ "deadline",
58
+ "failed",
59
+ "node_fail",
60
+ "out_of_memory",
61
+ "preempted",
62
+ "resv_del_hold",
63
+ "requeue_fed",
64
+ "requeue_hold",
65
+ "requeued",
66
+ "resizing",
67
+ "revoked",
68
+ "signaling",
69
+ "special_exit",
70
+ "stage_out",
71
+ "stopped",
72
+ "suspended",
73
+ "timeout",
74
+ ]
75
+
76
+ # Default columns for table output
77
+ DEFAULT_COLUMNS = [
78
+ "job_id",
79
+ "user_name",
80
+ "partition",
81
+ "job_state",
82
+ "start_time",
83
+ "endlimit",
84
+ "node_count",
85
+ "gres",
86
+ "reason",
87
+ ]
88
+
89
+ # All available columns
90
+ ALL_COLUMNS = [
91
+ "job_id",
92
+ "name",
93
+ "user_name",
94
+ "account",
95
+ "partition",
96
+ "job_state",
97
+ "time_limit",
98
+ "endlimit",
99
+ "node_count",
100
+ "nodes",
101
+ "cpus",
102
+ "gres",
103
+ "submit_time",
104
+ "start_time",
105
+ "end_time",
106
+ "priority",
107
+ "reason",
108
+ "command",
109
+ "working_directory",
110
+ "standard_output",
111
+ "standard_error",
112
+ ]
113
+
114
+ # Default styles for table columns
115
+ DEFAULT_STYLES = {
116
+ "job_id": "cyan bold",
117
+ "name": "white",
118
+ "user_name": "blue",
119
+ "account": "magenta",
120
+ "partition": "green",
121
+ "job_state": "yellow",
122
+ "time_limit": "dim",
123
+ "endlimit": "dim",
124
+ "node_count": "cyan",
125
+ "nodes": "dim",
126
+ "cpus": "yellow",
127
+ "gres": "magenta",
128
+ "submit_time": "dim",
129
+ "start_time": "green",
130
+ "end_time": "red",
131
+ "priority": "magenta",
132
+ "reason": "white",
133
+ "command": "dim",
134
+ "working_directory": "dim",
135
+ "standard_output": "dim",
136
+ "standard_error": "dim",
137
+ }
138
+
139
+ # Filter options
140
+ JOB_FILTER_OPTIONS = [
141
+ "job_id",
142
+ "user",
143
+ "account",
144
+ "partition",
145
+ "state",
146
+ "name",
147
+ "nodes",
148
+ "reservation",
149
+ ]
150
+
151
+ # Update options by type (from scontrol update job)
152
+ JOB_UPDATE_OPTIONS = {
153
+ # Yes/No options
154
+ "yesno": [
155
+ "contiguous",
156
+ "oversubscribe",
157
+ "reboot",
158
+ "shared",
159
+ ],
160
+ # 0/1 options
161
+ "binary": [
162
+ "requeue",
163
+ ],
164
+ # Count/number options
165
+ "count": [
166
+ "arraytaskthrottle",
167
+ "corespec",
168
+ "cpuspertask",
169
+ "mincpusnode",
170
+ "minmemorycpu",
171
+ "minmemorynode",
172
+ "mintmpdisknode",
173
+ "nice",
174
+ "numcpus",
175
+ "numnodes",
176
+ "numtasks",
177
+ "priority",
178
+ "reqcores",
179
+ "reqnodes",
180
+ "reqprocs",
181
+ "reqsockets",
182
+ "reqthreads",
183
+ "sitefactor",
184
+ "switches",
185
+ "taskspernode",
186
+ "threadspec",
187
+ ],
188
+ # Time spec options
189
+ "time": [
190
+ "deadline",
191
+ "delayboot",
192
+ "eligibletime",
193
+ "endtime",
194
+ "starttime",
195
+ "timelimit",
196
+ "timemin",
197
+ ],
198
+ # Node list options
199
+ "nodes": [
200
+ "excnodelist",
201
+ "nodelist",
202
+ "reqnodelist",
203
+ ],
204
+ # Partition (special - use cache)
205
+ "partition": [
206
+ "partition",
207
+ ],
208
+ # QOS (special - use cache)
209
+ "qos": [
210
+ "qos",
211
+ ],
212
+ # Account (special - use cache)
213
+ "account": [
214
+ "account",
215
+ ],
216
+ # Reservation (special - use cache)
217
+ "reservation": [
218
+ "reservationname",
219
+ ],
220
+ # User (special - use cache)
221
+ "user": [
222
+ "mailuser",
223
+ "userid",
224
+ ],
225
+ # String/text options
226
+ "string": [
227
+ "admincomment",
228
+ "burstbuffer",
229
+ "clusters",
230
+ "clusterfeatures",
231
+ "comment",
232
+ "dependency",
233
+ "extra",
234
+ "features",
235
+ "gres",
236
+ "jobname",
237
+ "licenses",
238
+ "mailtype",
239
+ "name",
240
+ "prefer",
241
+ "stderr",
242
+ "stdin",
243
+ "stdout",
244
+ "wckey",
245
+ "workdir",
246
+ ],
247
+ # No-value options (flags)
248
+ "flag": [
249
+ "resetaccruetime",
250
+ ],
251
+ }
252
+
253
+ # Mail types for MailType option
254
+ MAIL_TYPES = [
255
+ "NONE",
256
+ "BEGIN",
257
+ "END",
258
+ "FAIL",
259
+ "REQUEUE",
260
+ "ALL",
261
+ "INVALID_DEPEND",
262
+ "STAGE_OUT",
263
+ "TIME_LIMIT",
264
+ "TIME_LIMIT_90",
265
+ "TIME_LIMIT_80",
266
+ "TIME_LIMIT_50",
267
+ "ARRAY_TASKS",
268
+ ]
269
+
270
+ # Dependency types for Dependency option
271
+ DEPENDENCY_TYPES = [
272
+ "after:",
273
+ "afterany:",
274
+ "afternotok:",
275
+ "afterok:",
276
+ "singleton",
277
+ ]
278
+
279
+ def __init__(self, job_id: Union[str, None] = None, **kwargs: Any):
280
+ self.job_id = job_id
281
+ self.kwargs = kwargs
282
+
283
+ @classmethod
284
+ def get_profile_fields(cls) -> dict:
285
+ """Return field names and descriptions for profile templates."""
286
+ return {
287
+ "job_id": "Job ID",
288
+ "name": "Job name",
289
+ "user_name": "Username",
290
+ "account": "Account name",
291
+ "partition": "Partition",
292
+ "job_state": "Job state",
293
+ "time_limit": "Time limit",
294
+ "endlimit": "End time if known, otherwise time limit",
295
+ "node_count": "Number of nodes",
296
+ "nodes": "Node list",
297
+ "cpus": "Number of CPUs",
298
+ "gres": "Generic resources (GPUs, etc.)",
299
+ "submit_time": "Submit time",
300
+ "start_time": "Start time",
301
+ "end_time": "End time",
302
+ "priority": "Priority",
303
+ "reason": "Reason/Comment",
304
+ "command": "Command",
305
+ "working_directory": "Working directory",
306
+ "standard_output": "Standard output file",
307
+ "standard_error": "Standard error file",
308
+ }
309
+
310
+ @classmethod
311
+ def _fetch_jobs(
312
+ cls, force_update: bool = False
313
+ ) -> List[Dict[str, Any]]:
314
+ """Fetch jobs from scontrol (with caching for autocomplete)."""
315
+ from .resources import Resource
316
+
317
+ try:
318
+ # Use cached_resource to enable autocomplete caching
319
+ data = Resource.cached_resource("jobs", force_update)
320
+ if data:
321
+ return data.get("jobs", [])
322
+ return []
323
+ except Exception as e:
324
+ console.print(f"[red]Failed to fetch jobs: {e}[/red]")
325
+ return []
326
+
327
+ @classmethod
328
+ def _normalize_job(cls, job: Dict[str, Any]) -> Dict[str, Any]:
329
+ """Normalize job data for display."""
330
+
331
+ # Handle nested structures
332
+ def get_value(obj, key, default=None):
333
+ val = obj.get(key, default)
334
+ if isinstance(val, dict):
335
+ if "number" in val:
336
+ return val.get("number", default)
337
+ if "set" in val and not val.get("set", False):
338
+ return default
339
+ return str(val)
340
+ if isinstance(val, list):
341
+ return ",".join(str(v) for v in val)
342
+ return val if val else default
343
+
344
+ # Get time limit from nested structure
345
+ time_limit = job.get("time_limit", {})
346
+ if isinstance(time_limit, dict):
347
+ time_limit_val = time_limit.get("number", 0)
348
+ if time_limit.get("infinite"):
349
+ time_limit_str = "UNLIMITED"
350
+ else:
351
+ time_limit_str = _format_duration(time_limit_val)
352
+ else:
353
+ time_limit_str = (
354
+ _format_duration(time_limit) if time_limit else ""
355
+ )
356
+
357
+ # Get node count
358
+ node_count = get_value(job, "node_count", 0)
359
+ if isinstance(node_count, dict):
360
+ node_count = node_count.get("number", 0)
361
+
362
+ # Get CPUs
363
+ cpus = get_value(job, "cpus", 0)
364
+ if isinstance(cpus, dict):
365
+ cpus = cpus.get("number", 0)
366
+
367
+ # Get job state - can be list or string
368
+ job_state = job.get("job_state", "")
369
+ if isinstance(job_state, list):
370
+ job_state = ",".join(job_state)
371
+
372
+ # Compute end_time and endlimit
373
+ end_time_data = job.get("end_time", {})
374
+ if isinstance(end_time_data, dict):
375
+ end_time_set = end_time_data.get("set", False)
376
+ end_time_num = end_time_data.get("number", 0)
377
+ if end_time_set and end_time_num:
378
+ end_time_str = _format_timestamp(end_time_num)
379
+ else:
380
+ end_time_str = "-"
381
+ else:
382
+ end_time_str = _format_timestamp(end_time_data)
383
+ end_time_set = bool(end_time_data) and end_time_str != "-"
384
+
385
+ # endlimit: end_time (as timestamp) if known, otherwise time_limit
386
+ if end_time_str and end_time_str != "-":
387
+ endlimit_str = end_time_str
388
+ else:
389
+ endlimit_str = time_limit_str if time_limit_str else "-"
390
+
391
+ return {
392
+ "job_id": str(get_value(job, "job_id", "")),
393
+ "name": get_value(job, "name", ""),
394
+ "user_name": get_value(job, "user_name", ""),
395
+ "account": get_value(job, "account", ""),
396
+ "partition": get_value(job, "partition", ""),
397
+ "job_state": job_state,
398
+ "time_limit": time_limit_str,
399
+ "node_count": str(node_count),
400
+ "nodes": get_value(job, "nodes", ""),
401
+ "cpus": str(cpus),
402
+ "gres": get_value(job, "tres_per_node", ""),
403
+ "submit_time": _format_timestamp(
404
+ job.get("submit_time", {}).get("number", 0)
405
+ if isinstance(job.get("submit_time"), dict)
406
+ else job.get("submit_time", 0)
407
+ ),
408
+ "start_time": _format_timestamp(
409
+ job.get("start_time", {}).get("number", 0)
410
+ if isinstance(job.get("start_time"), dict)
411
+ else job.get("start_time", 0)
412
+ ),
413
+ "end_time": end_time_str,
414
+ "endlimit": endlimit_str,
415
+ "priority": str(job.get("priority", {}).get("number", ""))
416
+ if isinstance(job.get("priority"), dict)
417
+ else str(job.get("priority", "")),
418
+ "reason": get_value(job, "state_reason", ""),
419
+ "command": get_value(job, "command", ""),
420
+ "working_directory": get_value(
421
+ job, "current_working_directory", ""
422
+ ),
423
+ "standard_output": get_value(job, "standard_output", ""),
424
+ "standard_error": get_value(job, "standard_error", ""),
425
+ }
426
+
427
+ @classmethod
428
+ def _apply_filters(
429
+ cls,
430
+ jobs: List[Dict[str, Any]],
431
+ filters: Dict[str, str],
432
+ ) -> List[Dict[str, Any]]:
433
+ """Apply filters to job list."""
434
+ result = jobs
435
+
436
+ for key, value in filters.items():
437
+ key_lower = key.lower()
438
+ value_lower = value.lower()
439
+
440
+ if key_lower == "job_id":
441
+ result = [
442
+ j
443
+ for j in result
444
+ if str(j.get("job_id", "")) == value
445
+ ]
446
+ elif key_lower == "user":
447
+ result = [
448
+ j
449
+ for j in result
450
+ if value_lower in j.get("user_name", "").lower()
451
+ ]
452
+ elif key_lower == "account":
453
+ result = [
454
+ j
455
+ for j in result
456
+ if value_lower in j.get("account", "").lower()
457
+ ]
458
+ elif key_lower == "partition":
459
+ result = [
460
+ j
461
+ for j in result
462
+ if value_lower in j.get("partition", "").lower()
463
+ ]
464
+ elif key_lower == "state":
465
+ result = [
466
+ j
467
+ for j in result
468
+ if value_lower in j.get("job_state", "").lower()
469
+ ]
470
+ elif key_lower == "name":
471
+ result = [
472
+ j
473
+ for j in result
474
+ if value_lower in j.get("name", "").lower()
475
+ ]
476
+ elif key_lower == "nodes":
477
+ result = [
478
+ j
479
+ for j in result
480
+ if value_lower in j.get("nodes", "").lower()
481
+ ]
482
+ elif key_lower == "reservation":
483
+ result = [
484
+ j
485
+ for j in result
486
+ if value_lower in j.get("reservation", "").lower()
487
+ ]
488
+
489
+ return result
490
+
491
+ @classmethod
492
+ def show(
493
+ cls,
494
+ field: Union[str, None] = None,
495
+ style: str = "pretty",
496
+ force_cache_update: bool = False,
497
+ delimiter: str = ";",
498
+ zebra: bool = False,
499
+ profile: str = "default",
500
+ profile_str: Optional[str] = None,
501
+ ) -> None:
502
+ """Show job information.
503
+
504
+ Args:
505
+ field: Optional filter (e.g., user=john, state=running)
506
+ style: Output style ("pretty", "json", or "csv")
507
+ force_cache_update: Whether to force cache update
508
+ delimiter: Delimiter for CSV output (default: ";")
509
+ zebra: Use zebra striping for table rows
510
+ profile: Profile name to use for output formatting
511
+ profile_str: Inline profile string (overrides profile)
512
+ """
513
+ # Get profile configuration
514
+ (
515
+ columns,
516
+ styles,
517
+ template,
518
+ sort_field,
519
+ sort_asc,
520
+ ) = get_profile_config(profile, "jobs", profile_str)
521
+
522
+ # Use default columns if not specified, or all columns if "*"
523
+ if columns == "*":
524
+ columns = cls.ALL_COLUMNS
525
+ elif columns is None:
526
+ columns = cls.DEFAULT_COLUMNS
527
+
528
+ # Merge with default styles
529
+ merged_styles = dict(cls.DEFAULT_STYLES)
530
+ if styles:
531
+ merged_styles.update(styles)
532
+
533
+ # Parse filters from field argument
534
+ filters: Dict[str, str] = {}
535
+ if field:
536
+ parts = field.split()
537
+ for part in parts:
538
+ if "=" in part:
539
+ key, value = part.split("=", 1)
540
+ filters[key] = value
541
+ else:
542
+ # Treat as job_id filter
543
+ filters["job_id"] = part
544
+
545
+ try:
546
+ # Fetch jobs
547
+ raw_jobs = cls._fetch_jobs(force_cache_update)
548
+
549
+ if not raw_jobs:
550
+ console.print("[yellow]No jobs found.[/yellow]")
551
+ return
552
+
553
+ # Normalize jobs
554
+ jobs = [cls._normalize_job(j) for j in raw_jobs]
555
+
556
+ # Apply filters
557
+ if filters:
558
+ jobs = cls._apply_filters(jobs, filters)
559
+
560
+ if not jobs:
561
+ console.print(
562
+ "[yellow]No jobs matching filters found.[/yellow]"
563
+ )
564
+ return
565
+
566
+ # Apply sorting
567
+ if sort_field:
568
+ jobs = sort_data(jobs, sort_field, sort_asc)
569
+
570
+ # Output based on style
571
+ if style == "json":
572
+ console.print_json(json.dumps(jobs, indent=2))
573
+ elif style == "csv":
574
+ # CSV header
575
+ print(delimiter.join(columns))
576
+ for job in jobs:
577
+ row = [str(job.get(col, "")) for col in columns]
578
+ print(delimiter.join(row))
579
+ elif template:
580
+ # Template-based output
581
+ for job in jobs:
582
+ console.print(format_with_template(template, job))
583
+ else:
584
+ # Pretty table output
585
+ table = Table(
586
+ title="Slurm Jobs",
587
+ box=SIMPLE_HEAVY,
588
+ show_header=True,
589
+ header_style="bold",
590
+ )
591
+
592
+ # Add columns
593
+ for col in columns:
594
+ col_style = merged_styles.get(col, "white")
595
+ table.add_column(
596
+ col.replace("_", " ").title(), style=col_style
597
+ )
598
+
599
+ # Add rows
600
+ for i, job in enumerate(jobs):
601
+ row_style = None
602
+ if zebra and i % 2 == 1:
603
+ row_style = "on grey15"
604
+ row = [str(job.get(col, "")) for col in columns]
605
+ table.add_row(*row, style=row_style)
606
+
607
+ console.print(table)
608
+
609
+ except subprocess.CalledProcessError as e:
610
+ console.print(
611
+ f"[red]Failed to show jobs:[/red] {e.stderr or e}"
612
+ )
613
+
614
+ @classmethod
615
+ def create(cls, *args, **kwargs) -> None:
616
+ """Jobs are created via sbatch/srun, not scontrol."""
617
+ console.print(
618
+ "[yellow]Jobs are created using sbatch or srun commands, "
619
+ "not through this CLI.[/yellow]"
620
+ )
621
+
622
+ @classmethod
623
+ def update(
624
+ cls,
625
+ job_id: str,
626
+ verbose: bool = False,
627
+ dry_run: bool = False,
628
+ **kwargs: Any,
629
+ ) -> None:
630
+ """Update a job using scontrol."""
631
+ if not job_id:
632
+ console.print("[red]Job ID is required.[/red]")
633
+ return
634
+
635
+ options = " ".join(f"{k}={v}" for k, v in kwargs.items())
636
+ cmd = ["scontrol", "update", f"jobid={job_id}"]
637
+ if options:
638
+ cmd.append(options)
639
+
640
+ if dry_run:
641
+ console.print(f"[yellow]DRY RUN:[/yellow] {' '.join(cmd)}")
642
+ return
643
+
644
+ try:
645
+ result = subprocess.run(
646
+ cmd,
647
+ check=True,
648
+ capture_output=True,
649
+ text=True,
650
+ errors="replace",
651
+ )
652
+ if result.stdout:
653
+ console.print(result.stdout)
654
+ if verbose:
655
+ console.print(
656
+ f"[green]Job '{job_id}' updated successfully.[/green]"
657
+ )
658
+ except subprocess.CalledProcessError as e:
659
+ console.print(
660
+ f"[red]Failed to update job '{job_id}':[/red] {e.stderr or e}"
661
+ )
662
+
663
+ @classmethod
664
+ def delete(
665
+ cls, job_id: str, verbose: bool = False, **kwargs: Any
666
+ ) -> None:
667
+ """Cancel job(s) using scancel.
668
+
669
+ Args:
670
+ job_id: Job ID or filter expression (e.g., user=john)
671
+ verbose: Print verbose output
672
+ **kwargs: Additional filter options
673
+ """
674
+ # Check if job_id is a filter expression
675
+ if job_id and "=" in job_id:
676
+ # Parse as filter
677
+ key, value = job_id.split("=", 1)
678
+ kwargs[key] = value
679
+ job_id = value
680
+
681
+ # If we have filters, fetch and filter jobs first
682
+ if kwargs:
683
+ raw_jobs = cls._fetch_jobs()
684
+ if not raw_jobs:
685
+ console.print("[yellow]No jobs found.[/yellow]")
686
+ return
687
+
688
+ jobs = [cls._normalize_job(j) for j in raw_jobs]
689
+ jobs = cls._apply_filters(jobs, kwargs)
690
+
691
+ if not jobs:
692
+ console.print(
693
+ "[yellow]No jobs matching filters found.[/yellow]"
694
+ )
695
+ return
696
+
697
+ # Cancel all matching jobs in one call
698
+ job_ids = [j["job_id"] for j in jobs]
699
+ console.print(
700
+ f"[yellow]Cancelling {len(job_ids)} job(s)...[/yellow]"
701
+ )
702
+ cls._cancel_jobs(job_ids, verbose=verbose)
703
+ elif job_id:
704
+ # Cancel single job by ID
705
+ cls._cancel_jobs([job_id], verbose=verbose)
706
+ else:
707
+ console.print("[red]Job ID or filter is required.[/red]")
708
+
709
+ @classmethod
710
+ def _cancel_jobs(
711
+ cls, job_ids: List[str], verbose: bool = False
712
+ ) -> None:
713
+ """Cancel jobs by IDs (pass all to scancel in one call)."""
714
+ if not job_ids:
715
+ return
716
+ try:
717
+ result = subprocess.run(
718
+ ["scancel"] + job_ids,
719
+ check=True,
720
+ capture_output=True,
721
+ text=True,
722
+ errors="replace",
723
+ )
724
+ if result.stdout:
725
+ console.print(result.stdout)
726
+ if verbose:
727
+ console.print(
728
+ f"[green]{len(job_ids)} job(s) cancelled.[/green]"
729
+ )
730
+ except subprocess.CalledProcessError as e:
731
+ console.print(
732
+ f"[red]Failed to cancel jobs:[/red] {e.stderr or e}"
733
+ )
734
+
735
+ @classmethod
736
+ def _cancel_by_user(cls, user: str, verbose: bool = False) -> None:
737
+ """Cancel all jobs for a user (scancel -u USER)."""
738
+ try:
739
+ result = subprocess.run(
740
+ ["scancel", "-u", user],
741
+ check=True,
742
+ capture_output=True,
743
+ text=True,
744
+ errors="replace",
745
+ )
746
+ if result.stdout:
747
+ console.print(result.stdout)
748
+ if verbose:
749
+ console.print(
750
+ f"[green]All jobs for user '{user}' cancelled.[/green]"
751
+ )
752
+ except subprocess.CalledProcessError as e:
753
+ console.print(
754
+ f"[red]Failed to cancel jobs for user '{user}':[/red] "
755
+ f"{e.stderr or e}"
756
+ )
757
+
758
+ @classmethod
759
+ def generate_autocomplete_options(cls) -> str:
760
+ """Generate bash autocomplete script for job options."""
761
+ filter_opts = " ".join(
762
+ f"{opt}=" for opt in cls.JOB_FILTER_OPTIONS
763
+ )
764
+ states = " ".join(cls.JOB_STATES)
765
+
766
+ # Build update options list
767
+ update_opts = []
768
+ for opt_type, opts in cls.JOB_UPDATE_OPTIONS.items():
769
+ if opt_type == "flag":
770
+ update_opts.extend(opts) # No = suffix for flags
771
+ else:
772
+ update_opts.extend(f"{o}=" for o in opts)
773
+ update_opts_str = " ".join(update_opts)
774
+
775
+ mail_types = " ".join(cls.MAIL_TYPES)
776
+ dep_types = " ".join(cls.DEPENDENCY_TYPES)
777
+
778
+ script = f"""
779
+ _slurm_cli_jobs_autocomplete() {{
780
+ local cmd="$1"
781
+ local pos="$2"
782
+
783
+ local cur="${{COMP_WORDS[COMP_CWORD]}}"
784
+ local prev="${{COMP_WORDS[COMP_CWORD-1]}}"
785
+
786
+ local filter_options="{filter_opts}"
787
+ local update_options="{update_opts_str}"
788
+
789
+ # Check if 'set' keyword has been typed (for update command)
790
+ local found_set=0
791
+ for word in "${{COMP_WORDS[@]}}"; do
792
+ [[ "$word" == "set" ]] && found_set=1 && break
793
+ done
794
+
795
+ # Handle key=value completion
796
+ if _slurm_parse_keyval "$cur" "$prev"; then
797
+ case "$_key" in
798
+ # Filter options
799
+ job_id|jobid)
800
+ _slurm_complete_value "$(_slurm_cache_jobs)" "$_key" "$_val" "$cur" ;;
801
+ state)
802
+ _slurm_complete_value "{states}" "$_key" "$_val" "$cur" ;;
803
+ user|mailuser|userid)
804
+ _slurm_complete_value "$(_slurm_cache_users)" "$_key" "$_val" "$cur" ;;
805
+ account)
806
+ _slurm_complete_value "$(_slurm_cache_accounts)" "$_key" "$_val" "$cur" ;;
807
+ partition)
808
+ _slurm_complete_value "$(_slurm_cache_partitions)" "$_key" "$_val" "$cur" ;;
809
+ nodes|nodelist|excnodelist|reqnodelist)
810
+ _slurm_complete_nodes_value "$_val" "$cur" "$_key" ;;
811
+ reservation|reservationname)
812
+ _slurm_complete_value "$(_slurm_cache_reservations)" "$_key" "$_val" "$cur" ;;
813
+ qos)
814
+ _slurm_complete_value "$(_slurm_cache_qos)" "$_key" "$_val" "$cur" ;;
815
+ name|jobname)
816
+ # No completion for free-form text
817
+ return ;;
818
+ # Yes/No options
819
+ contiguous|oversubscribe|reboot|shared)
820
+ _slurm_complete_value "yes no" "$_key" "$_val" "$cur" ;;
821
+ # 0/1 options
822
+ requeue)
823
+ _slurm_complete_value "0 1" "$_key" "$_val" "$cur" ;;
824
+ # Mail type
825
+ mailtype)
826
+ _slurm_complete_value "{mail_types}" "$_key" "$_val" "$cur" ;;
827
+ # Dependency
828
+ dependency)
829
+ _slurm_complete_value "{dep_types}" "$_key" "$_val" "$cur" ;;
830
+ esac
831
+ [[ ${{#COMPREPLY[@]}} -gt 0 ]] && return
832
+ fi
833
+
834
+ local cached_jobs="$(_slurm_cache_jobs)"
835
+
836
+ # Default: show options and job IDs based on command
837
+ case "$cmd" in
838
+ show)
839
+ _slurm_complete "$filter_options" "$cur" ;;
840
+ delete|del|cancel)
841
+ _slurm_complete "$filter_options $cached_jobs" "$cur" ;;
842
+ update|modify|set)
843
+ # After 'set' keyword, only show update options
844
+ if [[ $found_set -eq 1 ]]; then
845
+ _slurm_complete "$update_options" "$cur"
846
+ else
847
+ # Before 'set': show job IDs, filter options, and 'set' keyword
848
+ _slurm_complete "$cached_jobs $filter_options set" "$cur"
849
+ fi
850
+ ;;
851
+ esac
852
+ }}
853
+ """ # noqa: E501
854
+ return script