github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/cmd/search.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"encoding/json"
     7  	"github.com/sirupsen/logrus"
     8  	"github.com/solo-io/unik/pkg/types"
     9  	"github.com/layer-x/layerx-commons/lxhttpclient"
    10  	"github.com/spf13/cobra"
    11  	"net/http"
    12  	"strings"
    13  )
    14  
    15  var searchCmd = &cobra.Command{
    16  	Use:   "search",
    17  	Short: "Search available images in the targeted Unik Image Repository",
    18  	Long: `
    19  Usage:
    20  
    21  unik search
    22  
    23    - or -
    24  
    25  unik search --imageName <imageName>
    26  
    27  Requires that you first authenticate to a unik image repository with 'unik login'`,
    28  	Run: func(cmd *cobra.Command, args []string) {
    29  		c, err := getHubConfig()
    30  		if err != nil {
    31  			logrus.Fatal(err)
    32  		}
    33  		resp, body, err := lxhttpclient.Get(c.URL, "/images", nil)
    34  		if err != nil {
    35  			logrus.Fatal(err)
    36  		}
    37  		if resp.StatusCode != http.StatusOK {
    38  			logrus.Fatal(fmt.Sprintf("failed with status %v: %s", resp.StatusCode, string(body)))
    39  		}
    40  		var images []*types.UserImage
    41  		if err := json.Unmarshal(body, &images); err != nil {
    42  			logrus.Fatal(err)
    43  		}
    44  		filteredImages := images[:0]
    45  		if imageName != "" {
    46  			for _, image := range images {
    47  				if !strings.Contains(image.Name, imageName) {
    48  					filteredImages = append(filteredImages, image)
    49  				}
    50  			}
    51  		} else {
    52  			filteredImages = images
    53  		}
    54  		printUserImages(filteredImages...)
    55  	},
    56  }
    57  
    58  func init() {
    59  	RootCmd.AddCommand(searchCmd)
    60  	searchCmd.Flags().StringVar(&imageName, "imageName", "", "<string,optional> search images by names containing this string")
    61  }