|
| 1 | +// Copyright © 2020 Banzai Cloud |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package kubectlversion |
| 16 | + |
| 17 | +import ( |
| 18 | + "encoding/json" |
| 19 | + "os/exec" |
| 20 | + |
| 21 | + "emperror.dev/errors" |
| 22 | + "github.com/Masterminds/semver" |
| 23 | +) |
| 24 | + |
| 25 | +type clientVersion struct { |
| 26 | + GitVersion string `json:"gitVersion,omitempty"` |
| 27 | +} |
| 28 | + |
| 29 | +type kubectlVersionOutput struct { |
| 30 | + ClientVersion clientVersion `json:"clientVersion,omitempty"` |
| 31 | +} |
| 32 | + |
| 33 | +func getLocalKubectlVersion() (clientVersion, error) { |
| 34 | + c := exec.Command("kubectl", "version", "--client=true", "-o", "json") |
| 35 | + out, err := c.Output() |
| 36 | + if err != nil { |
| 37 | + return clientVersion{}, errors.WrapIf(err, "failed to determine kubectl version") |
| 38 | + } |
| 39 | + |
| 40 | + var parsed kubectlVersionOutput |
| 41 | + if err := json.Unmarshal(out, &parsed); err != nil { |
| 42 | + return clientVersion{}, errors.WrapIf(err, "failed to parse kubectl version") |
| 43 | + } |
| 44 | + |
| 45 | + return parsed.ClientVersion, nil |
| 46 | +} |
| 47 | + |
| 48 | +func LessThan(v string) (bool, error) { |
| 49 | + inputVersion, err := semver.NewVersion(v) |
| 50 | + if err != nil { |
| 51 | + return false, errors.WrapIf(err, "failed to parse kubectl input version") |
| 52 | + } |
| 53 | + |
| 54 | + localKubectlVersion, err := getLocalKubectlVersion() |
| 55 | + if err != nil { |
| 56 | + return false, errors.WrapIf(err, "failed to get local kubectl version") |
| 57 | + } |
| 58 | + |
| 59 | + localVersion, err := semver.NewVersion(localKubectlVersion.GitVersion) |
| 60 | + if err != nil { |
| 61 | + return false, errors.WrapIf(err, "failed to parse kubectl local semantic version") |
| 62 | + } |
| 63 | + |
| 64 | + return localVersion.LessThan(inputVersion), nil |
| 65 | +} |
0 commit comments