blob: 9f6a1b4bd7059494e63a98cbb30493898a30cde2 [file] [log] [blame]
/*
Copyright 2013 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gerrit
import (
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"strings"
"gwt.googlesource.com/buildglue.git/creds"
)
var (
dryRun = flag.Bool("dryrun", false, "write Gerrit reviews to stdout instead of posting them")
)
// Comment represents a single inline file comment.
type Comment struct {
Line int `json:"line,omitempty"`
Message string `json:"message,omitempty"`
}
// Labels represents the Code-Review and Verified labels associated with a review.
type Labels struct {
CodeReview int `json:"Code-Review,omitempty"`
Verified int `json:"Verified,omitempty"`
}
// Review represents a complete Gerrit review post.
type Review struct {
Message string `json:"message,omitempty"`
Labels *Labels `json:"labels,omitempty"`
Comments map[string][]Comment `json:"comments,omitempty"`
}
// Post publishes a review to a Gerrit review thread.
// If the -dryrun flag is set to true, then it instead prints the review to stdout.
func Post(ref string, review Review) error {
if *dryRun {
fmt.Printf("Review for %s:\n%#v\n", ref, review)
return nil
}
// ref is of the form "refs/changes/34/1234/7"; we want "1234" and "7".
path := strings.Split(ref, "/")
changeID, revisionID := path[3], path[4]
url := fmt.Sprintf("https://gwt-review.googlesource.com/a/changes/%s/revisions/%s/review", changeID, revisionID)
pr, pw := io.Pipe()
go func() {
pw.CloseWithError(json.NewEncoder(pw).Encode(review))
}()
req, err := http.NewRequest("POST", url, pr)
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json;charset=UTF-8")
req.SetBasicAuth(creds.GerritBasicAuth())
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
res.Body.Close()
return nil
}