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

Commit

Permalink
refactor command splitting, add proper test
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikulas committed Jan 5, 2019
1 parent e3be49f commit 1d8d7e9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
8 changes: 5 additions & 3 deletions main/kubectl.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"os/exec"
"os/signal"
"regexp"
"strings"
"syscall"
)

Expand Down Expand Up @@ -103,7 +104,9 @@ func kubectl(cmd string) string {
// takes an option such as `get pods -l foo=bar`, so the `-l` would be parsed first.

if cmdPattern == nil {
cmdPattern = regexp.MustCompile(`(\s-|--|[[^\w\s]&&[^.-]])`)
// dash is treated specially as it can appear inside unquoted identifiers,
// such as node names; we must not split those identifiers with options
cmdPattern = regexp.MustCompile(`\s-|[>{}$!?'"()&;|]`)
}

splitAt := cmdPattern.FindStringIndex(cmd)
Expand All @@ -123,7 +126,6 @@ func kubectl(cmd string) string {
buffer.WriteString(" --namespace=")
buffer.WriteString(namespace)
}
buffer.WriteString(" ")
buffer.WriteString(cmdB)
return buffer.String()
return strings.TrimSpace(buffer.String())
}
29 changes: 29 additions & 0 deletions main/kubectl_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package main

import (
"github.com/stretchr/testify/assert"
"strings"
"testing"
)

const SPLIT_MARK = "\x11"

func assertInsertion(t *testing.T, input string) {
cmd := strings.Replace(input, SPLIT_MARK, "", 1)
expected := "kubectl " + strings.Replace(input, SPLIT_MARK, " --context=c --namespace=ns", 1)

assert.Equal(t, expected, kubectl(cmd))
}

func TestKubectlInsertion(t *testing.T) {
context = "c"
namespace = "ns"

assertInsertion(t, "get pods\x11")
assertInsertion(t, "get pods\x11 -l foo=bar")
assertInsertion(t, "\x11; echo foo")
assertInsertion(t, "get pods\x11 -l foo | grep bar")
assertInsertion(t, "\x11 -l foo get pods")
assertInsertion(t, "get pods\x11|grep foo")
assertInsertion(t, "describe node ip-172-23-76-75.eu-central-1.compute.internal\x11")
}

0 comments on commit 1d8d7e9

Please sign in to comment.