github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/bitbucket/yaml/cache.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 "errors"
    18  
    19  type (
    20  	// Cache configures a cache path.
    21  	Cache struct {
    22  		Key  *CacheKey
    23  		Path string
    24  	}
    25  
    26  	// temporary data structure for unmarshaling and
    27  	// marshaling caches.
    28  	cache struct {
    29  		Key  *CacheKey `json:"key"`
    30  		Path string    `json:"path"`
    31  	}
    32  
    33  	CacheKey struct {
    34  		Files []string `json:"files"`
    35  	}
    36  )
    37  
    38  // MarshalYAML implements the marshal interface.
    39  func (v *Cache) MarshalYAML() (interface{}, error) {
    40  	if v.Key == nil {
    41  		return v.Path, nil
    42  	}
    43  	return &cache{
    44  		Key:  v.Key,
    45  		Path: v.Path,
    46  	}, nil
    47  }
    48  
    49  // UnmarshalYAML implements the unmarshal interface.
    50  func (v *Cache) UnmarshalYAML(unmarshal func(interface{}) error) error {
    51  	var out1 string
    52  	var out2 *cache
    53  	if err := unmarshal(&out1); err == nil {
    54  		v.Path = out1
    55  		return nil
    56  	}
    57  	if err := unmarshal(&out2); err == nil {
    58  		v.Path = out2.Path
    59  		v.Key = out2.Key
    60  		return nil
    61  	}
    62  	return errors.New("failed to unmarshal cache")
    63  }