stringid.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. "errors"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. )
  11. const (
  12. shortLen = 12
  13. fullLen = 64
  14. )
  15. var (
  16. validShortID = regexp.MustCompile("^[a-f0-9]{12}$")
  17. validHex = regexp.MustCompile(`^[a-f0-9]{64}$`)
  18. )
  19. // IsShortID determines if id has the correct format and length for a short ID.
  20. // It checks the IDs length and if it consists of valid characters for IDs (a-f0-9).
  21. func IsShortID(id string) bool {
  22. if len(id) != shortLen {
  23. return false
  24. }
  25. return validShortID.MatchString(id)
  26. }
  27. // TruncateID returns a shorthand version of a string identifier for convenience.
  28. // A collision with other shorthands is very unlikely, but possible.
  29. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  30. // will need to use a longer prefix, or the full-length Id.
  31. func TruncateID(id string) string {
  32. if i := strings.IndexRune(id, ':'); i >= 0 {
  33. id = id[i+1:]
  34. }
  35. if len(id) > shortLen {
  36. id = id[:shortLen]
  37. }
  38. return id
  39. }
  40. // GenerateRandomID returns a unique id.
  41. func GenerateRandomID() string {
  42. b := make([]byte, 32)
  43. for {
  44. if _, err := rand.Read(b); err != nil {
  45. panic(err) // This shouldn't happen
  46. }
  47. id := hex.EncodeToString(b)
  48. // if we try to parse the truncated for as an int and we don't have
  49. // an error then the value is all numeric and causes issues when
  50. // used as a hostname. ref #3869
  51. if _, err := strconv.ParseInt(TruncateID(id), 10, 64); err == nil {
  52. continue
  53. }
  54. return id
  55. }
  56. }
  57. // ValidateID checks whether an ID string is a valid, full-length image ID.
  58. func ValidateID(id string) error {
  59. if len(id) != fullLen {
  60. return errors.New("image ID '" + id + "' is invalid")
  61. }
  62. if !validHex.MatchString(id) {
  63. return errors.New("image ID '" + id + "' is invalid")
  64. }
  65. return nil
  66. }