stringid.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Package stringid provides helper functions for dealing with string identifiers
  2. package stringid // import "github.com/docker/docker/pkg/stringid"
  3. import (
  4. "crypto/rand"
  5. "encoding/hex"
  6. "fmt"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. )
  11. const shortLen = 12
  12. var (
  13. validShortID = regexp.MustCompile("^[a-f0-9]{12}$")
  14. validHex = regexp.MustCompile(`^[a-f0-9]{64}$`)
  15. )
  16. // IsShortID determines if an arbitrary string *looks like* a short ID.
  17. func IsShortID(id string) bool {
  18. return validShortID.MatchString(id)
  19. }
  20. // TruncateID returns a shorthand version of a string identifier for convenience.
  21. // A collision with other shorthands is very unlikely, but possible.
  22. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  23. // will need to use a longer prefix, or the full-length Id.
  24. func TruncateID(id string) string {
  25. if i := strings.IndexRune(id, ':'); i >= 0 {
  26. id = id[i+1:]
  27. }
  28. if len(id) > shortLen {
  29. id = id[:shortLen]
  30. }
  31. return id
  32. }
  33. // GenerateRandomID returns a unique id.
  34. func GenerateRandomID() string {
  35. b := make([]byte, 32)
  36. for {
  37. if _, err := rand.Read(b); err != nil {
  38. panic(err) // This shouldn't happen
  39. }
  40. id := hex.EncodeToString(b)
  41. // if we try to parse the truncated for as an int and we don't have
  42. // an error then the value is all numeric and causes issues when
  43. // used as a hostname. ref #3869
  44. if _, err := strconv.ParseInt(TruncateID(id), 10, 64); err == nil {
  45. continue
  46. }
  47. return id
  48. }
  49. }
  50. // ValidateID checks whether an ID string is a valid image ID.
  51. func ValidateID(id string) error {
  52. if ok := validHex.MatchString(id); !ok {
  53. return fmt.Errorf("image ID %q is invalid", id)
  54. }
  55. return nil
  56. }