github.com/cloudfoundry/libcfbuildpack@v1.91.23/buildpack/version.go (about)

     1  /*
     2   * Copyright 2018-2020 the original author or authors.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *      https://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package buildpack
    18  
    19  import (
    20  	"fmt"
    21  	"reflect"
    22  
    23  	"github.com/Masterminds/semver"
    24  )
    25  
    26  // Version is an extension to semver.Version to make it marshalable.
    27  type Version struct {
    28  	*semver.Version
    29  }
    30  
    31  // MarshalText makes Version satisfy the encoding.TextMarshaler interface.
    32  func (v Version) MarshalText() ([]byte, error) {
    33  	return []byte(v.Version.Original()), nil
    34  }
    35  
    36  // UnmarshalText makes Version satisfy the encoding.TextUnmarshaler interface.
    37  func (v *Version) UnmarshalText(text []byte) error {
    38  	s := string(text)
    39  
    40  	w, err := semver.NewVersion(s)
    41  	if err != nil {
    42  		return fmt.Errorf("invalid semantic version %s", s)
    43  	}
    44  
    45  	v.Version = w
    46  	return nil
    47  }
    48  
    49  func unmarshalText(from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) {
    50  	if from.Kind() != reflect.String {
    51  		return data, nil
    52  	}
    53  
    54  	if to != reflect.TypeOf(Version{}) {
    55  		return data, nil
    56  	}
    57  
    58  	w, err := semver.NewVersion(data.(string))
    59  	if err != nil {
    60  		return nil, fmt.Errorf("invalid semantic version %s", data)
    61  	}
    62  
    63  	return Version{w}, nil
    64  }