search.go 2.4 KB

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