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