ref.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package blob
  2. import (
  3. "cmp"
  4. "iter"
  5. "slices"
  6. "strings"
  7. )
  8. type PartKind int
  9. // Levels of concreteness
  10. const (
  11. Invalid PartKind = iota
  12. Domain
  13. Namespace
  14. Name
  15. Tag
  16. Build
  17. )
  18. var kindNames = map[PartKind]string{
  19. Invalid: "Invalid",
  20. Domain: "Domain",
  21. Namespace: "Namespace",
  22. Name: "Name",
  23. Tag: "Tag",
  24. Build: "Build",
  25. }
  26. // Ref is an opaque reference to a blob.
  27. //
  28. // It is comparable and can be used as a map key.
  29. //
  30. // Users or Ref must check Valid before using it.
  31. type Ref struct {
  32. domain string
  33. namespace string
  34. name string
  35. tag string
  36. build string
  37. }
  38. // WithDomain returns a copy of r with the provided domain. If the provided
  39. // domain is empty, it returns the short, unqualified copy of r.
  40. func (r Ref) WithDomain(s string) Ref {
  41. r.domain = s
  42. return r
  43. }
  44. // WithNamespace returns a copy of r with the provided namespace. If the
  45. // provided namespace is empty, it returns the short, unqualified copy of r.
  46. func (r Ref) WithNamespace(s string) Ref {
  47. r.namespace = s
  48. return r
  49. }
  50. // WithName returns a copy of r with the provided name. If the provided
  51. // name is empty, it returns the short, unqualified copy of r.
  52. func (r Ref) WithName(s string) Ref {
  53. r.name = s
  54. return r
  55. }
  56. func (r Ref) WithTag(s string) Ref {
  57. r.tag = s
  58. return r
  59. }
  60. // WithBuild returns a copy of r with the provided build. If the provided
  61. // build is empty, it returns the short, unqualified copy of r.
  62. //
  63. // The build is normalized to uppercase.
  64. func (r Ref) WithBuild(s string) Ref {
  65. r.build = strings.ToUpper(s)
  66. return r
  67. }
  68. // Format returns a string representation of the ref with the given
  69. // concreteness. If a part is missing, it is replaced with a loud
  70. // placeholder.
  71. func (r Ref) Full() string {
  72. r.domain = cmp.Or(r.domain, "!(MISSING DOMAIN)")
  73. r.namespace = cmp.Or(r.namespace, "!(MISSING NAMESPACE)")
  74. r.name = cmp.Or(r.name, "!(MISSING NAME)")
  75. r.tag = cmp.Or(r.tag, "!(MISSING TAG)")
  76. r.build = cmp.Or(r.build, "!(MISSING BUILD)")
  77. return r.String()
  78. }
  79. func (r Ref) NameAndTag() string {
  80. r.domain = ""
  81. r.namespace = ""
  82. r.build = ""
  83. return r.String()
  84. }
  85. func (r Ref) NameTagAndBuild() string {
  86. r.domain = ""
  87. r.namespace = ""
  88. return r.String()
  89. }
  90. // String returns the fully qualified ref string.
  91. func (r Ref) String() string {
  92. var b strings.Builder
  93. if r.domain != "" {
  94. b.WriteString(r.domain)
  95. b.WriteString("/")
  96. }
  97. if r.namespace != "" {
  98. b.WriteString(r.namespace)
  99. b.WriteString("/")
  100. }
  101. b.WriteString(r.name)
  102. if r.tag != "" {
  103. b.WriteString(":")
  104. b.WriteString(r.tag)
  105. }
  106. if r.build != "" {
  107. b.WriteString("+")
  108. b.WriteString(r.build)
  109. }
  110. return b.String()
  111. }
  112. // Complete returns true if the ref is valid and has no empty parts.
  113. func (r Ref) Complete() bool {
  114. return r.Valid() && !slices.Contains(r.Parts(), "")
  115. }
  116. func (r Ref) CompleteWithoutBuild() bool {
  117. return r.Valid() && !slices.Contains(r.Parts()[:Tag], "")
  118. }
  119. // Less returns true if r is less concrete than o; false otherwise.
  120. func (r Ref) Less(o Ref) bool {
  121. rp := r.Parts()
  122. op := o.Parts()
  123. for i := range rp {
  124. if rp[i] < op[i] {
  125. return true
  126. }
  127. }
  128. return false
  129. }
  130. // Parts returns the parts of the ref in order of concreteness.
  131. //
  132. // The length of the returned slice is always 5.
  133. func (r Ref) Parts() []string {
  134. return []string{
  135. r.domain,
  136. r.namespace,
  137. r.name,
  138. r.tag,
  139. r.build,
  140. }
  141. }
  142. func (r Ref) Domain() string { return r.namespace }
  143. func (r Ref) Namespace() string { return r.namespace }
  144. func (r Ref) Name() string { return r.name }
  145. func (r Ref) Tag() string { return r.tag }
  146. func (r Ref) Build() string { return r.build }
  147. // ParseRef parses a ref string into a Ref. A ref string is a name, an
  148. // optional tag, and an optional build, separated by colons and pluses.
  149. //
  150. // The name must be valid ascii [a-zA-Z0-9_].
  151. // The tag must be valid ascii [a-zA-Z0-9_].
  152. // The build must be valid ascii [a-zA-Z0-9_].
  153. //
  154. // It returns then zero value if the ref is invalid.
  155. //
  156. // // Valid Examples:
  157. // ParseRef("mistral:latest") returns ("mistral", "latest", "")
  158. // ParseRef("mistral") returns ("mistral", "", "")
  159. // ParseRef("mistral:30B") returns ("mistral", "30B", "")
  160. // ParseRef("mistral:7b") returns ("mistral", "7b", "")
  161. // ParseRef("mistral:7b+Q4_0") returns ("mistral", "7b", "Q4_0")
  162. // ParseRef("mistral+KQED") returns ("mistral", "latest", "KQED")
  163. // ParseRef(".x.:7b+Q4_0:latest") returns (".x.", "7b", "Q4_0")
  164. // ParseRef("-grok-f.oo:7b+Q4_0") returns ("-grok-f.oo", "7b", "Q4_0")
  165. //
  166. // // Invalid Examples:
  167. // ParseRef("m stral") returns ("", "", "") // zero
  168. // ParseRef("... 129 chars ...") returns ("", "", "") // zero
  169. func ParseRef(s string) Ref {
  170. var r Ref
  171. for kind, part := range Parts(s) {
  172. switch kind {
  173. case Domain:
  174. r = r.WithDomain(part)
  175. case Namespace:
  176. r = r.WithNamespace(part)
  177. case Name:
  178. r.name = part
  179. case Tag:
  180. r = r.WithTag(part)
  181. case Build:
  182. r = r.WithBuild(part)
  183. case Invalid:
  184. return Ref{}
  185. }
  186. }
  187. if !r.Valid() {
  188. return Ref{}
  189. }
  190. return r
  191. }
  192. // Parts returns a sequence of the parts of a ref string from most specific
  193. // to least specific.
  194. //
  195. // It normalizes the input string by removing "http://" and "https://" only.
  196. // No other normalization is done.
  197. func Parts(s string) iter.Seq2[PartKind, string] {
  198. return func(yield func(PartKind, string) bool) {
  199. if strings.HasPrefix(s, "http://") {
  200. s = s[len("http://"):]
  201. }
  202. if strings.HasPrefix(s, "https://") {
  203. s = s[len("https://"):]
  204. }
  205. if len(s) > 255 || len(s) == 0 {
  206. return
  207. }
  208. yieldValid := func(kind PartKind, part string) bool {
  209. if !isValidPart(part) {
  210. yield(Invalid, "")
  211. return false
  212. }
  213. return yield(kind, part)
  214. }
  215. state, j := Build, len(s)
  216. for i := len(s) - 1; i >= 0; i-- {
  217. switch s[i] {
  218. case '+':
  219. switch state {
  220. case Build:
  221. if !yieldValid(Build, s[i+1:j]) {
  222. return
  223. }
  224. state, j = Tag, i
  225. default:
  226. yield(Invalid, "")
  227. return
  228. }
  229. case ':':
  230. switch state {
  231. case Build, Tag:
  232. if !yieldValid(Tag, s[i+1:j]) {
  233. return
  234. }
  235. state, j = Name, i
  236. default:
  237. yield(Invalid, "")
  238. return
  239. }
  240. case '/':
  241. switch state {
  242. case Name, Tag, Build:
  243. if !yieldValid(Name, s[i+1:j]) {
  244. return
  245. }
  246. state, j = Namespace, i
  247. case Namespace:
  248. if !yieldValid(Namespace, s[i+1:j]) {
  249. return
  250. }
  251. state, j = Domain, i
  252. default:
  253. yield(Invalid, "")
  254. return
  255. }
  256. default:
  257. if !isValidPart(s[i : i+1]) {
  258. yield(Invalid, "")
  259. return
  260. }
  261. }
  262. }
  263. if state <= Namespace {
  264. yieldValid(state, s[:j])
  265. } else {
  266. yieldValid(Name, s[:j])
  267. }
  268. }
  269. }
  270. // Complete is the same as ParseRef(s).Complete().
  271. //
  272. // Future versions may be faster than calling ParseRef(s).Complete(), so if
  273. // need to know if a ref is complete and don't need the ref, use this
  274. // function.
  275. func Complete(s string) bool {
  276. // TODO(bmizerany): fast-path this with a quick scan withput
  277. // allocating strings
  278. return ParseRef(s).Complete()
  279. }
  280. // Valid returns true if the ref has a valid name. To know if a ref is
  281. // "complete", use Complete.
  282. func (r Ref) Valid() bool {
  283. // Parts ensures we only have valid parts, so no need to validate
  284. // them here, only check if we have a name or not.
  285. return r.name != ""
  286. }
  287. // isValidPart returns true if given part is valid ascii [a-zA-Z0-9_\.-]
  288. func isValidPart(s string) bool {
  289. if s == "" {
  290. return false
  291. }
  292. for _, c := range []byte(s) {
  293. if c == '.' || c == '-' {
  294. return true
  295. }
  296. if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' {
  297. continue
  298. } else {
  299. return false
  300. }
  301. }
  302. return true
  303. }