github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/environs/tools/storage.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package tools
     5  
     6  import (
     7  	"errors"
     8  	"strings"
     9  
    10  	"launchpad.net/juju-core/environs/storage"
    11  	coretools "launchpad.net/juju-core/tools"
    12  	"launchpad.net/juju-core/version"
    13  )
    14  
    15  var ErrNoTools = errors.New("no tools available")
    16  
    17  const (
    18  	toolPrefix = "tools/releases/juju-"
    19  	toolSuffix = ".tgz"
    20  )
    21  
    22  // StorageName returns the name that is used to store and retrieve the
    23  // given version of the juju tools.
    24  func StorageName(vers version.Binary) string {
    25  	return toolPrefix + vers.String() + toolSuffix
    26  }
    27  
    28  // ReadList returns a List of the tools in store with the given major.minor version.
    29  // If minorVersion = -1, then only majorVersion is considered.
    30  // If store contains no such tools, it returns ErrNoMatches.
    31  func ReadList(stor storage.StorageReader, majorVersion, minorVersion int) (coretools.List, error) {
    32  	if minorVersion >= 0 {
    33  		logger.Debugf("reading v%d.%d tools", majorVersion, minorVersion)
    34  	} else {
    35  		logger.Debugf("reading v%d.* tools", majorVersion)
    36  	}
    37  	names, err := storage.List(stor, toolPrefix)
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  	var list coretools.List
    42  	var foundAnyTools bool
    43  	for _, name := range names {
    44  		if !strings.HasPrefix(name, toolPrefix) || !strings.HasSuffix(name, toolSuffix) {
    45  			continue
    46  		}
    47  		var t coretools.Tools
    48  		vers := name[len(toolPrefix) : len(name)-len(toolSuffix)]
    49  		if t.Version, err = version.ParseBinary(vers); err != nil {
    50  			logger.Debugf("failed to parse version %q: %v", vers, err)
    51  			continue
    52  		}
    53  		foundAnyTools = true
    54  		// Major version must match specified value.
    55  		if t.Version.Major != majorVersion {
    56  			continue
    57  		}
    58  		// If specified minor version value supplied, minor version must match.
    59  		if minorVersion >= 0 && t.Version.Minor != minorVersion {
    60  			continue
    61  		}
    62  		logger.Debugf("found %s", vers)
    63  		if t.URL, err = stor.URL(name); err != nil {
    64  			return nil, err
    65  		}
    66  		list = append(list, &t)
    67  	}
    68  	if len(list) == 0 {
    69  		if foundAnyTools {
    70  			return nil, coretools.ErrNoMatches
    71  		}
    72  		return nil, ErrNoTools
    73  	}
    74  	return list, nil
    75  }