github.com/solo-io/cue@v0.4.7/internal/source/source.go (about)

     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 source contains utility functions that standardize reading source
    16  // bytes across cue packages.
    17  package source
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  	"io"
    23  	"io/ioutil"
    24  )
    25  
    26  // Read loads the source bytes for the given arguments. If src != nil,
    27  // Read converts src to a []byte if possible; otherwise it returns an
    28  // error. If src == nil, readSource returns the result of reading the file
    29  // specified by filename.
    30  //
    31  func Read(filename string, src interface{}) ([]byte, error) {
    32  	if src != nil {
    33  		switch s := src.(type) {
    34  		case string:
    35  			return []byte(s), nil
    36  		case []byte:
    37  			return s, nil
    38  		case *bytes.Buffer:
    39  			// is io.Reader, but src is already available in []byte form
    40  			if s != nil {
    41  				return s.Bytes(), nil
    42  			}
    43  		case io.Reader:
    44  			var buf bytes.Buffer
    45  			if _, err := io.Copy(&buf, s); err != nil {
    46  				return nil, err
    47  			}
    48  			return buf.Bytes(), nil
    49  		}
    50  		return nil, fmt.Errorf("invalid source type %T", src)
    51  	}
    52  	return ioutil.ReadFile(filename)
    53  }