search.go 2.4 KB

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