1 // Copyright 2019 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 load 16 17 import ( 18 "cuelang.org/go/cue/ast" 19 "cuelang.org/go/cue/format" 20 ) 21 22 // A Source represents file contents. 23 type Source interface { 24 contents() ([]byte, *ast.File, error) 25 } 26 27 // FromString creates a Source from the given string. 28 func FromString(s string) Source { 29 return stringSource(s) 30 } 31 32 // FromBytes creates a Source from the given bytes. The contents are not 33 // copied and should not be modified. 34 func FromBytes(b []byte) Source { 35 return bytesSource(b) 36 } 37 38 // FromFile creates a Source from the given *ast.File. The file should not be 39 // modified. It is assumed the file is error-free. 40 func FromFile(f *ast.File) Source { 41 return (*fileSource)(f) 42 } 43 44 type stringSource string 45 46 func (s stringSource) contents() ([]byte, *ast.File, error) { 47 return []byte(s), nil, nil 48 } 49 50 type bytesSource []byte 51 52 func (s bytesSource) contents() ([]byte, *ast.File, error) { 53 return []byte(s), nil, nil 54 } 55 56 type fileSource ast.File 57 58 func (s *fileSource) contents() ([]byte, *ast.File, error) { 59 f := (*ast.File)(s) 60 // TODO: wasteful formatting, but needed for now. 61 b, err := format.Node(f) 62 return b, f, err 63 } 64