cuelang.org/go@v0.10.1/internal/encoding/detect.go (about) 1 // Copyright 2020 CUE Authors 2 // 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package encoding 16 17 import ( 18 "net/url" 19 "path" 20 "strings" 21 22 "cuelang.org/go/cue" 23 "cuelang.org/go/cue/build" 24 ) 25 26 // Detect detects the interpretation. 27 func Detect(v cue.Value) (i build.Interpretation) { 28 switch { 29 case isOpenAPI(v): 30 return build.OpenAPI 31 case isJSONSchema(v): 32 return build.JSONSchema 33 } 34 return i 35 } 36 37 func isOpenAPI(v cue.Value) bool { 38 s, _ := v.LookupPath(cue.MakePath(cue.Str("openapi"))).String() 39 if !strings.HasPrefix(s, "3.") { 40 return false 41 } 42 if _, err := v.LookupPath(cue.MakePath(cue.Str("info"), cue.Str("title"))).String(); err != nil { 43 return false 44 } 45 if _, err := v.LookupPath(cue.MakePath(cue.Str("info"), cue.Str("version"))).String(); err != nil { 46 return false 47 } 48 return true 49 } 50 51 func isJSONSchema(v cue.Value) bool { 52 s, err := v.LookupPath(cue.MakePath(cue.Str("$schema"))).String() 53 if err != nil { 54 return false 55 } 56 u, err := url.Parse(s) 57 if err != nil { 58 return false 59 } 60 if u.Hostname() != "json-schema.org" { 61 return false 62 } 63 if _, base := path.Split(u.EscapedPath()); base != "schema" { 64 return false 65 } 66 return true 67 }