github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/harness/yaml/parse.go (about)

     1  // Copyright 2022 Harness, Inc.
     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 yaml
    16  
    17  import (
    18  	"bytes"
    19  	"encoding/json"
    20  	"io"
    21  	"io/ioutil"
    22  	"os"
    23  
    24  	"github.com/ghodss/yaml"
    25  )
    26  
    27  // Parse parses the configuration from io.Reader r.
    28  func Parse(r io.Reader) (*Config, error) {
    29  	b, err := ioutil.ReadAll(r)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	b, err = yaml.YAMLToJSON(b)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	out := new(Config)
    38  	err = json.Unmarshal(b, out)
    39  	return out, err
    40  }
    41  
    42  // ParseBytes parses the configuration from bytes b.
    43  func ParseBytes(b []byte) (*Config, error) {
    44  	return Parse(
    45  		bytes.NewBuffer(b),
    46  	)
    47  }
    48  
    49  // ParseString parses the configuration from string s.
    50  func ParseString(s string) (*Config, error) {
    51  	return ParseBytes(
    52  		[]byte(s),
    53  	)
    54  }
    55  
    56  // ParseFile parses the configuration from path p.
    57  func ParseFile(p string) (*Config, error) {
    58  	f, err := os.Open(p)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  	defer f.Close()
    63  	return Parse(f)
    64  }