github.com/scaleway/scaleway-cli@v1.11.1/pkg/commands/search.go (about) 1 // Copyright (C) 2015 Scaleway. All rights reserved. 2 // Use of this source code is governed by a MIT-style 3 // license that can be found in the LICENSE.md file. 4 5 package commands 6 7 import ( 8 "fmt" 9 "strings" 10 "text/tabwriter" 11 12 "github.com/renstrom/fuzzysearch/fuzzy" 13 "github.com/scaleway/scaleway-cli/pkg/api" 14 "github.com/scaleway/scaleway-cli/pkg/utils" 15 ) 16 17 // SearchArgs are flags for the `RunSearch` function 18 type SearchArgs struct { 19 Term string 20 NoTrunc bool 21 } 22 23 // RunSearch is the handler for 'scw search' 24 func RunSearch(ctx CommandContext, args SearchArgs) error { 25 // FIXME: parallelize API calls 26 27 term := strings.ToLower(args.Term) 28 w := tabwriter.NewWriter(ctx.Stdout, 10, 1, 3, ' ', 0) 29 defer w.Flush() 30 fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n") 31 32 var entries = []api.ScalewayImageInterface{} 33 34 images, err := ctx.API.GetImages() 35 if err != nil { 36 return fmt.Errorf("unable to fetch images from the Scaleway API: %v", err) 37 } 38 for _, val := range *images { 39 if fuzzy.Match(term, strings.ToLower(val.Name)) { 40 entries = append(entries, api.ScalewayImageInterface{ 41 Type: "image", 42 Name: val.Name, 43 Public: val.Public, 44 }) 45 } 46 } 47 48 snapshots, err := ctx.API.GetSnapshots() 49 if err != nil { 50 return fmt.Errorf("unable to fetch snapshots from the Scaleway API: %v", err) 51 } 52 for _, val := range *snapshots { 53 if fuzzy.Match(term, strings.ToLower(val.Name)) { 54 entries = append(entries, api.ScalewayImageInterface{ 55 Type: "snapshot", 56 Name: val.Name, 57 Public: false, 58 }) 59 } 60 } 61 62 for _, image := range entries { 63 // name field 64 name := utils.TruncIf(utils.Wordify(image.Name), 45, !args.NoTrunc) 65 66 // description field 67 var description string 68 switch image.Type { 69 case "image": 70 if image.Public { 71 description = "public image" 72 } else { 73 description = "user image" 74 } 75 76 case "snapshot": 77 description = "user snapshot" 78 } 79 description = utils.TruncIf(utils.Wordify(description), 45, !args.NoTrunc) 80 81 // official field 82 var official string 83 if image.Public { 84 official = "[OK]" 85 } else { 86 official = "" 87 } 88 89 fmt.Fprintf(w, "%s\t%s\t%d\t%s\t%s\n", name, description, 0, official, "") 90 } 91 return nil 92 }