github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/travis/yaml/strings.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  	"errors"
    19  	"fmt"
    20  )
    21  
    22  // Stringorslice represents a string or an array of strings.
    23  type Stringorslice []string
    24  
    25  // UnmarshalYAML implements the unmarshal interface.
    26  func (s *Stringorslice) UnmarshalYAML(unmarshal func(interface{}) error) error {
    27  	var stringType string
    28  	if err := unmarshal(&stringType); err == nil {
    29  		*s = []string{stringType}
    30  		return nil
    31  	}
    32  
    33  	var sliceType []interface{}
    34  	if err := unmarshal(&sliceType); err == nil {
    35  		parts, err := toStrings(sliceType)
    36  		if err != nil {
    37  			return err
    38  		}
    39  		*s = parts
    40  		return nil
    41  	}
    42  
    43  	return errors.New("failed to unmarshal string or string array")
    44  }
    45  
    46  // helper function converts a slice of interfaces
    47  // to a slice of strings.
    48  func toStrings(s []interface{}) ([]string, error) {
    49  	if len(s) == 0 {
    50  		return nil, nil
    51  	}
    52  	r := make([]string, len(s))
    53  	for k, v := range s {
    54  		if sv, ok := v.(string); ok {
    55  			r[k] = sv
    56  		} else {
    57  			return nil, fmt.Errorf("cannot unmarshal %v of type %T into a string value", v, v)
    58  		}
    59  	}
    60  	return r, nil
    61  }