Skip to content
This repository has been archived by the owner on Mar 20, 2023. It is now read-only.

Commit

Permalink
improve context and namespace options insertion
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikulas committed Jan 4, 2019
1 parent 7954d90 commit 2aa34e1
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions main/kubectl.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ package main

import (
"bufio"
"bytes"
"fmt"
"github.com/fatih/color"
"io"
"os"
"os/exec"
"os/signal"
"regexp"
"syscall"
"bytes"
)

var (
cmdPattern *regexp.Regexp
)

func sh(shell string) error {
Expand Down Expand Up @@ -85,7 +90,31 @@ func shHandler(shell string, outputHandler func(string)) error {
}

func kubectl(cmd string) string {
buffer := bytes.NewBufferString("kubectl")
// Kubectl plugins are only invoked only if all arguments are specified
// after the command name itself.
// kubectl foo --namespace=foo # works
// kubectl --namespace=foo foo # fails
// https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/
//
// The `cmd` given can contain a very complex bash input. Instead of parsing it as a whole,
// we will find the first control character and place the arguments just before it.
//
// This fails on some edge case inputs, such as `foo bar=z`, but currently this syntax always
// takes an option such as `get pods -l foo=bar`, so the `-l` would be parsed first.

if cmdPattern == nil {
cmdPattern = regexp.MustCompile(`[^\w\s]`)
}

splitAt := cmdPattern.FindStringIndex(cmd)
if splitAt == nil {
splitAt = []int{len(cmd), len(cmd)}
}
cmdA := cmd[:splitAt[0]]
cmdB := cmd[splitAt[0]:]

buffer := bytes.NewBufferString("kubectl ")
buffer.WriteString(cmdA)
if context != "" {
buffer.WriteString(" --context=")
buffer.WriteString(context)
Expand All @@ -95,6 +124,6 @@ func kubectl(cmd string) string {
buffer.WriteString(namespace)
}
buffer.WriteString(" ")
buffer.WriteString(cmd)
buffer.WriteString(cmdB)
return buffer.String()
}

0 comments on commit 2aa34e1

Please sign in to comment.