/pkg/names/generate.go

https://github.com/tektoncd/pipeline · Go · 72 lines · 33 code · 12 blank · 27 comment · 3 complexity · 151916ab7b93dc72604e22e7919eac44 MD5 · raw file

  1. /*
  2. Copyright 2019 The Tekton Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package names
  14. import (
  15. "fmt"
  16. "regexp"
  17. utilrand "k8s.io/apimachinery/pkg/util/rand"
  18. )
  19. // NameGenerator generates names for objects. Some backends may have more information
  20. // available to guide selection of new names and this interface hides those details.
  21. type NameGenerator interface {
  22. // RestrictLengthWithRandomSuffix generates a valid name from the base name, adding a random suffix to the
  23. // the base. If base is valid, the returned name must also be valid. The generator is
  24. // responsible for knowing the maximum valid name length.
  25. RestrictLengthWithRandomSuffix(base string) string
  26. // RestrictLength generates a valid name from the name of a step specified in a Task,
  27. // shortening it to the maximum valid name length if needed.
  28. RestrictLength(base string) string
  29. }
  30. // simpleNameGenerator generates random names.
  31. type simpleNameGenerator struct{}
  32. // SimpleNameGenerator is a generator that returns the name plus a random suffix of five alphanumerics
  33. // when a name is requested. The string is guaranteed to not exceed the length of a standard Kubernetes
  34. // name (63 characters)
  35. var SimpleNameGenerator NameGenerator = simpleNameGenerator{}
  36. const (
  37. // TODO: make this flexible for non-core resources with alternate naming rules.
  38. maxNameLength = 63
  39. randomLength = 5
  40. maxGeneratedNameLength = maxNameLength - randomLength - 1
  41. )
  42. func (simpleNameGenerator) RestrictLengthWithRandomSuffix(base string) string {
  43. if len(base) > maxGeneratedNameLength {
  44. base = base[:maxGeneratedNameLength]
  45. }
  46. return fmt.Sprintf("%s-%s", base, utilrand.String(randomLength))
  47. }
  48. var alphaNumericRE = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
  49. func (simpleNameGenerator) RestrictLength(base string) string {
  50. if len(base) > maxNameLength {
  51. base = base[:maxNameLength]
  52. }
  53. for !alphaNumericRE.MatchString(base[len(base)-1:]) {
  54. base = base[:len(base)-1]
  55. }
  56. return base
  57. }