Skip to content

Commit

Permalink
Add key action for + to do kubectl apply -f
Browse files Browse the repository at this point in the history
Signed-off-by: Xiaodong Ye <[email protected]>
  • Loading branch information
yeahdongcn committed Nov 13, 2023
1 parent 337ad9e commit 48f4dc1
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions internal/ui/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ func initKeys() {
tcell.KeyNames[KeyHelp] = "?"
tcell.KeyNames[KeySlash] = "/"
tcell.KeyNames[KeySpace] = "space"
tcell.KeyNames[KeyPlus] = "+"

initNumbKeys()
initStdKeys()
Expand Down Expand Up @@ -77,6 +78,7 @@ const (
KeySlash = 47
KeyColon = 58
KeySpace = 32
KeyPlus = 43
)

// Define Shift Keys.
Expand Down
51 changes: 51 additions & 0 deletions internal/view/browser.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package view

import (
"bytes"
"context"
"errors"
"fmt"
"os"
"sort"
"strconv"
"strings"
Expand All @@ -20,6 +23,7 @@ import (
"github.com/derailed/tcell/v2"
"github.com/rs/zerolog/log"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubectl/pkg/cmd/util/editor"
)

// Browser represents a generic resource browser.
Expand Down Expand Up @@ -359,6 +363,52 @@ func (b *Browser) describeCmd(evt *tcell.EventKey) *tcell.EventKey {
return nil
}

func (b *Browser) applyCmd(evt *tcell.EventKey) *tcell.EventKey {
b.Stop()
defer b.Start()
{
a := b.app
a.Halt()
defer a.Resume()

var data []byte
var path string
var err error

if !a.Suspend(func() {
edit := editor.NewDefaultEditor([]string{})
buf := &bytes.Buffer{}
data, path, err = edit.LaunchTempFile("kubectl-apply-", ".yaml", buf)
}) {
time.AfterFunc(200*time.Millisecond, func() {
a.Flash().Err(errors.New("failed to suspend the application"))
})
return nil
}

defer os.Remove(path)
if err != nil {
time.AfterFunc(200*time.Millisecond, func() {
a.Flash().Err(fmt.Errorf("failed to edit a temporary file: %w", err))
})
} else if len(data) > 0 {
args := make([]string, 0, 10)
args = append(args, "apply", "-f", path)
if err := runK(a, shellOpts{clear: true, args: args}); err != nil {
time.AfterFunc(200*time.Millisecond, func() {
a.Flash().Err(fmt.Errorf("failed to apply resource: %w", err))
})
} else {
time.AfterFunc(200*time.Millisecond, func() {
a.Flash().Infof("Resource applied successfully!")
})
}
}
}

return evt
}

func (b *Browser) editCmd(evt *tcell.EventKey) *tcell.EventKey {
path := b.GetSelectedItem()
if path == "" {
Expand Down Expand Up @@ -481,6 +531,7 @@ func (b *Browser) refreshActions() {
if client.Can(b.meta.Verbs, "delete") {
aa[tcell.KeyCtrlD] = ui.NewKeyAction("Delete", b.deleteCmd, true)
}
aa[ui.KeyPlus] = ui.NewKeyAction("Apply", b.applyCmd, true)
}
}

Expand Down

0 comments on commit 48f4dc1

Please sign in to comment.