cuelang.org/go@v0.10.1/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  	"os"
    24  	"strings"
    25  )
    26  
    27  // ReadAll loads the source bytes for the given arguments. If src != nil,
    28  // ReadAll converts src to a []byte if possible; otherwise it returns an
    29  // error. If src == nil, ReadAll returns the result of reading the file
    30  // specified by filename.
    31  func ReadAll(filename string, src any) ([]byte, error) {
    32  	if src != nil {
    33  		switch src := src.(type) {
    34  		case string:
    35  			return []byte(src), nil
    36  		case []byte:
    37  			return src, nil
    38  		case *bytes.Buffer:
    39  			// is io.Reader, but src is already available in []byte form
    40  			if src != nil {
    41  				return src.Bytes(), nil
    42  			}
    43  		case io.Reader:
    44  			var buf bytes.Buffer
    45  			if _, err := io.Copy(&buf, src); 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 os.ReadFile(filename)
    53  }
    54  
    55  // Open creates a source reader for the given arguments. If src != nil,
    56  // Open converts src to an io.Open if possible; otherwise it returns an
    57  // error. If src == nil, Open returns the result of opening the file
    58  // specified by filename.
    59  func Open(filename string, src any) (io.ReadCloser, error) {
    60  	if src != nil {
    61  		switch src := src.(type) {
    62  		case string:
    63  			return io.NopCloser(strings.NewReader(src)), nil
    64  		case []byte:
    65  			return io.NopCloser(bytes.NewReader(src)), nil
    66  		case io.Reader:
    67  			return io.NopCloser(src), nil
    68  		}
    69  		return nil, fmt.Errorf("invalid source type %T", src)
    70  	}
    71  	return os.Open(filename)
    72  }