github.com/sona-tar/ghs@v0.0.0-20170415134710-bed1b2953748/search.go (about) 1 package main 2 3 import ( 4 "errors" 5 "net/http" 6 "net/url" 7 8 "github.com/google/go-github/github" 9 "golang.org/x/oauth2" 10 "context" 11 ) 12 13 type Search struct { 14 client *github.Client 15 option *SearchOpt 16 } 17 18 type SearchOpt struct { 19 sort string 20 order string 21 query string 22 max int 23 perPage int 24 baseURL *url.URL 25 token string 26 } 27 28 func NewSearch(c context.Context,opt *SearchOpt) *Search { 29 var tc *http.Client 30 31 if opt.token != "" { 32 ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: opt.token}) 33 tc = oauth2.NewClient(c, ts) 34 } 35 36 cli := github.NewClient(tc) 37 38 if opt.baseURL != nil { 39 cli.BaseURL = opt.baseURL 40 } 41 42 return &Search{client: cli, option: opt} 43 } 44 45 func repoSearch(c context.Context,client *github.Client, page int, opt *SearchOpt) (*github.RepositoriesSearchResult, *github.Response, error) { 46 opts := &github.SearchOptions{ 47 Sort: opt.sort, 48 Order: opt.order, 49 TextMatch: false, 50 ListOptions: github.ListOptions{PerPage: opt.perPage, Page: page}, 51 } 52 ret, resp, err := client.Search.Repositories(c,opt.query, opts) 53 return ret, resp, err 54 } 55 56 func (s *Search) First(c context.Context) (repos []github.Repository, lastPage int, maxItem int, err error) { 57 ret, resp, err := repoSearch(c,s.client, 1, s.option) 58 if err != nil { 59 Debug("error repoSearch()\n") 60 return nil, 0, 0, err 61 } 62 if len(ret.Repositories) == 0 { 63 return nil, 0, 0, errors.New("Repository not found") 64 } 65 66 Debug("main thread repos length %d\n", len(ret.Repositories)) 67 68 max := s.option.max 69 Debug("Total = %d\n", *ret.Total) 70 Debug("s.option.max = %d\n", s.option.max) 71 if *ret.Total < max { 72 max = *ret.Total 73 } 74 75 last := ((max - 1) / s.option.perPage) + 1 76 Debug("resp.LastPage = %d\n", resp.LastPage) 77 Debug("last = %d\n", last) 78 if resp.LastPage < last { 79 last = resp.LastPage 80 } 81 82 return ret.Repositories, last, max, nil 83 } 84 85 func (s *Search) Exec(c context.Context,page int) (repos []github.Repository, err error) { 86 Debug("Page%d go func search start\n", page) 87 88 Debug("Page%d query : %s\n", page, s.option.query) 89 ret, _, err := repoSearch(c, s.client, page, s.option) 90 if err != nil { 91 return nil, err 92 } 93 Debug("Page%d go func search result length %d\n", page, len(ret.Repositories)) 94 Debug("Page%d go func search end\n", page) 95 96 return ret.Repositories, nil 97 }