github.com/opentofu/opentofu@v1.7.1/internal/plugin/discovery/get_cache.go (about)

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