blob: c044dd4c67aa29412cd14ca16f9a5105eda5bc74 [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 (
"bufio"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"gwt.googlesource.com/buildglue.git/creds"
)
// Return a list of git references matched by the Gerrit search query q.
//
// See https://gerrit-review.googlesource.com/Documentation/user-search.html
// for documentation about Gerrit search syntax.
func Query(q string) ([]string, error) {
url := fmt.Sprintf("https://gwt-review.googlesource.com/a/changes/?o=CURRENT_REVISION&q=%s", url.QueryEscape(q))
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(creds.GerritBasicAuth())
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
return ParseRefs(res.Body)
}
// ParseRefs reads a list of Gerrit ChangeInfo entries from reader and returns
// the refs for the current revisions.
func ParseRefs(reader io.Reader) ([]string, error) {
r := bufio.NewReader(reader)
// First line of input is the XSSI guard (")]}'").
if _, err := r.ReadSlice('\n'); err != nil {
return nil, err
}
var changes []struct {
Current_revision string
Revisions map[string]struct {
Fetch struct {
Http struct {
Ref string
}
}
}
}
if err := json.NewDecoder(r).Decode(&changes); err != nil {
return nil, err
}
var res []string
for _, change := range changes {
res = append(res, change.Revisions[change.Current_revision].Fetch.Http.Ref)
}
return res, nil
}