github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/cf/actors/pluginrepo/plugin_repo.go (about)

     1  package pluginrepo
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"net/http"
     8  	"strings"
     9  
    10  	"code.cloudfoundry.org/cli/cf/models"
    11  	clipr "code.cloudfoundry.org/cli-plugin-repo/web"
    12  
    13  	. "code.cloudfoundry.org/cli/cf/i18n"
    14  )
    15  
    16  //go:generate counterfeiter . PluginRepo
    17  
    18  type PluginRepo interface {
    19  	GetPlugins([]models.PluginRepo) (map[string][]clipr.Plugin, []string)
    20  }
    21  
    22  type pluginRepo struct{}
    23  
    24  func NewPluginRepo() PluginRepo {
    25  	return pluginRepo{}
    26  }
    27  
    28  func (r pluginRepo) GetPlugins(repos []models.PluginRepo) (map[string][]clipr.Plugin, []string) {
    29  	var pluginList clipr.PluginsJson
    30  	repoError := []string{}
    31  	repoPlugins := make(map[string][]clipr.Plugin)
    32  
    33  	for _, repo := range repos {
    34  		resp, err := http.Get(getListEndpoint(repo.URL))
    35  		if err != nil {
    36  			repoError = append(repoError, fmt.Sprintf(T("Error requesting from")+" '%s' - %s", repo.Name, err.Error()))
    37  			continue
    38  		} else {
    39  			defer resp.Body.Close()
    40  
    41  			body, err := ioutil.ReadAll(resp.Body)
    42  			if err != nil {
    43  				repoError = append(repoError, fmt.Sprintf(T("Error reading response from")+" '%s' - %s ", repo.Name, err.Error()))
    44  				continue
    45  			}
    46  
    47  			pluginList = clipr.PluginsJson{Plugins: nil}
    48  			err = json.Unmarshal(body, &pluginList)
    49  			if err != nil {
    50  				repoError = append(repoError, fmt.Sprintf(T("Invalid json data from")+" '%s' - %s", repo.Name, err.Error()))
    51  				continue
    52  			} else if pluginList.Plugins == nil {
    53  				repoError = append(repoError, T("Invalid data from '{{.repoName}}' - plugin data does not exist", map[string]interface{}{"repoName": repo.Name}))
    54  				continue
    55  			}
    56  
    57  		}
    58  
    59  		repoPlugins[repo.Name] = pluginList.Plugins
    60  	}
    61  
    62  	return repoPlugins, repoError
    63  }
    64  
    65  func getListEndpoint(url string) string {
    66  	if strings.HasSuffix(url, "/") {
    67  		return url + "list"
    68  	}
    69  	return url + "/list"
    70  }