-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkubed.el
3522 lines (3241 loc) · 157 KB
/
kubed.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; kubed.el --- Kubernetes, Emacs, done! -*- lexical-binding: t; -*-
;; Copyright (C) 2024-2025 Free Software Foundation, Inc.
;; Author: Eshel Yaron <[email protected]>
;; Maintainer: Eshel Yaron <~eshel/[email protected]>
;; Keywords: tools kubernetes containers
;; URL: https://eshelyaron.com/kubed.html
;; Package-Version: 0.4.2
;; Package-Requires: ((emacs "29.1"))
;;; Commentary:
;; This library defines commands for interacting with Kubernetes
;; resources, such as Kubernetes pods, services, deployments, and more.
;;
;; Use `kubed-display-pod' to display a Kubernetes pod,
;; `kubed-edit-pod' to edit it, `kubed-delete-pods' to delete it, and
;; `kubed-list-pods' to see a menu of all pods. You can create new pods
;; from YAML or JSON files with `kubed-create-pod'.
;;
;; Similar commands are defined for other types of resources as well.
;;
;; This library interacts with Kubernetes via `kubectl', and uses the
;; current `kubectl' context and namespace by default. To change your
;; current context or namespace, use commands `kubed-use-context' and
;; `kubed-set-namespace' respectively; you can also interact with
;; resources in other namespaces without changing your default
;; namespace, for example you can call `kubed-list-pods' with a prefix
;; argument to choose another namespace for listing pods. The prefix
;; keymap `kubed-prefix-map' gives you quick access to these and other
;; useful commands, you may want to bind it globally to a convenient key
;; with `keymap-global-set':
;;
;; (keymap-global-set "C-c k" 'kubed-prefix-map)
;;
;; In addition, the command `kubed-transient' lets you explore various
;; Kubernetes operations with a transient menu interface. You may also
;; want to enable `kubed-menu-bar-mode', which add a "Kubernetes" menu
;; to your menu-bar with many useful entries.
;;
;; If you want to work with more or different types of Kubernetes
;; resources, use the macro `kubed-define-resource'. This macro defines
;; some common functions and commands that'll get you started with ease.
;;
;; For more information, see the Kubed manual at (info "(kubed)Top"), or
;; online at https://eshelyaron.com/kubed.html
;;; Code:
(require 'kubed-common)
(defgroup kubed nil
"Kubernetes interface."
:group 'tools)
(defcustom kubed-default-context-and-namespace nil
"Default `kubectl' context and Kubernetes namespace.
This is either a cons cell (CONTEXT . NAMESPACE), or nil. If nil, Kubed
initializes this option to a non-nil value next time Kubed consults it."
:type '(choice (const :tag "Initialize from `kubectl' on first use" nil)
(cons :tag "Context and namespace"
(string :tag "Context")
(string :tag "Namespace"))))
(defcustom kubed-yaml-setup-hook '(yaml-ts-mode view-mode)
"List of functions to call in Kubernetes resource description YAML buffers.
The first function in the list should normally be the major mode to use,
by default it is `yaml-ts-mode'."
:type 'hook)
(defcustom kubed-logs-setup-hook '(view-mode)
"List of functions to call when setting up Kubernetes pod logs buffers."
:type 'hook)
(defcustom kubed-name-column '("Name" 48 t)
"Specification of resource name column in Kubernetes resource list buffers."
:type '(list string natnum boolean))
(defvar kubed--data nil)
(defun kubed--alist (type context namespace)
"Return information about resources in CONTEXT of type TYPE in NAMESPACE."
(alist-get namespace
(alist-get type
(alist-get context
kubed--data nil nil #'string=)
nil nil #'string=)
nil nil #'equal))
(gv-define-setter kubed--alist (value type context namespace)
`(setf (alist-get ,namespace
(alist-get ,type
(alist-get ,context
kubed--data nil nil #'string=)
nil nil #'string=)
nil nil #'equal)
,value))
(defvar kubed--columns nil)
(defun kubed-update (type context &optional namespace)
"Update list of resources of type TYPE in CONTEXT and NAMESPACE."
(when (process-live-p (alist-get 'process (kubed--alist type context namespace)))
(user-error "Update in progress"))
(let* ((out (get-buffer-create (format " *kubed-get-%s*" type)))
(err (get-buffer-create (format " *kubed-get-%s-stderr*" type)))
(columns (alist-get type kubed--columns nil nil #'string=)))
(with-current-buffer out (erase-buffer))
(setf (alist-get 'process (kubed--alist type context namespace))
(make-process
:name (format "*kubed-get-%s*" type)
:buffer out
:stderr err
:command (append
(list kubed-kubectl-program "get" type
"--context" context
(format "--output=custom-columns=%s"
(mapconcat #'car columns ",")))
(when namespace (list "--namespace" namespace)))
:sentinel
(lambda (_proc status)
(cond
((string= status "finished\n")
(let (new offsets eol)
(with-current-buffer out
(goto-char (point-min))
(setq eol (pos-eol))
(while (re-search-forward "[^ ]+" eol t)
(push (1- (match-beginning 0)) offsets))
(setq offsets (nreverse offsets))
(forward-char 1)
(while (not (eobp))
(let ((cols nil)
(beg (car offsets))
(ends (append (cdr offsets)
(list (- (pos-eol) (point))))))
(dolist (column columns)
(let ((str (string-trim (buffer-substring
(+ (point) beg)
(+ (point) (car ends))))))
(push (if-let ((f (cdr column))) (funcall f str) str)
cols)
(setq beg (pop ends))))
(push (nreverse cols) new))
(forward-line 1)))
(setf (kubed--alist type context namespace)
(list (cons 'resources
(mapcar (lambda (c) (list (car c) (apply #'vector c)))
new))))
(let ((bufs nil))
(dolist (buf (buffer-list))
(and (equal (buffer-local-value 'kubed-list-type buf) type)
(equal (buffer-local-value 'kubed-list-context buf) context)
(equal (buffer-local-value 'kubed-list-namespace buf) namespace)
(with-current-buffer buf
(when (derived-mode-p 'kubed-list-mode)
(revert-buffer)
(when-let ((win (get-buffer-window)))
(set-window-point win (point))
(push buf bufs))))))
(walk-windows
(lambda (win)
(let ((buf (window-buffer win)))
(when (memq buf bufs)
(set-window-point
win (with-current-buffer buf (point))))))))
(message (format "Updated Kubernetes %S." type))))
((string= status "exited abnormally with code 1\n")
(with-current-buffer err
(goto-char (point-max))
(insert "\n" status))
(display-buffer err))))))))
(defvar-local kubed-display-resource-info nil
"Information about Kubernetes resource that current buffer displays.
The value is a list (TYPE NAME CONTEXT NAMESPACE), where TYPE is the
type of the resource, NAME is the name of the resource, CONTEXT is the
`kubectl' context to use for accessing the resource, and NAMESPACE is
the namespace of the resource, or nil if TYPE is not namespaced.")
(put 'kubed-display-resource-info 'permanent-local t)
(defun kubed-display-resource-revert (&optional _ _)
"Clear and populate current Kubernetes resource buffer."
(seq-let (type name context namespace)
kubed-display-resource-info
(let ((inhibit-read-only t)
(target (current-buffer)))
(buffer-disable-undo)
(with-temp-buffer
(unless (zerop
(apply
#'call-process
kubed-kubectl-program nil t nil "get"
type "--output=yaml" name
(append (when namespace (list "-n" namespace))
(when context (list "--context" context)))))
(error "Failed to display Kubernetes resource `%s'" name))
(let ((source (current-buffer)))
(with-current-buffer target
(replace-buffer-contents source)
(set-buffer-modified-p nil)
(buffer-enable-undo)))))))
(defun kubed-display-resource-in-buffer
(buffer type resource &optional context namespace)
"Display Kubernetes RESOURCE of type TYPE in BUFFER."
(let ((info (list type resource context namespace)))
(with-current-buffer (get-buffer-create buffer)
(setq-local kubed-display-resource-info info)
(kubed-display-resource-revert)
(goto-char (point-min))
(run-hooks 'kubed-yaml-setup-hook)
(kubed-display-resource-mode)
(current-buffer))))
(defun kubed-display-resource-short-description
(type resource context namespace)
"Return short string to use as a label for RESOURCE of type TYPE."
(concat type "/" resource
(when namespace (concat "@" namespace))
(when context (concat "[" context "]"))))
(defun kubed-namespaced-p (type &optional context)
"Return non-nil if TYPE is a namespaced resource type in context CONTEXT."
(member type (kubed-api-resources context t)))
(defun kubed--namespace (context &optional prompt-p)
"Return Kubernetes namespace for CONTEXT.
Non-nil optional argument PROMPT-P says to prompt for a namespace."
(let ((ns (if (equal context (kubed-local-context))
(kubed-local-namespace)
(kubed-current-namespace context))))
;; If CONTEXT is another context that has no configured namespace,
;; then NS is nil and we must prompt.
(unless ns (setq prompt-p t))
(if prompt-p
(kubed-read-namespace "Namespace" ns nil context)
ns)))
;;;###autoload
(defun kubed-display-resource
(type resource context &optional namespace)
"Display Kubernetes RESOURCE of type TYPE in CONTEXT.
For namespaced resource types, NAMESPACE is the namespace of RESOURCE.
Interactively, use the current context and namespace by default, and
prompt for TYPE and RESOURCE. With a prefix argument \
\\[universal-argument],
prompt for NAMESPACE. With a double prefix argument \
\\[universal-argument] \\[universal-argument],
prompt for CONTEXT as well."
(interactive
(let ((type nil) (context nil) (namespace nil))
(dolist (arg (kubed-transient-args 'kubed-transient-display))
(cond
((string-match "--namespace=\\(.+\\)" arg)
(setq namespace (match-string 1 arg)))
((string-match "--context=\\(.+\\)" arg)
(setq context (match-string 1 arg)))))
(unless context
(setq context
(let ((cxt (kubed-local-context)))
(if (equal current-prefix-arg '(16))
(kubed-read-context "Context" cxt)
cxt))))
(unless type
(setq type (kubed-read-resource-type "Type of resource to display"
nil context)))
(when (and (null namespace) (kubed-namespaced-p type context))
(setq namespace (kubed--namespace context current-prefix-arg)))
(list type (kubed-read-resource-name type "Display" nil nil
context namespace)
context namespace)))
(display-buffer
(kubed-display-resource-in-buffer
(concat "*Kubed "
(kubed-display-resource-short-description
type resource context namespace)
"*")
type resource context namespace)))
(declare-function bookmark-prop-get "bookmark")
(declare-function bookmark-get-front-context-string "bookmark")
(declare-function bookmark-get-rear-context-string "bookmark")
(declare-function bookmark-make-record-default "bookmark")
;;;###autoload
(defun kubed-display-resource-handle-bookmark (bookmark)
"Display Kubernetes resource according to BOOKMARK."
(require 'bookmark)
(seq-let (type name context namespace)
(bookmark-prop-get bookmark 'resource)
(set-buffer
(kubed-display-resource-in-buffer
(concat "*Kubed "
(kubed-display-resource-short-description
type name context namespace)
"*")
type name context namespace))
(when-let ((str (bookmark-get-front-context-string bookmark))
((search-forward str (point-max) t)))
(goto-char (match-beginning 0)))
(when-let ((str (bookmark-get-rear-context-string bookmark))
((search-backward str (point-min) t)))
(goto-char (match-end 0)))))
(put 'kubed-display-resource-handle-bookmark 'bookmark-handler-type "KubedResource")
(defun kubed-display-resource-make-bookmark ()
"Return bookmark pointing to currently displayed Kubernetes resource."
(require 'bookmark)
(seq-let (type name context namespace) kubed-display-resource-info
(cons
(kubed-display-resource-short-description type name context namespace)
(append
(list
(cons 'handler #'kubed-display-resource-handle-bookmark)
(cons 'resource kubed-display-resource-info))
(bookmark-make-record-default t)))))
(defun kubed-display-resource-jump-to-list ()
"Jump to line in resources list that corresponds to the displayed resource."
(interactive)
(seq-let (type name context namespace) kubed-display-resource-info
(apply (intern (concat "kubed-list-" type)) context
(when namespace (list namespace)))
(kubed-list-go-to-line name)))
(defun kubed-display-resource-diff ()
"Show diff of current buffer with current state of the displayed resource."
(interactive)
(kubed-diff (current-buffer) nil (nth 2 kubed-display-resource-info)))
(defun kubed-display-resource-replace ()
"Replace displayed Kubernetes resource with current buffer contents."
(interactive)
(let (choice)
(while (= ?d (setq choice
(car (read-multiple-choice
"Replace resource with changes in current buffer?"
'((?y "yes") (?n "no") (?d "diff"))))))
(kubed-display-resource-diff))
(when (= ?y choice)
(let ((err-buf (get-buffer-create " *kubed-replace*")))
(with-current-buffer err-buf (erase-buffer))
(unless (zerop (call-process-region nil nil kubed-kubectl-program
nil err-buf nil "replace" "-f" "-"))
(display-buffer err-buf)
(user-error "`kubectl replace' failed!")))
(message "Replaced Kubernetes resource with changes in current buffer.")
(revert-buffer))))
(defun kubed-display-resource-p (_symbol buffer)
"Return non-nil if `kubed-display-resource-mode' is enabled in BUFFER.
The first argument, SYMBOL, is ignored. You can use this function as
the `completion-predicate' property of commands that you define that
should only be available in buffers that display Kubernetes resources."
(buffer-local-value 'kubed-display-resource-mode buffer))
(dolist (cmd '(kubed-display-resource-jump-to-list
kubed-display-resource-diff
kubed-display-resource-replace))
(put cmd 'completion-predicate #'kubed-display-resource-p))
(defvar-keymap kubed-display-resource-mode-map
:doc "Keymap buffers that display Kubernetes resource."
"C-c C-j" #'kubed-display-resource-jump-to-list
"C-c C-=" #'kubed-display-resource-diff
"C-c C-c" #'kubed-display-resource-replace)
(define-minor-mode kubed-display-resource-mode
"Minor mode for buffers that display a Kubernetes resource."
:interactive nil
:lighter " Kubed"
(when kubed-display-resource-mode
(setq-local
revert-buffer-function #'kubed-display-resource-revert
bookmark-make-record-function #'kubed-display-resource-make-bookmark)))
(defun kubed-list-filter-lt-operator (v s)
"Return non-nil if S is less than V as a number or as a string."
(let ((l (string-to-number s)) (r (string-to-number v)))
(if (= l r) (string< s v) (< l r))))
(defun kubed-list-filter-gt-operator (v s)
"Return non-nil if S is greater than V as a number or as a string."
(let ((l (string-to-number s)) (r (string-to-number v)))
(if (= l r) (string> s v) (> l r))))
(defcustom kubed-list-filter-operator-alist
'((= . string=)
(~ . string-match-p)
(< . kubed-list-filter-lt-operator)
(> . kubed-list-filter-gt-operator))
"Association list of filter operators and functions that implement them.
Elements of the list are cons cells (OP . FN), where OP is a symbol that
is used as a filter operator and FN is a function that implements OP.
FN takes two arguments, a string STR and a parameter VAL. FN should
return non-nil if STR and VAL are related according to OP: to determine
if a line in which column COL is STR satisfies the filter (OP COL VAL),
Kubed checks if the form (FN VAL STR) evaluates to non-nil."
:type '(alist :key-type (symbol :tag "Operator") :value-type function))
(defun kubed-list-interpret-atomic-filter (atom)
"Return function that implements atomic filter ATOM."
(if (eq (car-safe atom) 'quote)
(let ((p (kubed-list-interpret-atomic-filter (cadr atom))))
(lambda (x) (not (funcall p x))))
(let* ((column-number (tabulated-list--column-number (symbol-name (nth 1 atom))))
(value (nth 2 atom))
(value (if (stringp value) value (prin1-to-string value)))
(op (alist-get (car atom) kubed-list-filter-operator-alist)))
(unless op (user-error "Unknown filter operator `%S'" (car atom)))
(lambda (x) (funcall op value (aref (cadr x) column-number))))))
(defvar-local kubed-list-filter nil "Filter in effect in the current buffer.")
(defun kubed-list-interpret-filter (&optional filter)
"Return function that implements FILTER.
If FILTER is omitted or nil, it defaults to `kubed-list-filter'."
(let ((conjunction (or filter kubed-list-filter)))
(if (listp (car conjunction))
(let ((conjuncts
(mapcar (lambda (disjunction)
(if (listp (car disjunction))
(let ((disjuncts
(mapcar #'kubed-list-interpret-atomic-filter
disjunction)))
(lambda (entry)
(catch 'keep-it
(dolist (pred disjuncts)
(when (funcall pred entry)
(throw 'keep-it t)))
nil)))
;; Single atomic disjunct.
(kubed-list-interpret-atomic-filter disjunction)))
(or conjunction kubed-list-filter))))
(lambda (entry)
(catch 'keep-it
(dolist (pred conjuncts)
(unless (funcall pred entry)
(throw 'keep-it nil)))
t)))
;; Single atomic conjunct.
(kubed-list-interpret-atomic-filter conjunction))))
(defun kubed-list-validate-atomic-filter (atom)
"Return string explaining why ATOM is invalid, or nil if it is valid."
(unless (consp atom)
(throw 'validation-error
(format (substitute-quotes
"Invalid atomic filter `%S', must be a list")
atom)))
(if (eq (car-safe atom) 'quote)
(kubed-list-validate-atomic-filter (cadr atom))
(unless (length= atom 3)
(throw 'validation-error
(format (substitute-quotes
"Invalid atomic filter `%S', must have three elements")
atom)))
(unless (assq (car atom) kubed-list-filter-operator-alist)
(throw 'validation-error
(format (substitute-quotes
"No operator `%S' in `kubed-list-filter-operator-alist'")
(car atom))))
(unless (ignore-errors
(tabulated-list--column-number (symbol-name (nth 1 atom))))
(throw 'validation-error (format (substitute-quotes
"Invalid column name `%S'")
(nth 1 atom))))))
(defun kubed-list-validate-filter (filter)
"Return string explaining why FILTER is invalid, or nil if it is valid."
(catch 'validation-error
(if (listp (car-safe filter))
(dolist (disjunction filter)
(if (and (consp disjunction) (listp (car disjunction)))
(dolist (disjunct disjunction)
(kubed-list-validate-atomic-filter disjunct))
(kubed-list-validate-atomic-filter disjunction)))
(kubed-list-validate-atomic-filter filter))))
(defvar-local kubed-list-filter-history-variable nil
"History list variable to use for filter history in the current buffer.")
(defvar-local kubed--list-read-filter-target-buffer nil
"Resource list buffer for which this minibuffer is reading a filter.")
(defvar-local kubed-list-type nil)
(defvar-local kubed-list-context nil)
(defvar-local kubed-list-namespace nil)
(defvar-local kubed-list-transient-extra-suffixes nil
"List of transient suffixes for the type of resources in current buffer.")
(defun kubed-list-go-to-line (id)
"Go to beginning of table line with ID."
(let ((pos nil))
(save-excursion
;; Wait for refresh to finish, if currently underway.
(while (process-live-p
(alist-get 'process (kubed--alist kubed-list-type
kubed-list-context
kubed-list-namespace)))
(accept-process-output
(alist-get 'process (kubed--alist kubed-list-type
kubed-list-context
kubed-list-namespace))
1))
(goto-char (point-min))
(while (not (or pos (eobp)))
(if (equal id (tabulated-list-get-id))
(setq pos (point))
(forward-line))))
(goto-char pos)))
(defun kubed-list-try-read-filter ()
"Try to read a resource list filter in the minibuffer.
Exit the minibuffer if successful, else report the error and move point
to the location of the error. If point is not already at the location
of the error, push a mark before moving point."
(interactive "" minibuffer-mode)
(let* ((prompt-end (minibuffer-prompt-end))
(contents (minibuffer-contents))
(error-point nil) (error-message nil) (form nil) (inval nil))
(with-temp-buffer
(condition-case err
(progn
;; FIXME: There is a small edge case here that could get
;; better treatment: when `contents' ends with " ?", it
;; espaces the terminating closing parenthesis and leads us
;; to incorrectly report the input as incomplete.
(insert "(" contents ")")
(goto-char (point-min))
(setq form (read (current-buffer))))
(error (setq error-point (+ prompt-end (1- (point)))
error-message err))))
(cond
(error-point
(unless (= (point) error-point) (push-mark))
(goto-char error-point)
(minibuffer-message (error-message-string error-message)))
((setq inval (with-current-buffer kubed--list-read-filter-target-buffer
(kubed-list-validate-filter form)))
(minibuffer-message inval))
(t (exit-minibuffer)))))
(defvar-keymap kubed-list-read-filter-map
:parent minibuffer-local-map
"TAB" #'completion-at-point
"M-?" #'completion-help-at-point
"<remap> <exit-minibuffer>" #'kubed-list-try-read-filter)
(defun kubed-list-read-filter (prompt)
"Prompt with PROMPT for a filter for the current buffer."
(let* ((buf (current-buffer))
(cols (seq-map #'car tabulated-list-format))
(vals (let ((tmp nil))
(dolist (ent (alist-get 'resources
(kubed--alist kubed-list-type
kubed-list-context
kubed-list-namespace)))
(let ((i 0))
(dolist (col cols)
(push (aref (cadr ent) i)
(alist-get col tmp nil nil #'string=))
(setq i (1+ i)))))
(mapcar #'delete-dups tmp)))
(filter
(minibuffer-with-setup-hook
(lambda ()
(set-syntax-table emacs-lisp-mode-syntax-table)
(setq-local kubed--list-read-filter-target-buffer buf)
(add-hook
'completion-at-point-functions
(lambda ()
(let ((cont (buffer-substring
(minibuffer-prompt-end) (point)))
(bounds (or (bounds-of-thing-at-point 'symbol)
(cons (point) (point)))))
(with-temp-buffer
(set-syntax-table emacs-lisp-mode-syntax-table)
(insert "(" cont)
(when-let ((fn-argi (elisp--fnsym-in-current-sexp))
(argi (cadr fn-argi)))
(if (= argi 0)
;; Complete operators.
(list
(car bounds) (cdr bounds)
(mapcar #'car kubed-list-filter-operator-alist))
(when (car fn-argi)
(cond
((= argi 1)
;; Complete column names.
(list (car bounds) (cdr bounds) cols))
((= argi 2)
;; Complete column values.
(when-let ((beg (nth 1 (syntax-ppss)))
;; Grab preceding symbol.
(col (save-excursion
(goto-char beg)
(forward-char 1)
(forward-sexp 2)
(thing-at-point 'symbol))))
(list (car bounds) (cdr bounds)
(alist-get col vals
nil nil #'string=)))))))))))
nil t))
(read-from-minibuffer
(format-prompt prompt "disable")
(mapconcat #'prin1-to-string kubed-list-filter " ")
kubed-list-read-filter-map nil
kubed-list-filter-history-variable ""))))
(car (ignore-errors (read-from-string (format "(%s)" filter))))))
(defun kubed-list-set-filter (filter)
"Set the filter of the current buffer to FILTER.
FILTER determines which resources to keep. FILTER can be an atomic
filter, which is a list (OP COL VAL), where OP is an operator defined in
`kubed-list-filter-operator-alist' (which see), COL is a symbol whose
name is a column name, and VAL is a string or an object whose printed
representation is compared to the value of the column COL according to
OP. For example, the atomic filter (= Name foobar) keeps only resources
whose name is \"foobar\". (= Name \"foobar\") does exactly the same.
To negate an atomic filter, quote it. E.g. use \\='(~ Namespace kube)
to hide all resources in namespaces whose name contains \"kube\".
FILTER can also be a list of sub-filters (SUB1 SUB2 ...) where each
sub-filter is either an atomic filter or a list of atomic filters. If a
sub-filter is a list of atomic filters, then that sub-filter denotes the
disjunction of those atomic filters. FILTER denotes the conjunction of
the sub-filters. In particular, FILTER nil denotes the empty
conjunction which is always true (keeps all resources).
More examples:
- `((= Name foobar) (~ Namespace kube))': keep only resources named
\"foobar\" in namespaces that contain \"kube\".
- `(((= Name foobar) (~ Namespace kube)))': keep resources that are
either named \"foobar\" or in a namespace that contains \"kube\".
- `(((= Name foobar) (~ Namespace kube)) \\='(~ Starttime 2024-07))':
keep only resources that are either named \"foobar\" or in a namespace
that contains \"kube\", and were not started during July 2024.
Interactively, prompt for FILTER sans the outermost set of parenthesis.
For example, enter \"= Name foobar\" in the minibuffer to specify the
atomic FILTER (= Name foobar).
See also Info node \"(kubed) List Filter\"."
(interactive (list (kubed-list-read-filter "Set filter")) kubed-list-mode)
(when-let ((validation-error (kubed-list-validate-filter filter)))
(user-error validation-error))
(setq-local kubed-list-filter filter)
(revert-buffer))
(defun kubed-list-mark-for-deletion ()
"Mark Kubernetes resource at point for deletion."
(interactive "" kubed-list-mode)
(tabulated-list-put-tag (propertize "D" 'help-echo "Marked for deletion") t))
(defun kubed-list-unmark ()
"Remove mark from Kubernetes resource at point."
(interactive "" kubed-list-mode)
(tabulated-list-put-tag " " t))
(defun kubed-list-previous-column (&optional n)
"Move backward N columns.
Interactively, N is the numeric value of the prefix argument, defaulting
to 1."
(interactive "p" kubed-list-mode)
(kubed-list-next-column (- n)))
(defun kubed-list-next-column (&optional n)
"Move forward N columns.
Interactively, N is the numeric value of the prefix argument, defaulting
to 1."
(interactive "p" kubed-list-mode)
(let ((next (point))
(times (abs (or n 1)))
(dir-fn (if (< 0 n)
#'next-single-property-change
#'previous-single-property-change)))
(dotimes (_ times)
(setq next (funcall dir-fn next 'tabulated-list-column-name))
(when (= (char-after next) ?\n)
;; At line boundary, go to first/last column of next line.
(setq next (funcall dir-fn next 'tabulated-list-column-name)))
(unless next (user-error "End of table")))
(goto-char next)))
(defun kubed-list-copy-as-kill (click)
"Copy name of Kubernetes resource at CLICK into the kill ring."
(interactive (list last-nonmenu-event) kubed-list-mode)
(if-let ((ent (tabulated-list-get-entry (mouse-set-point click)))
(new (aref ent 0)))
(progn
(kill-new new)
(message "Copied resource name `%s'" new))
(user-error "No Kubernetes resource at point")))
(defun kubed-list-context-menu (menu click)
"Extend MENU with common actions on Kubernetes resource at CLICK."
(when (tabulated-list-get-entry (posn-point (event-start click)))
(define-key menu [kubed-list-select-resource]
'(menu-item "Select" kubed-list-select-resource))
(define-key menu [kubed-list-display-resource]
'(menu-item "Display" kubed-list-display-resource))
(define-key menu [kubed-list-delete]
'(menu-item "Delete" kubed-list-delete))
(define-key menu [kubed-list-patch]
'(menu-item "Patch" kubed-list-patch))
(define-key menu [kubed-list-edit]
'(menu-item "Edit" kubed-list-edit))
(define-key menu [kubed-list-kubectl-command]
'(menu-item "Execute `kubectl' command" kubed-list-kubectl-command))
(define-key menu [kubed-list-copy-as-kill]
'(menu-item "Copy name" kubed-list-copy-as-kill)))
menu)
(defun kubed-list-update (&optional quiet)
"Update list of Kubernetes resources.
If optional argument QUIET is non-nil, do not emit a message when
starting to update. Display a message when the update is done
regardless of QUIET."
(interactive "" kubed-list-mode)
(kubed-update kubed-list-type kubed-list-context kubed-list-namespace)
(force-mode-line-update)
(unless quiet (minibuffer-message (format "Updating Kubernetes %S..." kubed-list-type))))
(defun kubed-list-delete-marked ()
"Delete marked Kubernetes resources."
(interactive "" kubed-list-mode)
(let (delete-list)
(save-excursion
(goto-char (point-min))
(while (not (eobp))
(when (eq (char-after) ?D)
(push (tabulated-list-get-id) delete-list))
(forward-line)))
(if delete-list
(when (y-or-n-p (format "Delete %d marked Kubernetes resources?"
(length delete-list)))
(save-excursion
(goto-char (point-min))
(while (not (eobp))
(when (member (tabulated-list-get-id) delete-list)
(tabulated-list-put-tag
(propertize "K" 'help-echo "Deletion in progress")))
(forward-line)))
(let ((errb (generate-new-buffer " *kubed-list-delete-marked-stderr*"))
(buf (current-buffer)))
(make-process
:name "*kubed-list-delete-marked*"
:stderr errb
:command (cons kubed-kubectl-program
(append
(when kubed-list-context
(list "--context" kubed-list-context))
(when kubed-list-namespace
(list "--namespace" kubed-list-namespace))
(list "delete" kubed-list-type)
delete-list))
:sentinel (lambda (_proc status)
(cond
((string= status "finished\n")
(message (format "Deleted %d marked Kubernetes resources."
(length delete-list)))
(when (buffer-live-p buf)
(with-current-buffer buf
(kubed-list-update t))))
((string= status "exited abnormally with code 1\n")
(with-current-buffer errb
(goto-char (point-max))
(insert "\n" status))
(display-buffer errb)))))))
(user-error "No Kubernetes resources marked for deletion"))))
(defun kubed-list-display-resource (click)
"Display Kubernetes resource at CLICK in another window."
(interactive (list last-nonmenu-event) kubed-list-mode)
(if-let ((resource (tabulated-list-get-id (mouse-set-point click))))
(kubed-display-resource
kubed-list-type resource kubed-list-context kubed-list-namespace)
(user-error "No Kubernetes resource at point")))
(defun kubed-list-select-resource (click)
"Display Kubernetes resource at CLICK in current window."
(interactive (list last-nonmenu-event) kubed-list-mode)
(if-let ((resource (tabulated-list-get-id (mouse-set-point click))))
(switch-to-buffer
(kubed-display-resource-in-buffer
(concat "*Kubed "
(kubed-display-resource-short-description
kubed-list-type resource kubed-list-context kubed-list-namespace)
"*")
kubed-list-type resource kubed-list-context kubed-list-namespace))
(user-error "No Kubernetes resource at point")))
(defun kubed-list-select-resource-other-window (click)
"Display Kubernetes resource at CLICK in other window and select that window."
(interactive (list last-nonmenu-event) kubed-list-mode)
(if-let ((resource (tabulated-list-get-id (mouse-set-point click))))
(switch-to-buffer-other-window
(kubed-display-resource-in-buffer
(concat "*Kubed "
(kubed-display-resource-short-description
kubed-list-type resource kubed-list-context kubed-list-namespace)
"*")
kubed-list-type resource kubed-list-context kubed-list-namespace))
(user-error "No Kubernetes resource at point")))
(defun kubed-list-delete (click)
"Delete Kubernetes resource at CLICK."
(interactive (list last-nonmenu-event) kubed-list-mode)
(if-let ((resource (tabulated-list-get-id (mouse-set-point click))))
(when (y-or-n-p (format "Delete `%s'?" resource))
(kubed-delete-resources kubed-list-type (list resource)
kubed-list-context kubed-list-namespace))
(user-error "No Kubernetes resource at point")))
(defun kubed-list-patch (click)
"Patch Kubernetes resource at CLICK."
(interactive (list last-nonmenu-event) kubed-list-mode)
(if-let ((resource (tabulated-list-get-id (mouse-set-point click))))
(kubed-patch kubed-list-type resource
(kubed-read-patch) kubed-list-context kubed-list-namespace)
(user-error "No Kubernetes resource at point")))
(defun kubed-list-edit (click)
"Edit Kubernetes resource at CLICK."
(interactive (list last-nonmenu-event) kubed-list-mode)
(if-let ((resource (tabulated-list-get-id (mouse-set-point click))))
(kubed-edit-resource kubed-list-type resource
kubed-list-context kubed-list-namespace)
(user-error "No Kubernetes resource at point")))
(defun kubed-list-kubectl-command (click)
"Use Kubernetes resource at CLICK as argument for `kubectl' command."
(interactive (list last-nonmenu-event) kubed-list-mode)
(if-let ((resource (tabulated-list-get-id (mouse-set-point click))))
(kubed-kubectl-command
(kubed-read-kubectl-command
"Execute command: "
(cons (concat
" "
(when kubed-list-namespace (concat "-n " kubed-list-namespace " "))
(when kubed-list-context (concat "--context " kubed-list-context " "))
kubed-list-type " " resource)
;; Put point after "kubectl ".
0)))
(user-error "No Kubernetes resource at point")))
(defun kubed-list-logs (click)
"Show logs for Kubernetes resource at CLICK."
(interactive (list last-nonmenu-event) kubed-list-mode)
(if-let ((resource (tabulated-list-get-id (mouse-set-point click))))
(kubed-logs kubed-list-type resource kubed-list-context kubed-list-namespace
t t nil t)
(user-error "No Kubernetes resource at point")))
(defun kubed-list-create (definition &optional kind)
"Create Kubernetes resource of kind KIND from definition file DEFINITION."
(interactive (list (kubed-read-resource-definition-file-name)) kubed-list-mode)
(kubed-create definition kind kubed-list-context)
(kubed-list-update t))
(defun kubed-list-column-number-at-point ()
"Return table column number at point."
(let ((start (current-column))
(nb-cols (1- (length tabulated-list-format)))
(col-nb 0)
(total-width tabulated-list-padding)
(found nil))
(while (and (not found) (< col-nb nb-cols))
(if (>= start
(setq total-width
(+ total-width
(cadr (aref tabulated-list-format col-nb))
(or (plist-get (nthcdr 3 (aref tabulated-list-format
col-nb))
:pad-right)
1))))
(setq col-nb (1+ col-nb))
(setq found t)))
col-nb))
(defun kubed-list-fit-column-width-to-content (n)
"Fit width of Nth table column to its content.
If N is negative, fit all columns. Interactively, N is the column
number at point, or the numeric prefix argument if you provide one."
(interactive
(list (if current-prefix-arg
(prefix-numeric-value current-prefix-arg)
(kubed-list-column-number-at-point)))
kubed-list-mode)
(if (< n 0)
;; Fit all columns.
(let* ((num-cols (length tabulated-list-format))
(widths (apply #'vector (seq-map
;; +2 to make room for sorting icon.
(lambda (col) (+ 2 (length (car col))))
tabulated-list-format))))
(save-excursion
(goto-char (point-min))
(while-let ((entry (tabulated-list-get-entry)))
(dotimes (i num-cols)
(aset widths i (max (aref widths i) (length (aref entry i)))))
(forward-line)))
(setq tabulated-list-format (copy-tree tabulated-list-format t))
(dotimes (i num-cols)
(setf (cadr (aref tabulated-list-format i))
(1+ (aref widths i)))))
;; Fit Nth column.
(let* ((width (+ 2 (length (car (aref tabulated-list-format n))))))
(save-excursion
(goto-char (point-min))
(while-let ((entry (tabulated-list-get-entry)))
(setq width (max width (length (aref entry n))))
(forward-line)))
(setq tabulated-list-format (copy-tree tabulated-list-format t))
(setf (cadr (aref tabulated-list-format n)) (1+ width))))
(tabulated-list-print t)
(tabulated-list-init-header))
(declare-function kubed-list-transient "kubed-transient" ())
(declare-function kubed-transient-logs-for-pod "kubed-transient" (val))
(declare-function kubed-transient-logs-for-deployment "kubed-transient" (val))
(declare-function kubed-transient-logs-for-statefulset "kubed-transient" (val))
(declare-function kubed-transient-logs-for-replicaset "kubed-transient" (val))
(declare-function kubed-transient-logs-for-job "kubed-transient" (val))
(declare-function kubed-transient-logs-for-service "kubed-transient" (val))
(defvar-keymap kubed-list-mode-map
:doc "Common keymap for Kubernetes resource list buffers."
"RET" #'kubed-list-select-resource
"o" #'kubed-list-select-resource-other-window
"C-o" #'kubed-list-display-resource
"D" #'kubed-list-delete
"P" #'kubed-list-patch
"x" #'kubed-list-delete-marked
"e" #'kubed-list-edit
"!" #'kubed-list-kubectl-command
"g" #'kubed-list-update
"/" #'kubed-list-set-filter
"|" #'kubed-list-fit-column-width-to-content
"d" #'kubed-list-mark-for-deletion
"u" #'kubed-list-unmark
"w" #'kubed-list-copy-as-kill
"C-i" #'kubed-list-next-column
"TAB" #'kubed-list-next-column
"C-S-i" #'kubed-list-previous-column
"S-TAB" #'kubed-list-previous-column
"<backtab>" #'kubed-list-previous-column
"+" #'kubed-list-create
"?" #'kubed-list-transient)
(defun kubed-list-entries ()
"`tabulated-list-entries' function for `kubed-list-mode'."
(let ((pred (kubed-list-interpret-filter))
(ents nil))
(dolist (ent (alist-get 'resources (kubed--alist kubed-list-type
kubed-list-context
kubed-list-namespace)))
(when (funcall pred ent) (push ent ents)))
(reverse ents)))
;;;###autoload
(defun kubed-list-handle-bookmark (bookmark)
"Display Kubernetes resource according to BOOKMARK."
(require 'bookmark)
(let* ((type (bookmark-prop-get bookmark 'type))
(context (bookmark-prop-get bookmark 'context))
(namespace (bookmark-prop-get bookmark 'namespace))
(current (bookmark-prop-get bookmark 'current))
(buff-fn (intern (format "kubed-%s-buffer" type)))
(buff (apply buff-fn context (when namespace (list namespace)))))
(set-buffer buff)
(when current (kubed-list-go-to-line current))))
(put 'kubed-list-handle-bookmark 'bookmark-handler-type "KubedList")
(defun kubed-list-make-bookmark ()
"Return bookmark pointing to currently displayed Kubernetes resource."
(require 'bookmark)