github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/plugin/discovery/get_cache.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package discovery
     5  
     6  // PluginCache is an interface implemented by objects that are able to maintain
     7  // a cache of plugins.
     8  type PluginCache interface {
     9  	// CachedPluginPath returns a path where the requested plugin is already
    10  	// cached, or an empty string if the requested plugin is not yet cached.
    11  	CachedPluginPath(kind string, name string, version Version) string
    12  
    13  	// InstallDir returns the directory that new plugins should be installed into
    14  	// in order to populate the cache. This directory should be used as the
    15  	// first argument to getter.Get when downloading plugins with go-getter.
    16  	//
    17  	// After installing into this directory, use CachedPluginPath to obtain the
    18  	// path where the plugin was installed.
    19  	InstallDir() string
    20  }
    21  
    22  // NewLocalPluginCache returns a PluginCache that caches plugins in a
    23  // given local directory.
    24  func NewLocalPluginCache(dir string) PluginCache {
    25  	return &pluginCache{
    26  		Dir: dir,
    27  	}
    28  }
    29  
    30  type pluginCache struct {
    31  	Dir string
    32  }
    33  
    34  func (c *pluginCache) CachedPluginPath(kind string, name string, version Version) string {
    35  	allPlugins := FindPlugins(kind, []string{c.Dir})
    36  	plugins := allPlugins.WithName(name).WithVersion(version)
    37  
    38  	if plugins.Count() == 0 {
    39  		// nothing cached
    40  		return ""
    41  	}
    42  
    43  	// There should generally be only one plugin here; if there's more than
    44  	// one match for some reason then we'll just choose one arbitrarily.
    45  	plugin := plugins.Newest()
    46  	return plugin.Path
    47  }
    48  
    49  func (c *pluginCache) InstallDir() string {
    50  	return c.Dir
    51  }