github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/environs/tools/versionfile.go (about)

     1  // Copyright 2017 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package tools
     5  
     6  import (
     7  	"crypto/sha256"
     8  	"encoding/hex"
     9  	"io"
    10  	"io/ioutil"
    11  
    12  	"github.com/juju/errors"
    13  	"gopkg.in/yaml.v2"
    14  )
    15  
    16  // VersionHash contains the SHA256 of one jujud version.
    17  type VersionHash struct {
    18  	Version string `yaml:"version"`
    19  	SHA256  string `yaml:"sha256"`
    20  }
    21  
    22  // Versions stores the content of a jujud signature file.
    23  type Versions struct {
    24  	Versions []VersionHash `yaml:"versions"`
    25  }
    26  
    27  // ParseVersions constructs a versions object from a reader..
    28  func ParseVersions(r io.Reader) (*Versions, error) {
    29  	data, err := ioutil.ReadAll(r)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	var results Versions
    34  	err = yaml.Unmarshal(data, &results)
    35  	if err != nil {
    36  		return nil, errors.Trace(err)
    37  	}
    38  	return &results, nil
    39  }
    40  
    41  // VersionsMatching returns all version numbers for which the SHA256
    42  // matches the content of the reader passed in.
    43  func (v *Versions) VersionsMatching(r io.Reader) ([]string, error) {
    44  	hash := sha256.New()
    45  	_, err := io.Copy(hash, r)
    46  	if err != nil {
    47  		return nil, errors.Trace(err)
    48  	}
    49  	return v.versionsMatchingHash(hex.EncodeToString(hash.Sum(nil))), nil
    50  }
    51  
    52  // versionsMatchingHash returns all version numbers for which the SHA256
    53  // matches the hash passed in.
    54  func (v *Versions) versionsMatchingHash(h string) []string {
    55  	logger.Debugf("looking for sha256 %s", h)
    56  	var results []string
    57  	for i := range v.Versions {
    58  		if v.Versions[i].SHA256 == h {
    59  			results = append(results, v.Versions[i].Version)
    60  		}
    61  	}
    62  	return results
    63  }