Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(378)

Side by Side Diff: common/api/gitiles/gitiles.go

Issue 2983513002: gitiles.Log: implement paging. (Closed)
Patch Set: review Created 3 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | common/api/gitiles/gitiles_test.go » ('j') | common/api/gitiles/gitiles_test.go » ('J')
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2016 The LUCI Authors. 1 // Copyright 2016 The LUCI Authors.
2 // 2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License. 4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at 5 // You may obtain a copy of the License at
6 // 6 //
7 // http://www.apache.org/licenses/LICENSE-2.0 7 // http://www.apache.org/licenses/LICENSE-2.0
8 // 8 //
9 // Unless required by applicable law or agreed to in writing, software 9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, 10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and 12 // See the License for the specific language governing permissions and
13 // limitations under the License. 13 // limitations under the License.
14 14
15 package gitiles 15 package gitiles
16 16
17 // TODO(tandrii): add tests. 17 // TODO(tandrii): add tests.
18 18
19 import ( 19 import (
20 "encoding/json" 20 "encoding/json"
21 "fmt" 21 "fmt"
22 "net/http" 22 "net/http"
23 "net/url" 23 "net/url"
24 "reflect"
24 "strings" 25 "strings"
25 "time" 26 "time"
26 27
28 "github.com/luci/luci-go/common/errors"
29 "github.com/luci/luci-go/common/retry/transient"
27 "github.com/luci/luci-go/server/auth" 30 "github.com/luci/luci-go/server/auth"
28 "golang.org/x/net/context" 31 "golang.org/x/net/context"
32 "golang.org/x/net/context/ctxhttp"
29 ) 33 )
30 34
31 // User is the author or the committer returned from gitiles. 35 // User is the author or the committer returned from gitiles.
32 type User struct { 36 type User struct {
33 Name string `json:"name"` 37 Name string `json:"name"`
34 Email string `json:"email"` 38 Email string `json:"email"`
35 Time string `json:"time"` 39 Time string `json:"time"`
36 } 40 }
37 41
38 // GetTime returns the Time field as real data! 42 // GetTime returns the Time field as real data!
39 func (u *User) GetTime() (time.Time, error) { 43 func (u *User) GetTime() (time.Time, error) {
40 return time.Parse(time.ANSIC, u.Time) 44 return time.Parse(time.ANSIC, u.Time)
41 } 45 }
42 46
43 // Commit is the information of a commit returned from gitiles. 47 // Commit is the information of a commit returned from gitiles.
44 type Commit struct { 48 type Commit struct {
45 Commit string `json:"commit"` 49 Commit string `json:"commit"`
46 Tree string `json:"tree"` 50 Tree string `json:"tree"`
47 Parents []string `json:"parents"` 51 Parents []string `json:"parents"`
48 Author User `json:"author"` 52 Author User `json:"author"`
49 Committer User `json:"committer"` 53 Committer User `json:"committer"`
50 Message string `json:"message"` 54 Message string `json:"message"`
51 } 55 }
52 56
53 // LogResponse is the JSON response from querying gitiles for a log request. 57 // ValidateRepoURL validates gitiles repository URL for use in this package.
54 type LogResponse struct { 58 func ValidateRepoURL(repoURL string) error {
55 » Log []Commit `json:"log"` 59 » _, err := NormalizeRepoURL(repoURL)
56 » Next string `json:"next"` 60 » return err
57 } 61 }
58 62
59 // fixURL validates and normalizes a repoURL and treeish, and returns the 63 // NormalizeRepoURL returns canonical for gitiles URL of the repo including "a/" path prefix.
60 // log JSON gitiles URL. 64 // error is returned if validation fails.
61 func fixURL(repoURL, treeish string) (string, error) { 65 func NormalizeRepoURL(repoURL string) (string, error) {
62 u, err := url.Parse(repoURL) 66 u, err := url.Parse(repoURL)
63 if err != nil { 67 if err != nil {
64 return "", err 68 return "", err
65 } 69 }
66 if u.Scheme != "https" { 70 if u.Scheme != "https" {
67 return "", fmt.Errorf("%s should start with https://", repoURL) 71 return "", fmt.Errorf("%s should start with https://", repoURL)
68 } 72 }
69 if !strings.HasSuffix(u.Host, ".googlesource.com") { 73 if !strings.HasSuffix(u.Host, ".googlesource.com") {
70 » » return "", fmt.Errorf("Only .googlesource.com repos supported") 74 » » return "", fmt.Errorf("only .googlesource.com repos supported")
71 } 75 }
72 » // Use the authenticated URL 76 » if u.Path == "" || u.Path == "/" {
73 » u.Path = "a/" + u.Path 77 » » return "", fmt.Errorf("path to repo is empty")
74 » URL := fmt.Sprintf("%s/+log/%s?format=JSON", u.String(), treeish) 78 » }
75 » return URL, nil 79 » if !strings.HasPrefix(u.Path, "/") {
80 » » u.Path = "/" + u.Path
81 » }
82 » if !strings.HasPrefix(u.Path, "/a/") {
83 » » // Use the authenticated URL
84 » » u.Path = "/a" + u.Path
85 » }
86
87 » u.Path = strings.TrimRight(u.Path, "/")
88 » u.Path = strings.TrimSuffix(u.Path, ".git")
89 » return u.String(), nil
76 } 90 }
77 91
78 // Log returns a list of commits based on a repo and treeish (usually 92 // Log returns a list of commits based on a repo and treeish.
79 // a branch). This should be equivilent of a "git log <treeish>" call in 93 // This should be equivalent of a "git log <treeish>" call in that repository.
80 // that repository. 94 //
95 // treeish can be either:
96 // (1) a git revision as 40-char string or its prefix so long as its unique in repo.
97 // (2) a ref such as "refs/heads/branch" or just "branch"
98 // (3) a ref defined as n-th parent of R in the form "R~n".
99 // For example, "master~2" or "deadbeef~1".
100 // (4) a range between two revisions in the form "CHILD..PREDECESSOR", where
101 // CHILD and PREDECESSOR are each specified in either (1), (2) or (3)
102 // formats listed above.
103 // For example, "foo..ba1", "master..refs/branch-heads/1.2.3",
104 // or even "master~5..master~9".
105 //
106 //
107 // If the returned log has a commit with 2+ parents, the order of commits after
108 // that is whatever Gitiles returns, which currently means ordered
109 // by topological sort first, and then by commit timestamps.
110 //
111 // This means that if Log(C) contains commit A, Log(A) will not necessarily retu rn
112 // a subsequence of Log(C) (though definitely a subset). For example,
113 //
114 //» » common... -> base ------> A ----> C
115 // » » » » » » » » » » \ /
116 // » » » » » » » » » --> B ------
117 //
118 //» » ----commit timestamp increases--->
119 //
120 // Log(A) = [A, base, common...]
121 // Log(B) = [B, base, common...]
122 // Log(C) = [C, A, B, base, common...]
123 //
81 func Log(c context.Context, repoURL, treeish string, limit int) ([]Commit, error ) { 124 func Log(c context.Context, repoURL, treeish string, limit int) ([]Commit, error ) {
82 » // TODO(hinoka): Respect the limit. 125 » if limit < 1 {
83 » URL, err := fixURL(repoURL, treeish) 126 » » return nil, fmt.Errorf("limit must be at least 1, but %d provide d", limit)
127 » }
128 » logURL, err := NormalizeRepoURL(repoURL)
84 if err != nil { 129 if err != nil {
85 return nil, err 130 return nil, err
86 } 131 }
132
133 logURL = fmt.Sprintf("%s/+log/%s?format=JSON", logURL, url.PathEscape(tr eeish))
87 t, err := auth.GetRPCTransport(c, auth.NoAuth) 134 t, err := auth.GetRPCTransport(c, auth.NoAuth)
88 if err != nil { 135 if err != nil {
89 return nil, err 136 return nil, err
90 } 137 }
91 client := http.Client{Transport: t} 138 client := http.Client{Transport: t}
92 » r, err := client.Get(URL) 139 » resp := &logResponse{}
93 » if err != nil { 140 » if err = get(c, &client, logURL, resp); err != nil {
94 return nil, err 141 return nil, err
95 } 142 }
96 » if r.StatusCode != 200 { 143 » result := resp.Log
97 » » return nil, fmt.Errorf("Failed to fetch %s, status code %d", URL , r.StatusCode) 144 » for {
145 » » if resp.Next == "" || len(result) >= limit {
146 » » » if len(result) > limit {
147 » » » » result = result[0:limit]
Vadim Sh. 2017/07/19 23:02:30 nit: just result[:limit]
tandrii(chromium) 2017/07/20 16:19:15 Done.
148 » » » }
149 » » » return result, nil
150 » » }
151 » » nextURL := logURL + "&s=" + resp.Next
152 » » resp = &logResponse{}
153 » » if err = get(c, &client, nextURL, resp); err != nil {
154 » » » return nil, err
155 » » }
156 » » result = append(result, resp.Log...)
157 » }
158 }
159
160 ////////////////////////////////////////////////////////////////////////////////
161
162 // logResponse is the JSON response from querying gitiles for a log request.
163 type logResponse struct {
164 » Log []Commit `json:"log"`
165 » Next string `json:"next"`
166 }
167
168 func get(c context.Context, client *http.Client, URL string, result interface{}) error {
169 » r, err := ctxhttp.Get(c, client, URL)
170 » if err != nil {
171 » » return err
Vadim Sh. 2017/07/19 23:02:30 this is always transient error too non-transient
98 } 172 }
99 defer r.Body.Close() 173 defer r.Body.Close()
174 if r.StatusCode != 200 {
175 err = fmt.Errorf("failed to fetch %s, status code %d", URL, r.St atusCode)
176 if r.StatusCode >= 500 {
177 // TODO(tandrii): consider retrying.
178 err = transient.Tag.Apply(err)
179 }
180 return err
181 }
100 // Strip out the jsonp header, which is ")]}'" 182 // Strip out the jsonp header, which is ")]}'"
101 trash := make([]byte, 4) 183 trash := make([]byte, 4)
102 » r.Body.Read(trash) // Read the jsonp header 184 » if c, err := r.Body.Read(trash); err != nil || c != 4 || ")]}'" != strin g(trash) {
103 » commits := LogResponse{} 185 » » return errors.Annotate(err, "unexpected response from Gitiles"). Err()
Vadim Sh. 2017/07/19 23:02:30 this will return nil if trash happened to be somet
tandrii(chromium) 2017/07/20 16:19:15 Oops, fixed.
104 » if err := json.NewDecoder(r.Body).Decode(&commits); err != nil {
105 » » return nil, err
106 } 186 }
107 » // TODO(hinoka): If there is a page and we have gotten less than the lim it, 187 » if err := json.NewDecoder(r.Body).Decode(result); err != nil {
108 » // keep making requests for the next page until we have enough commits. 188 » » return errors.Annotate(err, "failed to decode Gitiles response i nto %v", reflect.TypeOf(result)).Err()
109 » return commits.Log, nil 189 » }
190 » return nil
110 } 191 }
OLDNEW
« no previous file with comments | « no previous file | common/api/gitiles/gitiles_test.go » ('j') | common/api/gitiles/gitiles_test.go » ('J')

Powered by Google App Engine
This is Rietveld 408576698