truncate commit in version

This commit is contained in:
Benjamin Elder
2019-10-22 11:17:01 -07:00
parent cc9e3fbb6a
commit cb1e6727f4
3 changed files with 71 additions and 1 deletions

View File

@@ -35,7 +35,8 @@ func Version() string {
// if commit was set, add the + <build>
// we only do this for pre-release versions
if GitCommit != "" {
v += "+" + GitCommit
// NOTE: use 14 character short hash, like Kubernetes
v += "+" + truncate(GitCommit, 14)
}
}
return v
@@ -78,3 +79,10 @@ func NewCommand() *cobra.Command {
}
return cmd
}
func truncate(s string, maxLen int) string {
if len(s) < maxLen {
return s
}
return s[:maxLen]
}

View File

@@ -0,0 +1,61 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package version
import (
"testing"
)
func TestTruncate(t *testing.T) {
cases := []struct {
Value string
MaxLength int
Expected string
}{
{
Value: "A Really Long String",
MaxLength: 1,
Expected: "A",
},
{
Value: "A Short String",
MaxLength: 10,
Expected: "A Short St",
},
{
Value: "Under Max Length String",
MaxLength: 1000,
Expected: "Under Max Length String",
},
}
for _, tc := range cases {
tc := tc // capture range variable
t.Run(tc.Value, func(t *testing.T) {
t.Parallel()
result := truncate(tc.Value, tc.MaxLength)
// sanity check length
if len(result) > tc.MaxLength {
t.Errorf("Result %q longer than Max Length %d!", result, tc.MaxLength)
}
if tc.Expected != result {
t.Errorf("Strings did not match!")
t.Errorf("Expected: %q", tc.Expected)
t.Errorf("But got: %q", result)
}
})
}
}

1
go.sum
View File

@@ -17,6 +17,7 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90Pveol
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8 h1:1wopBVtVdWnn03fZelqdXTqk7U7zPQCb+T4rbU9ZEoU=
golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=