godeps: vendor dependency to docker/docker/pkg/stringid.

Signed-off-by: Andrea Luzzardi <aluzzardi@gmail.com>
This commit is contained in:
Andrea Luzzardi 2015-05-07 00:02:17 -07:00
parent 054702fedc
commit c4c07c97ac
4 changed files with 80 additions and 1 deletions

7
Godeps/Godeps.json generated
View File

@ -1,6 +1,6 @@
{
"ImportPath": "github.com/docker/swarm",
"GoVersion": "go1.3.1",
"GoVersion": "go1.3.3",
"Packages": [
"./..."
],
@ -40,6 +40,11 @@
"Comment": "v1.4.1-3245-g443437f",
"Rev": "443437f5ea04da9d62bf3e05d7951f7d30e77d96"
},
{
"ImportPath": "github.com/docker/docker/pkg/stringid",
"Comment": "v1.4.1-3245-g443437f",
"Rev": "443437f5ea04da9d62bf3e05d7951f7d30e77d96"
},
{
"ImportPath": "github.com/docker/docker/pkg/units",
"Comment": "v1.4.1-3245-g443437f",

View File

@ -0,0 +1 @@
This package provides helper functions for dealing with string identifiers

View File

@ -0,0 +1,38 @@
package stringid
import (
"crypto/rand"
"encoding/hex"
"io"
"strconv"
)
// TruncateID returns a shorthand version of a string identifier for convenience.
// A collision with other shorthands is very unlikely, but possible.
// In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
// will need to use a langer prefix, or the full-length Id.
func TruncateID(id string) string {
shortLen := 12
if len(id) < shortLen {
shortLen = len(id)
}
return id[:shortLen]
}
// GenerateRandomID returns an unique id
func GenerateRandomID() string {
for {
id := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, id); err != nil {
panic(err) // This shouldn't happen
}
value := hex.EncodeToString(id)
// if we try to parse the truncated for as an int and we don't have
// an error then the value is all numberic and causes issues when
// used as a hostname. ref #3869
if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil {
continue
}
return value
}
}

View File

@ -0,0 +1,35 @@
package stringid
import "testing"
func TestGenerateRandomID(t *testing.T) {
id := GenerateRandomID()
if len(id) != 64 {
t.Fatalf("Id returned is incorrect: %s", id)
}
}
func TestShortenId(t *testing.T) {
id := GenerateRandomID()
truncID := TruncateID(id)
if len(truncID) != 12 {
t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID)
}
}
func TestShortenIdEmpty(t *testing.T) {
id := ""
truncID := TruncateID(id)
if len(truncID) > len(id) {
t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID)
}
}
func TestShortenIdInvalid(t *testing.T) {
id := "1234"
truncID := TruncateID(id)
if len(truncID) != len(id) {
t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID)
}
}