Merge pull request #2422 from dotcloud/links_names_generator
Add name generator for container without -name
This commit is contained in:
commit
c0662488c7
2 changed files with 58 additions and 0 deletions
30
names-generator/names-generator.go
Normal file
30
names-generator/names-generator.go
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
package namesgenerator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type NameChecker interface {
|
||||||
|
Exists(name string) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
colors = [...]string{"white", "silver", "gray", "black", "blue", "green", "cyan", "yellow", "gold", "orange", "brown", "red", "violet", "pink", "magenta", "purple"}
|
||||||
|
animals = [...]string{"ant", "bird", "cat", "chicken", "cow", "dog", "fish", "fox", "horse", "lion", "monkey", "pig", "sheep", "tiger", "whale", "wolf"}
|
||||||
|
)
|
||||||
|
|
||||||
|
func GenerateRandomName(checker NameChecker) (string, error) {
|
||||||
|
retry := 5
|
||||||
|
rand.Seed(time.Now().UnixNano())
|
||||||
|
name := fmt.Sprintf("%s_%s", colors[rand.Intn(len(colors))], animals[rand.Intn(len(animals))])
|
||||||
|
for checker != nil && checker.Exists(name) && retry > 0 {
|
||||||
|
name = fmt.Sprintf("%s%d", name, rand.Intn(10))
|
||||||
|
retry = retry - 1
|
||||||
|
}
|
||||||
|
if retry == 0 {
|
||||||
|
return name, fmt.Errorf("Error generating random name")
|
||||||
|
}
|
||||||
|
return name, nil
|
||||||
|
}
|
28
names-generator/names-generator_test.go
Normal file
28
names-generator/names-generator_test.go
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
package namesgenerator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FalseChecker struct{}
|
||||||
|
|
||||||
|
func (n *FalseChecker) Exists(name string) bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
type TrueChecker struct{}
|
||||||
|
|
||||||
|
func (n *TrueChecker) Exists(name string) bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateRandomName(t *testing.T) {
|
||||||
|
if _, err := GenerateRandomName(&FalseChecker{}); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := GenerateRandomName(&TrueChecker{}); err == nil {
|
||||||
|
t.Error("An error was expected")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in a new issue