| 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 // Client is Gitiles client. |
| 79 // a branch). This should be equivilent of a "git log <treeish>" call in | 94 type Client struct { |
| 80 // that repository. | 95 » Client *http.Client |
| 81 func Log(c context.Context, repoURL, treeish string, limit int) ([]Commit, error
) { | 96 |
| 82 » // TODO(hinoka): Respect the limit. | 97 » // Used for testing only. |
| 83 » URL, err := fixURL(repoURL, treeish) | 98 » mockRepoURL string |
| 99 } |
| 100 |
| 101 // Log returns a list of commits based on a repo and treeish. |
| 102 // This should be equivalent of a "git log <treeish>" call in that repository. |
| 103 // |
| 104 // treeish can be either: |
| 105 // (1) a git revision as 40-char string or its prefix so long as its unique in
repo. |
| 106 // (2) a ref such as "refs/heads/branch" or just "branch" |
| 107 // (3) a ref defined as n-th parent of R in the form "R~n". |
| 108 // For example, "master~2" or "deadbeef~1". |
| 109 // (4) a range between two revisions in the form "CHILD..PREDECESSOR", where |
| 110 // CHILD and PREDECESSOR are each specified in either (1), (2) or (3) |
| 111 // formats listed above. |
| 112 // For example, "foo..ba1", "master..refs/branch-heads/1.2.3", |
| 113 // or even "master~5..master~9". |
| 114 // |
| 115 // |
| 116 // If the returned log has a commit with 2+ parents, the order of commits after |
| 117 // that is whatever Gitiles returns, which currently means ordered |
| 118 // by topological sort first, and then by commit timestamps. |
| 119 // |
| 120 // This means that if Log(C) contains commit A, Log(A) will not necessarily retu
rn |
| 121 // a subsequence of Log(C) (though definitely a subset). For example, |
| 122 // |
| 123 // common... -> base ------> A ----> C |
| 124 // \ / |
| 125 // --> B ------ |
| 126 // |
| 127 // ----commit timestamp increases---> |
| 128 // |
| 129 // Log(A) = [A, base, common...] |
| 130 // Log(B) = [B, base, common...] |
| 131 // Log(C) = [C, A, B, base, common...] |
| 132 // |
| 133 func (c *Client) Log(ctx context.Context, repoURL, treeish string, limit int) ([
]Commit, error) { |
| 134 » repoURL, err := NormalizeRepoURL(repoURL) |
| 84 if err != nil { | 135 if err != nil { |
| 85 return nil, err | 136 return nil, err |
| 86 } | 137 } |
| 87 » t, err := auth.GetRPCTransport(c, auth.AsSelf, auth.WithScopes( | 138 » if limit < 1 { |
| 88 » » "https://www.googleapis.com/auth/gerritcodereview", | 139 » » return nil, fmt.Errorf("limit must be at least 1, but %d provide
d", limit) |
| 89 » )) | 140 » } |
| 90 » if err != nil { | 141 » subPath := fmt.Sprintf("+log/%s?format=JSON", url.PathEscape(treeish)) |
| 142 » resp := &logResponse{} |
| 143 » if err := c.get(ctx, repoURL, subPath, resp); err != nil { |
| 91 return nil, err | 144 return nil, err |
| 92 } | 145 } |
| 93 » client := http.Client{Transport: t} | 146 » result := resp.Log |
| 94 » r, err := client.Get(URL) | 147 » for { |
| 148 » » if resp.Next == "" || len(result) >= limit { |
| 149 » » » if len(result) > limit { |
| 150 » » » » result = result[:limit] |
| 151 » » » } |
| 152 » » » return result, nil |
| 153 » » } |
| 154 » » nextPath := subPath + "&s=" + resp.Next |
| 155 » » resp = &logResponse{} |
| 156 » » if err := c.get(ctx, repoURL, nextPath, resp); err != nil { |
| 157 » » » return nil, err |
| 158 » » } |
| 159 » » result = append(result, resp.Log...) |
| 160 » } |
| 161 } |
| 162 |
| 163 //////////////////////////////////////////////////////////////////////////////// |
| 164 |
| 165 // logResponse is the JSON response from querying gitiles for a log request. |
| 166 type logResponse struct { |
| 167 » Log []Commit `json:"log"` |
| 168 » Next string `json:"next"` |
| 169 } |
| 170 |
| 171 func (c *Client) get(ctx context.Context, repoURL, subPath string, result interf
ace{}) error { |
| 172 » URL := fmt.Sprintf("%s/%s", repoURL, subPath) |
| 173 » if c.mockRepoURL != "" { |
| 174 » » URL = fmt.Sprintf("%s/%s", c.mockRepoURL, subPath) |
| 175 » } |
| 176 » r, err := ctxhttp.Get(ctx, c.Client, URL) |
| 95 if err != nil { | 177 if err != nil { |
| 96 » » return nil, err | 178 » » 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 } | 179 } |
| 101 defer r.Body.Close() | 180 defer r.Body.Close() |
| 181 if r.StatusCode != 200 { |
| 182 err = fmt.Errorf("failed to fetch %s, status code %d", URL, r.St
atusCode) |
| 183 if r.StatusCode >= 500 { |
| 184 // TODO(tandrii): consider retrying. |
| 185 err = transient.Tag.Apply(err) |
| 186 } |
| 187 return err |
| 188 } |
| 102 // Strip out the jsonp header, which is ")]}'" | 189 // Strip out the jsonp header, which is ")]}'" |
| 103 trash := make([]byte, 4) | 190 trash := make([]byte, 4) |
| 104 » r.Body.Read(trash) // Read the jsonp header | 191 » cnt, err := r.Body.Read(trash) |
| 105 » commits := LogResponse{} | 192 » if err != nil { |
| 106 » if err := json.NewDecoder(r.Body).Decode(&commits); err != nil { | 193 » » return errors.Annotate(err, "unexpected response from Gitiles").
Err() |
| 107 » » return nil, err | |
| 108 } | 194 } |
| 109 » // TODO(hinoka): If there is a page and we have gotten less than the lim
it, | 195 » if cnt != 4 || ")]}'" != string(trash) { |
| 110 » // keep making requests for the next page until we have enough commits. | 196 » » return errors.New("unexpected response from Gitiles") |
| 111 » return commits.Log, nil | 197 » } |
| 198 » if err = json.NewDecoder(r.Body).Decode(result); err != nil { |
| 199 » » return errors.Annotate(err, "failed to decode Gitiles response i
nto %T", result).Err() |
| 200 » } |
| 201 » return nil |
| 112 } | 202 } |
| OLD | NEW |