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

Side by Side Diff: tools/bug_chomper/src/issue_tracker/issue_tracker.go

Issue 274693002: BugChomper utility - rewrite in Go (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Use securecookie, add --public flag Created 6 years, 7 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
OLDNEW
(Empty)
1 // Copyright (c) 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 /*
6 Utilities for interacting with the GoogleCode issue tracker.
7
8 Example usage:
9 issueTracker := issue_tracker.MakeIssueTraker(myOAuthConfigFile)
10 authURL := issueTracker.MakeAuthRequestURL()
11 // Visit the authURL to obtain an authorization code.
12 issueTracker.UpgradeCode(code)
13 // Now issueTracker can be used to retrieve and edit issues.
14 */
15 package issue_tracker
16
17 import (
18 "bytes"
19 "code.google.com/p/goauth2/oauth"
20 "encoding/json"
21 "fmt"
22 "io/ioutil"
23 "net/http"
24 "net/url"
25 "strconv"
26 "strings"
27 )
28
29 // BugPriorities are the possible values for "Priority-*" labels for issues.
30 var BugPriorities = []string{"Critical", "High", "Medium", "Low", "Never"}
31
32 var apiScope = []string{
33 "https://www.googleapis.com/auth/projecthosting",
34 "https://www.googleapis.com/auth/userinfo.email",
35 }
36
37 const issueApiURL = "https://www.googleapis.com/projecthosting/v2/projects/"
38 const issueURL = "https://code.google.com/p/skia/issues/detail?id="
39 const personApiURL = "https://www.googleapis.com/userinfo/v2/me"
40
41 // Enum for determining whether a label has been added, removed, or is
42 // unchanged.
43 const (
44 labelAdded = iota
45 labelRemoved
46 labelUnchanged
47 )
48
49 // loadOAuthConfig reads the OAuth given config file path and returns an
50 // appropriate oauth.Config.
51 func loadOAuthConfig(oauthConfigFile string) (*oauth.Config, error) {
52 errFmt := "failed to read OAuth config file: %s"
53 fileContents, err := ioutil.ReadFile(oauthConfigFile)
54 if err != nil {
55 return nil, fmt.Errorf(errFmt, err)
56 }
57 var decodedJson map[string]struct {
58 AuthURL string `json:"auth_uri"`
59 ClientId string `json:"client_id"`
60 ClientSecret string `json:"client_secret"`
61 TokenURL string `json:"token_uri"`
62 }
63 if err := json.Unmarshal(fileContents, &decodedJson); err != nil {
64 return nil, fmt.Errorf(errFmt, err)
65 }
66 config, ok := decodedJson["web"]
67 if !ok {
68 return nil, fmt.Errorf(errFmt, err)
69 }
70 return &oauth.Config{
71 ClientId: config.ClientId,
72 ClientSecret: config.ClientSecret,
73 Scope: strings.Join(apiScope, " "),
74 AuthURL: config.AuthURL,
75 TokenURL: config.TokenURL,
76 }, nil
77 }
78
79 // Issue contains information about an issue.
80 type Issue struct {
81 Id int `json:"id"`
82 Project string `json:"projectId"`
83 Title string `json:"title"`
84 Labels []string `json:"labels"`
85 }
86
87 // URL returns the URL of a given issue.
88 func (i Issue) URL() string {
89 return issueURL + strconv.Itoa(i.Id)
90 }
91
92 // IssueList represents a list of issues from the IssueTracker.
93 type IssueList struct {
94 TotalResults int `json:"totalResults"`
95 Items []*Issue `json:"items"`
96 }
97
98 // IssueTracker is the primary point of contact with the issue tracker,
99 // providing methods for authenticating to and interacting with it.
100 type IssueTracker struct {
101 OAuthConfig *oauth.Config
102 OAuthTransport *oauth.Transport
103 }
104
105 // MakeIssueTracker creates and returns an IssueTracker with authentication
106 // configuration from the given authConfigFile.
107 func MakeIssueTracker(
108 authConfigFile string, redirectURL string) (*IssueTracker, error) {
109 oauthConfig, err := loadOAuthConfig(authConfigFile)
110 if err != nil {
111 return nil, fmt.Errorf(
112 "failed to create IssueTracker: %s", err)
113 }
114 oauthConfig.RedirectURL = redirectURL
115 return &IssueTracker{
116 OAuthConfig: oauthConfig,
117 OAuthTransport: &oauth.Transport{Config: oauthConfig},
118 }, nil
119 }
120
121 // MakeAuthRequestURL returns an authentication request URL which can be used
122 // to obtain an authorization code via user sign-in.
123 func (it IssueTracker) MakeAuthRequestURL() string {
124 // NOTE: Need to add XSRF protection if we ever want to run this on a pu blic
125 // server.
126 return it.OAuthConfig.AuthCodeURL(it.OAuthConfig.RedirectURL)
127 }
128
129 // IsAuthenticated determines whether the IssueTracker has sufficient
130 // permissions to retrieve and edit Issues.
131 func (it IssueTracker) IsAuthenticated() bool {
132 return it.OAuthTransport.Token != nil
133 }
134
135 // UpgradeCode exchanges the single-use authorization code, obtained by
136 // following the URL obtained from IssueTracker.MakeAuthRequestURL, for a
137 // multi-use, session token. This is required before IssueTracker can retrieve
138 // and edit issues.
139 func (it *IssueTracker) UpgradeCode(code string) error {
140 token, err := it.OAuthTransport.Exchange(code)
141 if err == nil {
142 it.OAuthTransport.Token = token
143 return nil
144 } else {
145 return fmt.Errorf(
146 "failed to exchange single-user auth code: %s", err)
147 }
148 }
149
150 // GetLoggedInUser retrieves the email address of the authenticated user.
151 func (it IssueTracker) GetLoggedInUser() (string, error) {
152 errFmt := "error retrieving user email: %s"
153 if !it.IsAuthenticated() {
154 return "", fmt.Errorf(errFmt, "User is not authenticated!")
155 }
156 resp, err := it.OAuthTransport.Client().Get(personApiURL)
157 if err != nil {
158 return "", fmt.Errorf(errFmt, err)
159 }
160 defer resp.Body.Close()
161 body, _ := ioutil.ReadAll(resp.Body)
162 if resp.StatusCode != http.StatusOK {
163 return "", fmt.Errorf(errFmt, fmt.Sprintf(
164 "user data API returned code %d: %v", resp.StatusCode, s tring(body)))
165 }
166 userInfo := struct {
167 Email string `json:"email"`
168 }{}
169 if err := json.Unmarshal(body, &userInfo); err != nil {
170 return "", fmt.Errorf(errFmt, err)
171 }
172 return userInfo.Email, nil
173 }
174
175 // GetBug retrieves the Issue with the given ID from the IssueTracker.
176 func (it IssueTracker) GetBug(project string, id int) (*Issue, error) {
177 errFmt := fmt.Sprintf("error retrieving issue %d: %s", id, "%s")
178 if !it.IsAuthenticated() {
179 return nil, fmt.Errorf(errFmt, "user is not authenticated!")
180 }
181 requestURL := issueApiURL + project + "/issues/" + strconv.Itoa(id)
182 resp, err := it.OAuthTransport.Client().Get(requestURL)
183 if err != nil {
184 return nil, fmt.Errorf(errFmt, err)
185 }
186 defer resp.Body.Close()
187 body, _ := ioutil.ReadAll(resp.Body)
188 if resp.StatusCode != http.StatusOK {
189 return nil, fmt.Errorf(errFmt, fmt.Sprintf(
190 "issue tracker returned code %d:%v", resp.StatusCode, st ring(body)))
191 }
192 var issue Issue
193 if err := json.Unmarshal(body, &issue); err != nil {
194 return nil, fmt.Errorf(errFmt, err)
195 }
196 return &issue, nil
197 }
198
199 // GetBugs retrieves all Issues with the given owner from the IssueTracker,
200 // returning an IssueList.
201 func (it IssueTracker) GetBugs(
202 project string, owner string) (*IssueList, error) {
203 errFmt := "error retrieving issues: %s"
204 if !it.IsAuthenticated() {
205 return nil, fmt.Errorf(errFmt, "user is not authenticated!")
206 }
207 params := map[string]string{
208 "owner": url.QueryEscape(owner),
209 "can": "open",
210 "maxResults": "9999",
211 }
212 requestURL := issueApiURL + project + "/issues?"
213 first := true
214 for k, v := range params {
215 if first {
216 first = false
217 } else {
218 requestURL += "&"
219 }
220 requestURL += k + "=" + v
221 }
222 resp, err := it.OAuthTransport.Client().Get(requestURL)
223 if err != nil {
224 return nil, fmt.Errorf(errFmt, err)
225 }
226 defer resp.Body.Close()
227 body, _ := ioutil.ReadAll(resp.Body)
228 if resp.StatusCode != http.StatusOK {
229 return nil, fmt.Errorf(errFmt, fmt.Sprintf(
230 "issue tracker returned code %d:%v", resp.StatusCode, st ring(body)))
231 }
232
233 var bugList IssueList
234 if err := json.Unmarshal(body, &bugList); err != nil {
235 return nil, fmt.Errorf(errFmt, err)
236 }
237 return &bugList, nil
238 }
239
240 // SubmitIssueChanges creates a comment on the given Issue which modifies it
241 // according to the contents of the passed-in Issue struct.
242 func (it IssueTracker) SubmitIssueChanges(
243 issue *Issue, comment string) error {
244 errFmt := "Error updating issue " + strconv.Itoa(issue.Id) + ": %s"
245 if !it.IsAuthenticated() {
246 return fmt.Errorf(errFmt, "user is not authenticated!")
247 }
248 oldIssue, err := it.GetBug(issue.Project, issue.Id)
249 if err != nil {
250 return fmt.Errorf(errFmt, err)
251 }
252 postData := struct {
253 Content string `json:"content"`
254 Updates struct {
255 Title *string `json:"summary"`
256 Labels []string `json:"labels"`
257 } `json:"updates"`
258 }{
259 Content: comment,
260 }
261 if issue.Title != oldIssue.Title {
262 postData.Updates.Title = &issue.Title
263 }
264 // TODO(borenet): Add other issue attributes, eg. Owner.
265 labels := make(map[string]int)
266 for _, label := range issue.Labels {
267 labels[label] = labelAdded
268 }
269 for _, label := range oldIssue.Labels {
270 if _, ok := labels[label]; ok {
271 labels[label] = labelUnchanged
272 } else {
273 labels[label] = labelRemoved
274 }
275 }
276 labelChanges := make([]string, 0)
277 for labelName, present := range labels {
278 if present == labelRemoved {
279 labelChanges = append(labelChanges, "-"+labelName)
280 } else if present == labelAdded {
281 labelChanges = append(labelChanges, labelName)
282 }
283 }
284 if len(labelChanges) > 0 {
285 postData.Updates.Labels = labelChanges
286 }
287
288 postBytes, err := json.Marshal(&postData)
289 if err != nil {
290 return fmt.Errorf(errFmt, err)
291 }
292 requestURL := issueApiURL + issue.Project + "/issues/" +
293 strconv.Itoa(issue.Id) + "/comments"
294 resp, err := it.OAuthTransport.Client().Post(
295 requestURL, "application/json", bytes.NewReader(postBytes))
296 if err != nil {
297 return fmt.Errorf(errFmt, err)
298 }
299 defer resp.Body.Close()
300 body, _ := ioutil.ReadAll(resp.Body)
301 if resp.StatusCode != http.StatusOK {
302 return fmt.Errorf(errFmt, fmt.Sprintf(
303 "Issue tracker returned code %d:%v", resp.StatusCode, st ring(body)))
304 }
305 return nil
306 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698