blob: 7650fc14f1fabbfd6192ded336131af0d7b04f43 [file] [log] [blame]
Samuel A. Falvo II43d83532014-07-31 14:34:48 -07001package tools
2
3import (
4 "crypto/rand"
Ash Wilsonfd566482014-09-23 15:47:35 -04005 "errors"
Jamie Hannaford930df422014-11-24 14:39:08 +01006 mrand "math/rand"
Samuel A. Falvo II43d83532014-07-31 14:34:48 -07007 "time"
8)
9
Ash Wilsonfd566482014-09-23 15:47:35 -040010// ErrTimeout is returned if WaitFor takes longer than 300 second to happen.
11var ErrTimeout = errors.New("Timed out")
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070012
Ash Wilsonfd566482014-09-23 15:47:35 -040013// WaitFor polls a predicate function once per second to wait for a certain state to arrive.
14func WaitFor(predicate func() (bool, error)) error {
15 for i := 0; i < 300; i++ {
16 time.Sleep(1 * time.Second)
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070017
Ash Wilsonfd566482014-09-23 15:47:35 -040018 satisfied, err := predicate()
19 if err != nil {
20 return err
21 }
22 if satisfied {
23 return nil
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070024 }
25 }
Ash Wilsonfd566482014-09-23 15:47:35 -040026 return ErrTimeout
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070027}
28
Ash Wilsonfd566482014-09-23 15:47:35 -040029// MakeNewPassword generates a new string that's guaranteed to be different than the given one.
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070030func MakeNewPassword(oldPass string) string {
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070031 randomPassword := RandomString("", 16)
32 for randomPassword == oldPass {
33 randomPassword = RandomString("", 16)
34 }
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070035 return randomPassword
36}
37
Ash Wilsonfd566482014-09-23 15:47:35 -040038// RandomString generates a string of given length, but random content.
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070039// All content will be within the ASCII graphic character set.
40// (Implementation from Even Shaw's contribution on
41// http://stackoverflow.com/questions/12771930/what-is-the-fastest-way-to-generate-a-long-random-string-in-go).
42func RandomString(prefix string, n int) string {
43 const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
44 var bytes = make([]byte, n)
45 rand.Read(bytes)
46 for i, b := range bytes {
47 bytes[i] = alphanum[b%byte(len(alphanum))]
48 }
49 return prefix + string(bytes)
50}
Ash Wilson20b4e872014-10-22 17:39:21 -040051
Jamie Hannaford930df422014-11-24 14:39:08 +010052// RandomInt will return a random integer between a specified range.
53func RandomInt(min, max int) int {
54 mrand.Seed(time.Now().Unix())
55 return mrand.Intn(max-min) + min
56}
57
Ash Wilson20b4e872014-10-22 17:39:21 -040058// Elide returns the first bit of its input string with a suffix of "..." if it's longer than
59// a comfortable 40 characters.
60func Elide(value string) string {
61 if len(value) > 40 {
62 return value[0:37] + "..."
63 }
64 return value
65}