github.com/equinix-metal/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/imagetranslation/file_source.go (about)

     1  /*
     2  Copyright 2017 Mirantis
     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      http://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 imagetranslation
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"path"
    24  
    25  	"github.com/ghodss/yaml"
    26  
    27  	"github.com/Mirantis/virtlet/pkg/api/virtlet.k8s/v1"
    28  )
    29  
    30  type fileConfigSource struct {
    31  	configsDirectory string
    32  }
    33  
    34  var _ ConfigSource = fileConfigSource{}
    35  
    36  type fileConfig struct {
    37  	name string
    38  	cs   *fileConfigSource
    39  }
    40  
    41  var _ TranslationConfig = fileConfig{}
    42  
    43  // Config implements ConfigSource Config
    44  func (cs fileConfigSource) Configs(ctx context.Context) ([]TranslationConfig, error) {
    45  	var result []TranslationConfig
    46  	r, err := ioutil.ReadDir(cs.configsDirectory)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	for _, f := range r {
    51  		if f.IsDir() {
    52  			continue
    53  		}
    54  		result = append(result, fileConfig{name: f.Name(), cs: &cs})
    55  	}
    56  	return result, nil
    57  }
    58  
    59  // Description implements ConfigSource Description
    60  func (cs fileConfigSource) Description() string {
    61  	return fmt.Sprintf("local directory %s", cs.configsDirectory)
    62  }
    63  
    64  // Name implements TranslationConfig Name
    65  func (c fileConfig) ConfigName() string {
    66  	return c.name
    67  }
    68  
    69  // Payload implements TranslationConfig Payload
    70  func (c fileConfig) Payload() (v1.ImageTranslation, error) {
    71  	data, err := ioutil.ReadFile(path.Join(c.cs.configsDirectory, c.name))
    72  	var tr v1.ImageTranslation
    73  	if err != nil {
    74  		return tr, err
    75  	}
    76  	err = yaml.Unmarshal(data, &tr)
    77  	return tr, err
    78  }
    79  
    80  // NewFileConfigSource is a factory for a directory-based config source
    81  func NewFileConfigSource(configsDirectory string) ConfigSource {
    82  	return fileConfigSource{configsDirectory: configsDirectory}
    83  }