Chromium Code Reviews| OLD | NEW |
|---|---|
| 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 "strings" | 24 "strings" |
| 25 "time" | 25 "time" |
| 26 | 26 |
| 27 » "github.com/luci/luci-go/server/auth" | 27 » "github.com/luci/luci-go/common/errors" |
| 28 » "github.com/luci/luci-go/common/retry/transient" | |
| 28 "golang.org/x/net/context" | 29 "golang.org/x/net/context" |
| 30 "golang.org/x/net/context/ctxhttp" | |
| 29 ) | 31 ) |
| 30 | 32 |
| 31 // User is the author or the committer returned from gitiles. | 33 // User is the author or the committer returned from gitiles. |
| 32 type User struct { | 34 type User struct { |
| 33 Name string `json:"name"` | 35 Name string `json:"name"` |
| 34 Email string `json:"email"` | 36 Email string `json:"email"` |
| 35 Time string `json:"time"` | 37 Time string `json:"time"` |
| 36 } | 38 } |
| 37 | 39 |
| 38 // GetTime returns the Time field as real data! | 40 // GetTime returns the Time field as real data! |
| 39 func (u *User) GetTime() (time.Time, error) { | 41 func (u *User) GetTime() (time.Time, error) { |
| 40 return time.Parse(time.ANSIC, u.Time) | 42 return time.Parse(time.ANSIC, u.Time) |
| 41 } | 43 } |
| 42 | 44 |
| 43 // Commit is the information of a commit returned from gitiles. | 45 // Commit is the information of a commit returned from gitiles. |
| 44 type Commit struct { | 46 type Commit struct { |
| 45 Commit string `json:"commit"` | 47 Commit string `json:"commit"` |
| 46 Tree string `json:"tree"` | 48 Tree string `json:"tree"` |
| 47 Parents []string `json:"parents"` | 49 Parents []string `json:"parents"` |
| 48 Author User `json:"author"` | 50 Author User `json:"author"` |
| 49 Committer User `json:"committer"` | 51 Committer User `json:"committer"` |
| 50 Message string `json:"message"` | 52 Message string `json:"message"` |
| 51 } | 53 } |
| 52 | 54 |
| 53 // LogResponse is the JSON response from querying gitiles for a log request. | 55 // ValidateRepoURL validates gitiles repository URL for use in this package. |
| 54 type LogResponse struct { | 56 func ValidateRepoURL(repoURL string) error { |
| 55 » Log []Commit `json:"log"` | 57 » _, err := NormalizeRepoURL(repoURL) |
| 56 » Next string `json:"next"` | 58 » return err |
| 57 } | 59 } |
| 58 | 60 |
| 59 // fixURL validates and normalizes a repoURL and treeish, and returns the | 61 // NormalizeRepoURL returns canonical for gitiles URL of the repo including "a/" path prefix. |
| 60 // log JSON gitiles URL. | 62 // error is returned if validation fails. |
| 61 func fixURL(repoURL, treeish string) (string, error) { | 63 func NormalizeRepoURL(repoURL string) (string, error) { |
| 62 u, err := url.Parse(repoURL) | 64 u, err := url.Parse(repoURL) |
| 63 if err != nil { | 65 if err != nil { |
| 64 return "", err | 66 return "", err |
| 65 } | 67 } |
| 66 if u.Scheme != "https" { | 68 if u.Scheme != "https" { |
| 67 return "", fmt.Errorf("%s should start with https://", repoURL) | 69 return "", fmt.Errorf("%s should start with https://", repoURL) |
| 68 } | 70 } |
| 69 if !strings.HasSuffix(u.Host, ".googlesource.com") { | 71 if !strings.HasSuffix(u.Host, ".googlesource.com") { |
| 70 » » return "", fmt.Errorf("Only .googlesource.com repos supported") | 72 » » return "", errors.New("only .googlesource.com repos supported") |
| 71 } | 73 } |
| 72 » // Use the authenticated URL | 74 » if u.Fragment != "" { |
| 73 » u.Path = "a/" + u.Path | 75 » » return "", errors.New("no fragments allowed in repoURL") |
| 74 » URL := fmt.Sprintf("%s/+log/%s?format=JSON", u.String(), treeish) | 76 » } |
| 75 » return URL, nil | 77 » if u.Path == "" || u.Path == "/" { |
| 78 » » return "", errors.New("path to repo is empty") | |
| 79 » } | |
| 80 » if !strings.HasPrefix(u.Path, "/") { | |
| 81 » » u.Path = "/" + u.Path | |
| 82 » } | |
| 83 » if !strings.HasPrefix(u.Path, "/a/") { | |
| 84 » » // Use the authenticated URL | |
| 85 » » u.Path = "/a" + u.Path | |
| 86 » } | |
| 87 | |
| 88 » u.Path = strings.TrimRight(u.Path, "/") | |
| 89 » u.Path = strings.TrimSuffix(u.Path, ".git") | |
| 90 » return u.String(), nil | |
| 76 } | 91 } |
| 77 | 92 |
| 78 // Log returns a list of commits based on a repo and treeish (usually | 93 // New returns new gitiles client bound to a specific repository. |
| 79 // a branch). This should be equivilent of a "git log <treeish>" call in | 94 // Returns errors if repoURL is not valid. |
| 80 // that repository. | 95 func New(c *http.Client, repoURL string) (*Client, error) { |
|
Vadim Sh.
2017/07/20 16:48:12
I'm not a fan of such ambiguous constructors. How
tandrii(chromium)
2017/07/20 19:04:10
Done!
| |
| 81 func Log(c context.Context, repoURL, treeish string, limit int) ([]Commit, error ) { | 96 » u, err := NormalizeRepoURL(repoURL) |
| 82 » // TODO(hinoka): Respect the limit. | |
| 83 » URL, err := fixURL(repoURL, treeish) | |
| 84 if err != nil { | 97 if err != nil { |
| 85 return nil, err | 98 return nil, err |
| 86 } | 99 } |
| 87 » t, err := auth.GetRPCTransport(c, auth.AsSelf, auth.WithScopes( | 100 » return &Client{c, u}, nil |
| 88 » » "https://www.googleapis.com/auth/gerritcodereview", | 101 } |
| 89 » )) | 102 |
| 90 » if err != nil { | 103 // Client is Gitiles client bound to a specific Git repository. |
| 104 type Client struct { | |
| 105 » Client *http.Client | |
| 106 » RepoURL string // Normalized RepoURL | |
| 107 } | |
| 108 | |
| 109 // Log returns a list of commits based on a repo and treeish. | |
| 110 // This should be equivalent of a "git log <treeish>" call in that repository. | |
| 111 // | |
| 112 // treeish can be either: | |
| 113 // (1) a git revision as 40-char string or its prefix so long as its unique in repo. | |
| 114 // (2) a ref such as "refs/heads/branch" or just "branch" | |
| 115 // (3) a ref defined as n-th parent of R in the form "R~n". | |
| 116 // For example, "master~2" or "deadbeef~1". | |
| 117 // (4) a range between two revisions in the form "CHILD..PREDECESSOR", where | |
| 118 // CHILD and PREDECESSOR are each specified in either (1), (2) or (3) | |
| 119 // formats listed above. | |
| 120 // For example, "foo..ba1", "master..refs/branch-heads/1.2.3", | |
| 121 // or even "master~5..master~9". | |
| 122 // | |
| 123 // | |
| 124 // If the returned log has a commit with 2+ parents, the order of commits after | |
| 125 // that is whatever Gitiles returns, which currently means ordered | |
| 126 // by topological sort first, and then by commit timestamps. | |
| 127 // | |
| 128 // This means that if Log(C) contains commit A, Log(A) will not necessarily retu rn | |
| 129 // a subsequence of Log(C) (though definitely a subset). For example, | |
| 130 // | |
| 131 // common... -> base ------> A ----> C | |
| 132 // \ / | |
| 133 // --> B ------ | |
| 134 // | |
| 135 // ----commit timestamp increases---> | |
| 136 // | |
| 137 // Log(A) = [A, base, common...] | |
| 138 // Log(B) = [B, base, common...] | |
| 139 // Log(C) = [C, A, B, base, common...] | |
| 140 // | |
| 141 func (c *Client) Log(ctx context.Context, treeish string, limit int) ([]Commit, error) { | |
| 142 » if limit < 1 { | |
| 143 » » return nil, fmt.Errorf("limit must be at least 1, but %d provide d", limit) | |
| 144 » } | |
| 145 » subPath := fmt.Sprintf("+log/%s?format=JSON", url.PathEscape(treeish)) | |
| 146 » resp := &logResponse{} | |
| 147 » if err := c.get(ctx, subPath, resp); err != nil { | |
| 91 return nil, err | 148 return nil, err |
| 92 } | 149 } |
| 93 » client := http.Client{Transport: t} | 150 » result := resp.Log |
| 94 » r, err := client.Get(URL) | 151 » for { |
| 152 » » if resp.Next == "" || len(result) >= limit { | |
| 153 » » » if len(result) > limit { | |
| 154 » » » » result = result[:limit] | |
| 155 » » » } | |
| 156 » » » return result, nil | |
| 157 » » } | |
| 158 » » nextPath := subPath + "&s=" + resp.Next | |
| 159 » » resp = &logResponse{} | |
| 160 » » if err := c.get(ctx, nextPath, resp); err != nil { | |
| 161 » » » return nil, err | |
| 162 » » } | |
| 163 » » result = append(result, resp.Log...) | |
| 164 » } | |
| 165 } | |
| 166 | |
| 167 //////////////////////////////////////////////////////////////////////////////// | |
| 168 | |
| 169 // logResponse is the JSON response from querying gitiles for a log request. | |
| 170 type logResponse struct { | |
| 171 » Log []Commit `json:"log"` | |
| 172 » Next string `json:"next"` | |
| 173 } | |
| 174 | |
| 175 func (c *Client) get(ctx context.Context, subPath string, result interface{}) er ror { | |
| 176 » URL := fmt.Sprintf("%s/%s", c.RepoURL, subPath) | |
| 177 » r, err := ctxhttp.Get(ctx, c.Client, URL) | |
| 95 if err != nil { | 178 if err != nil { |
| 96 » » return nil, err | 179 » » return transient.Tag.Apply(err) |
| 97 » } | |
| 98 » if r.StatusCode != 200 { | |
| 99 » » return nil, fmt.Errorf("Failed to fetch %s, status code %d", URL , r.StatusCode) | |
| 100 } | 180 } |
| 101 defer r.Body.Close() | 181 defer r.Body.Close() |
| 182 if r.StatusCode != 200 { | |
| 183 err = fmt.Errorf("failed to fetch %s, status code %d", URL, r.St atusCode) | |
| 184 if r.StatusCode >= 500 { | |
| 185 // TODO(tandrii): consider retrying. | |
| 186 err = transient.Tag.Apply(err) | |
| 187 } | |
| 188 return err | |
| 189 } | |
| 102 // Strip out the jsonp header, which is ")]}'" | 190 // Strip out the jsonp header, which is ")]}'" |
| 103 trash := make([]byte, 4) | 191 trash := make([]byte, 4) |
| 104 » r.Body.Read(trash) // Read the jsonp header | 192 » cnt, err := r.Body.Read(trash) |
| 105 » commits := LogResponse{} | 193 » if err != nil { |
| 106 » if err := json.NewDecoder(r.Body).Decode(&commits); err != nil { | 194 » » return errors.Annotate(err, "unexpected response from Gitiles"). Err() |
| 107 » » return nil, err | |
| 108 } | 195 } |
| 109 » // TODO(hinoka): If there is a page and we have gotten less than the lim it, | 196 » if cnt != 4 || ")]}'" != string(trash) { |
| 110 » // keep making requests for the next page until we have enough commits. | 197 » » return errors.New("unexpected response from Gitiles") |
| 111 » return commits.Log, nil | 198 » } |
| 199 » if err = json.NewDecoder(r.Body).Decode(result); err != nil { | |
| 200 » » return errors.Annotate(err, "failed to decode Gitiles response i nto %T", result).Err() | |
| 201 » } | |
| 202 » return nil | |
| 112 } | 203 } |
| OLD | NEW |