Skip to content

Commit 843fd88

Browse files
committed
cmd/xb: handle case where kubectl doesn't have a current-context
Change-Id: I8bad43c80458c4c85e8ca61a162e04b04312750f Reviewed-on: https://go-review.googlesource.com/128335 Reviewed-by: Dmitri Shuralyov <[email protected]>
1 parent e7a2a01 commit 843fd88

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed

cmd/xb/xb.go

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ func main() {
5454
switch cmd {
5555
case "kubectl":
5656
env := getEnv()
57-
curCtx := cmdStrOutput("kubectl", "config", "current-context")
57+
curCtx := kubeCurrentContext()
5858
wantCtx := fmt.Sprintf("gke_%s_%s_go", env.ProjectName, env.Zone)
5959
if curCtx != wantCtx {
6060
log.SetFlags(0)
@@ -73,6 +73,29 @@ func main() {
7373
}
7474
}
7575

76+
func kubeCurrentContext() string {
77+
kubectl, err := exec.LookPath("kubectl")
78+
if err != nil {
79+
log.SetFlags(0)
80+
log.Fatalf("No kubectl in path.")
81+
}
82+
// Get current context, but ignore errors, as kubectl returns an error
83+
// if there's no context.
84+
out, err := exec.Command(kubectl, "config", "current-context").Output()
85+
if err != nil {
86+
var stderr string
87+
if ee, ok := err.(*exec.ExitError); ok {
88+
stderr = string(ee.Stderr)
89+
}
90+
if strings.Contains(stderr, "current-context is not set") {
91+
return ""
92+
}
93+
log.Printf("Failed to run 'kubectl config current-context': %v, %s", err, stderr)
94+
return ""
95+
}
96+
return strings.TrimSpace(string(out))
97+
}
98+
7699
func getEnv() *buildenv.Environment {
77100
if *prod == *staging {
78101
log.Fatalf("must specify exactly one of --prod or --staging")
@@ -83,22 +106,6 @@ func getEnv() *buildenv.Environment {
83106
return buildenv.Staging
84107
}
85108

86-
func cmdStrOutput(cmd string, args ...string) string {
87-
out, err := exec.Command(cmd, args...).Output()
88-
if err != nil {
89-
var stderr []byte
90-
if ee, ok := err.(*exec.ExitError); ok {
91-
stderr = ee.Stderr
92-
}
93-
log.Fatalf("error running %s %v: %v, %s", cmd, args, err, stderr)
94-
}
95-
ret := strings.TrimSpace(string(out))
96-
if ret == "" {
97-
log.Fatalf("expected output from %s %v; got nothing", cmd, args)
98-
}
99-
return ret
100-
}
101-
102109
var expectedGoLayerVersion = map[string]string{
103110
"golang:1.10": "go version go1.10.2 linux/amd64",
104111
}

0 commit comments

Comments
 (0)