Skip to content

Commit

Permalink
feat: add functionality to install kubectl
Browse files Browse the repository at this point in the history
  • Loading branch information
ryantking committed Aug 3, 2019
1 parent 340219d commit 205b5f4
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
44 changes: 44 additions & 0 deletions internal/kubectl/install.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package kubectl

import (
"fmt"
"io"
"net/http"
"os"
"runtime"
)

const (
kubectlBase = "https://storage.googleapis.com"
pathBase = "/kubernetes-release/releases/%s/bin/%s/%s/kubectl"
kubectlPath = "./kubectl"
)

// Install installs the desired version of kubectl
func Install(version string) error {
path := fmt.Sprintf(pathBase, version, runtime.GOOS, runtime.GOARCH)
url := fmt.Sprintf("%s%s", kubectlBase, path)
res, err := http.Get(url)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("could not install kubectl, received code %d", res.StatusCode)
}
f, err := os.Create(kubectlPath)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, res.Body)
if err != nil {
return err
}
return os.Chmod(kubectlPath, os.ModePerm)
}

// Uninstall deletes the installed binary
func Uninstall() error {
return os.RemoveAll(kubectlPath)
}
66 changes: 66 additions & 0 deletions internal/kubectl/kubectl_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package kubectl

import (
"fmt"
"io/ioutil"
"net/http"
"os"
"runtime"
"testing"

"github.com/stretchr/testify/suite"
"gopkg.in/h2non/gock.v1"
)

const (
testVersion = "v1.13.2"
testBinary = "kubectl binary"
)

type KubectlTestSuite struct {
suite.Suite
}

func (suite *KubectlTestSuite) TearDownTest() {
require := suite.Require()

err := Uninstall()
require.NoError(err)
}

func (suite *KubectlTestSuite) TestInstall() {
assert := suite.Assert()
require := suite.Require()

path := fmt.Sprintf(pathBase, testVersion, runtime.GOOS, runtime.GOARCH)
gock.New(kubectlBase).
Get(path).
Reply(http.StatusOK).
BodyString(testBinary)

err := Install(testVersion)
require.NoError(err)
f, err := os.Open(kubectlPath)
require.NoError(err)
b, err := ioutil.ReadAll(f)
require.NoError(err)
assert.EqualValues(testBinary, b)
}

func (suite *KubectlTestSuite) TestInstallBadResponse() {
require := suite.Require()

path := fmt.Sprintf(pathBase, testVersion, runtime.GOOS, runtime.GOARCH)
gock.New(kubectlBase).
Get(path).
Reply(http.StatusInternalServerError).
BodyString(testBinary)

err := Install(testVersion)
require.EqualError(err, "could not install kubectl, received code 500")
}

func TestKubectlTestSuite(t *testing.T) {
tests := new(KubectlTestSuite)
suite.Run(t, tests)
}

0 comments on commit 205b5f4

Please sign in to comment.