github.com/rsampaio/docker@v0.7.2-0.20150827203920-fdc73cc3fc31/api/client/search.go (about) 1 package client 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "net/url" 7 "sort" 8 "strings" 9 "text/tabwriter" 10 11 Cli "github.com/docker/docker/cli" 12 flag "github.com/docker/docker/pkg/mflag" 13 "github.com/docker/docker/pkg/parsers" 14 "github.com/docker/docker/pkg/stringutils" 15 "github.com/docker/docker/registry" 16 ) 17 18 // ByStars sorts search results in ascending order by number of stars. 19 type ByStars []registry.SearchResult 20 21 func (r ByStars) Len() int { return len(r) } 22 func (r ByStars) Swap(i, j int) { r[i], r[j] = r[j], r[i] } 23 func (r ByStars) Less(i, j int) bool { return r[i].StarCount < r[j].StarCount } 24 25 // CmdSearch searches the Docker Hub for images. 26 // 27 // Usage: docker search [OPTIONS] TERM 28 func (cli *DockerCli) CmdSearch(args ...string) error { 29 cmd := Cli.Subcmd("search", []string{"TERM"}, "Search the Docker Hub for images", true) 30 noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") 31 trusted := cmd.Bool([]string{"#t", "#trusted", "#-trusted"}, false, "Only show trusted builds") 32 automated := cmd.Bool([]string{"-automated"}, false, "Only show automated builds") 33 stars := cmd.Uint([]string{"s", "#stars", "-stars"}, 0, "Only displays with at least x stars") 34 cmd.Require(flag.Exact, 1) 35 36 cmd.ParseFlags(args, true) 37 38 name := cmd.Arg(0) 39 v := url.Values{} 40 v.Set("term", name) 41 42 // Resolve the Repository name from fqn to hostname + name 43 taglessRemote, _ := parsers.ParseRepositoryTag(name) 44 repoInfo, err := registry.ParseRepositoryInfo(taglessRemote) 45 if err != nil { 46 return err 47 } 48 49 rdr, _, err := cli.clientRequestAttemptLogin("GET", "/images/search?"+v.Encode(), nil, nil, repoInfo.Index, "search") 50 if err != nil { 51 return err 52 } 53 54 defer rdr.Close() 55 56 results := ByStars{} 57 if err := json.NewDecoder(rdr).Decode(&results); err != nil { 58 return err 59 } 60 61 sort.Sort(sort.Reverse(results)) 62 63 w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0) 64 fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n") 65 for _, res := range results { 66 if ((*automated || *trusted) && (!res.IsTrusted && !res.IsAutomated)) || (int(*stars) > res.StarCount) { 67 continue 68 } 69 desc := strings.Replace(res.Description, "\n", " ", -1) 70 desc = strings.Replace(desc, "\r", " ", -1) 71 if !*noTrunc && len(desc) > 45 { 72 desc = stringutils.Truncate(desc, 42) + "..." 73 } 74 fmt.Fprintf(w, "%s\t%s\t%d\t", res.Name, desc, res.StarCount) 75 if res.IsOfficial { 76 fmt.Fprint(w, "[OK]") 77 78 } 79 fmt.Fprint(w, "\t") 80 if res.IsAutomated || res.IsTrusted { 81 fmt.Fprint(w, "[OK]") 82 } 83 fmt.Fprint(w, "\n") 84 } 85 w.Flush() 86 return nil 87 }