Initial 'buildglue' project code dump

This brings the build tools used to integrate GWT's Gerrit and Jenkins
instances under proper code review and version control.

The main tool of interest is the 'presubmitter' command, which
periodically polls Gerrit for new unverified changes and runs various
presubmit checks on them.

Change-Id: Idd132bc62b1c0c91ab9ac16354fe5afecab5ff53
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/README b/README
new file mode 100644
index 0000000..e4eaa20
--- /dev/null
+++ b/README
@@ -0,0 +1,6 @@
+A collection of libraries and commands for GWT's automated build
+infrastructure.
+
+The main tool of interest is the "presubmitter" command, which
+periodically polls Gerrit for new unverified changes and runs various
+presubmit checks on them.
diff --git a/checkstyle/checkstyle.go b/checkstyle/checkstyle.go
new file mode 100644
index 0000000..fe3ac31
--- /dev/null
+++ b/checkstyle/checkstyle.go
@@ -0,0 +1,77 @@
+/*
+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 checkstyle provides helper methods for invoking checkstyle
+// against GWT's source code.
+package checkstyle
+
+import (
+	"encoding/xml"
+	"flag"
+	"io"
+	"log"
+	"os"
+	"os/exec"
+)
+
+var checkstylejar = flag.String("checkstylejar", "../tools/antlib/checkstyle-all-4.2.jar", "path to checkstyle jar")
+
+// Error represents a specific instance of an error reported by checkstyle.
+type Error struct {
+	Line     int    `xml:"line,attr"`
+	Severity string `xml:"severity,attr"`
+	Message  string `xml:"message,attr"`
+}
+
+// File represents a collection of checkstyle errors for a single file.
+type File struct {
+	Name   string  `xml:"name,attr"`
+	Errors []Error `xml:"error"`
+}
+
+// ReadXML reads a checkstyle XML report from reader.
+func ReadXML(reader io.Reader) ([]File, error) {
+	var res struct {
+		Files []File `xml:"file"`
+	}
+	return res.Files, xml.NewDecoder(reader).Decode(&res)
+}
+
+// Run runs checkstyle using the specified config against the specified
+// list of files and returns the style errors found.
+func Run(config string, files []string) (outfiles []File, err error) {
+	if len(files) == 0 {
+		return []File{}, nil
+	}
+
+	cmd := exec.Command("java", append([]string{"-cp", *checkstylejar,
+		"-Dcheckstyle.header.file=eclipse/settings/code-style/google.header",
+		"com.puppycrawl.tools.checkstyle.Main", "-f", "xml", "-c", config},
+		files...)...)
+	reader, err := cmd.StdoutPipe()
+	if err != nil {
+		return nil, err
+	}
+	defer reader.Close()
+	cmd.Stderr = os.Stderr
+	log.Println("running checkstyle:", cmd.Args)
+	if err = cmd.Start(); err != nil {
+		return nil, err
+	}
+	// TODO(mdempsky): Check cmd.Wait() exit code?
+	defer cmd.Wait()
+	return ReadXML(reader)
+}
diff --git a/checkstyle/checkstyle_test.go b/checkstyle/checkstyle_test.go
new file mode 100644
index 0000000..ba7e99c
--- /dev/null
+++ b/checkstyle/checkstyle_test.go
@@ -0,0 +1,58 @@
+/*
+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 checkstyle_test
+
+import (
+	"fmt"
+	"strings"
+	"testing"
+
+	"gwt.googlesource.com/buildglue.git/checkstyle"
+)
+
+func TestReadXML(t *testing.T) {
+	input := `
+	  <checkstyle>
+	    <file name="foo">
+	      <error line="15" severity="error" message="hello"/>
+	      <error line="27" severity="warning" message="bye bye"/>
+	    </file>
+	    <file name="blorp"/>
+	    <file name="bar">
+	      <error line="42" severity="info" message="woof"/>
+	    </file>
+	  </checkstyle>
+	`
+	expect := []checkstyle.File{
+		{Name: "foo", Errors: []checkstyle.Error{
+			{Line: 15, Severity: "error", Message: "hello"},
+			{Line: 27, Severity: "warning", Message: "bye bye"},
+		}},
+		{Name: "blorp"},
+		{Name: "bar", Errors: []checkstyle.Error{
+			{Line: 42, Severity: "info", Message: "woof"},
+		}},
+	}
+
+	actual, err := checkstyle.ReadXML(strings.NewReader(input))
+	if err != nil {
+		t.Error("ReadXML returned failure:", err)
+	}
+	if fmt.Sprintf("%#v", expect) != fmt.Sprintf("%#v", actual) {
+		t.Errorf("expect %#v, actual %#v", expect, actual)
+	}
+}
diff --git a/cmd/lint/lint.go b/cmd/lint/lint.go
new file mode 100644
index 0000000..b4c9b13
--- /dev/null
+++ b/cmd/lint/lint.go
@@ -0,0 +1,30 @@
+/*
+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 main
+
+import (
+	"flag"
+
+	"gwt.googlesource.com/buildglue.git/lint"
+)
+
+func main() {
+	flag.Parse()
+	if err := lint.Lint(flag.Arg(0)); err != nil {
+		panic(err)
+	}
+}
diff --git a/cmd/post-review/postreview.go b/cmd/post-review/postreview.go
new file mode 100644
index 0000000..8111689
--- /dev/null
+++ b/cmd/post-review/postreview.go
@@ -0,0 +1,44 @@
+/*
+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 main
+
+import (
+	"flag"
+	"strings"
+
+	"gwt.googlesource.com/buildglue.git/gerrit"
+)
+
+var (
+	verified = flag.Int("verified", 0, "value for gerrit review verified label")
+)
+
+func main() {
+	flag.Parse()
+
+	ref, message := flag.Arg(0), flag.Arg(1)
+	if !strings.HasPrefix(ref, "refs/changes/") {
+		panic("ref doesn't start with \"refs/changes/\"")
+	}
+
+	review := gerrit.Review{Message: message}
+	if *verified != 0 {
+		review.Labels = &gerrit.Labels{Verified: *verified}
+	}
+
+	gerrit.Post(ref, review)
+}
diff --git a/cmd/presubmitter/presubmitter.go b/cmd/presubmitter/presubmitter.go
new file mode 100644
index 0000000..bcc47dc
--- /dev/null
+++ b/cmd/presubmitter/presubmitter.go
@@ -0,0 +1,101 @@
+/*
+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.
+*/
+
+/*
+Presubmitter polls GWT's Gerrit server and runs presubmit checks when
+new changes are detected.
+
+To use presubmitter, you need to first setup a JSON-formatted creds file
+like:
+
+    {
+      "GerritUsername": "git-azurediamond.bash.org",
+      "GerritPassword": "hunter2",
+      "JenkinsToken": "opensesame"
+    }
+
+By default, presubmitter looks for this file at $HOME/.gwtcreds.  This
+can be changed using the -creds flag.
+
+Additionally, presubmitter expects to be run from the top-level
+directory of a GWT git repository that it can use for checking out
+uploaded changes.
+
+Lastly, presubmitter expects to find the checkstyle JAR at
+../tools/antlib/checkstyle-all-4.2.jar, but this can also be changed using
+the -checkstylejar flag.
+*/
+package main
+
+import (
+	"flag"
+	"log"
+	"sync"
+	"time"
+
+	"gwt.googlesource.com/buildglue.git/gerrit"
+	"gwt.googlesource.com/buildglue.git/jenkins"
+	"gwt.googlesource.com/buildglue.git/lint"
+)
+
+const query = "(project:gwt status:open -label:Verified=1 -label:Verified=-1 -label:Code-Review=-1 -label:Code-Review=-2 ownerin:\"Jenkins Trusted\" -age:1w) OR (project:gwt status:open -label:Verified=1 -label:Verified=-1 label:Code-Review=2 -age:1w)"
+
+const timeout = 90 * time.Minute
+
+// Running lint mutates the current directory, so we need to ensure we serialize it.
+var lintLock sync.Mutex
+
+func main() {
+	flag.Parse()
+
+	nextRetry := make(map[string]time.Time)
+	for {
+		refs, err := gerrit.Query(query)
+		if err != nil {
+			log.Println("error querying gerrit:", err)
+			time.Sleep(time.Minute)
+			continue
+		}
+		log.Println("found refs:", refs)
+
+		now := time.Now()
+		for _, ref := range refs {
+			if now.Before(nextRetry[ref]) {
+				continue
+			}
+			// TODO(mdempsky): Exponential back off.
+			nextRetry[ref] = now.Add(timeout)
+
+			log.Println("verifying ref:", ref)
+			go func(ref string) {
+				lintLock.Lock()
+				if err := lint.Lint(ref); err != nil {
+					lintLock.Unlock()
+					log.Println("lint error:", err)
+					return
+				}
+				lintLock.Unlock()
+
+				if err := jenkins.RunPresubmit(ref); err != nil {
+					log.Println("presubmit error:", err)
+					return
+				}
+			}(ref)
+		}
+
+		time.Sleep(time.Minute)
+	}
+}
diff --git a/creds/creds.go b/creds/creds.go
new file mode 100644
index 0000000..fe171e7
--- /dev/null
+++ b/creds/creds.go
@@ -0,0 +1,59 @@
+/*
+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 creds provides credentials for working with GWT build infrastructure.
+package creds
+
+import (
+	"encoding/json"
+	"flag"
+	"os"
+	"sync"
+)
+
+var credsFile = flag.String("creds", os.Getenv("HOME")+"/.gwtcreds", "path to GWT creds file")
+
+var creds struct {
+	GerritUsername string
+	GerritPassword string
+	JenkinsToken   string
+}
+
+func load() {
+	f, err := os.Open(*credsFile)
+	if err != nil {
+		panic(err)
+	}
+	defer f.Close()
+	if err = json.NewDecoder(f).Decode(&creds); err != nil {
+		panic(err)
+	}
+}
+
+var once sync.Once
+
+// GerritBasicAuth returns the username and password for calling Gerrit REST API
+// as Jenkins.
+func GerritBasicAuth() (string, string) {
+	once.Do(load)
+	return creds.GerritUsername, creds.GerritPassword
+}
+
+// JenkinsAuthToken returns the Jenkins auth token for triggering Jenkins builds.
+func JenkinsAuthToken() string {
+	once.Do(load)
+	return creds.JenkinsToken
+}
diff --git a/gerrit/doc.go b/gerrit/doc.go
new file mode 100644
index 0000000..1bfa631
--- /dev/null
+++ b/gerrit/doc.go
@@ -0,0 +1,18 @@
+/*
+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 provides methods for interfacing with Gerrit's REST API.
+package gerrit
diff --git a/gerrit/query.go b/gerrit/query.go
new file mode 100644
index 0000000..c044dd4
--- /dev/null
+++ b/gerrit/query.go
@@ -0,0 +1,81 @@
+/*
+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
+}
diff --git a/gerrit/query_test.go b/gerrit/query_test.go
new file mode 100644
index 0000000..34b3e38
--- /dev/null
+++ b/gerrit/query_test.go
@@ -0,0 +1,66 @@
+/*
+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_test
+
+import (
+	"fmt"
+	"strings"
+	"testing"
+
+	"gwt.googlesource.com/buildglue.git/gerrit"
+)
+
+func TestParseRefs(t *testing.T) {
+	// Revelant snippet from https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#current-revision
+	input := `)]}'
+	[
+	  {
+	    "current_revision": "184ebe53805e102605d11f6b143486d15c23a09c",
+	    "revisions": {
+	      "184ebe53805e102605d11f6b143486d15c23a09c": {
+	        "fetch": {
+	          "http": {
+	            "ref": "refs/changes/97/97/1"
+	          }
+	        }
+	      }
+	    }
+	  },
+	  {
+	    "current_revision": "27cc4558b5a3d3387dd11ee2df7a117e7e581822",
+	    "revisions": {
+	      "27cc4558b5a3d3387dd11ee2df7a117e7e581822": {
+	        "fetch": {
+	          "http": {
+	            "ref": "refs/changes/99/4799/2"
+	          }
+	        }
+	      }
+	    }
+	  }
+	]
+	`
+	expect := []string{"refs/changes/97/97/1", "refs/changes/99/4799/2"}
+
+	actual, err := gerrit.ParseRefs(strings.NewReader(input))
+	if err != nil {
+		t.Error("failed to parse input:", err)
+	}
+	if fmt.Sprintf("%#v", expect) != fmt.Sprintf("%#v", actual) {
+		t.Errorf("expect %#v, actual %#v", expect, actual)
+	}
+}
diff --git a/gerrit/review.go b/gerrit/review.go
new file mode 100644
index 0000000..9f6a1b4
--- /dev/null
+++ b/gerrit/review.go
@@ -0,0 +1,84 @@
+/*
+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
+}
diff --git a/git/git.go b/git/git.go
new file mode 100644
index 0000000..6063881
--- /dev/null
+++ b/git/git.go
@@ -0,0 +1,109 @@
+/*
+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 git provides helper methods for invoking Git commands.
+package git
+
+import (
+	"bufio"
+	"errors"
+	"io"
+	"os"
+	"os/exec"
+	"strconv"
+	"strings"
+)
+
+// Errors returned by this package.
+var (
+	NotOneLine = errors.New("git command output was not one line")
+)
+
+// Run invokes git with the specified arguments.
+func Run(args ...string) error {
+	cmd := exec.Command("git", args...)
+	cmd.Stdout = os.Stdout
+	cmd.Stderr = os.Stderr
+	return cmd.Run()
+}
+
+// Lines invokes git with the specified arguments and returns a slice of
+// the output lines.
+func Lines(args ...string) (res []string, err error) {
+	cmd := exec.Command("git", args...)
+	reader, err := cmd.StdoutPipe()
+	if err != nil {
+		return nil, err
+	}
+	defer reader.Close()
+	cmd.Stderr = os.Stderr
+	if err = cmd.Start(); err != nil {
+		return nil, err
+	}
+	defer func() {
+		errwait := cmd.Wait()
+		if err == nil {
+			err = errwait
+		}
+	}()
+	r := bufio.NewReader(reader)
+	for {
+		line, err := r.ReadString('\n')
+		if err == io.EOF {
+			break
+		} else if err != nil {
+			return nil, err
+		}
+		res = append(res, line[:len(line)-1])
+	}
+	return res, nil
+}
+
+// Lines invokes git with the specified arguments and returns a string
+// containing its single line of output.  Returns NotOneLine if the
+// git does not output a single line.
+func Line(args ...string) (string, error) {
+	lines, err := Lines(args...)
+	if err != nil {
+		return "", err
+	}
+	if len(lines) != 1 {
+		return "", NotOneLine
+	}
+	return lines[0], err
+}
+
+// Blame returns the set of line numbers from file that were added or modified
+// in Git revision rev.  Rev must be a full 20 char hex revision id.  Lines are
+// numbered from 1.
+func Blame(rev, file string) (map[int]bool, error) {
+	lines, err := Lines("blame", "--porcelain", rev+"^..", "--", file)
+	if err != nil {
+		return nil, err
+	}
+	res := make(map[int]bool)
+	for _, s := range lines {
+		if !strings.HasPrefix(s, rev+" ") {
+			continue
+		}
+		i, err := strconv.Atoi(strings.Split(s, " ")[2])
+		if err != nil {
+			return nil, err
+		}
+		res[i] = true
+	}
+	return res, nil
+}
diff --git a/jenkins/jenkins.go b/jenkins/jenkins.go
new file mode 100644
index 0000000..f4d5a60
--- /dev/null
+++ b/jenkins/jenkins.go
@@ -0,0 +1,45 @@
+/*
+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 jenkins provides helper methods for interacting with GWT's Jenkins server.
+package jenkins
+
+import (
+	"net/http"
+	"net/url"
+
+	"gwt.googlesource.com/buildglue.git/creds"
+)
+
+// RunPresubmit queues a Jenkins presubmit build.
+func RunPresubmit(ref string) error {
+	url := (&url.URL{
+		Scheme: "http",
+		Host:   "localhost:8080",
+		Path:   "/job/gwt.presubmit/buildWithParameters",
+		RawQuery: url.Values{
+			"token":  {creds.JenkinsAuthToken()},
+			"COMMIT": {ref},
+		}.Encode(),
+	}).String()
+
+	// TODO(mdempsky): Check for failed return codes?
+	resp, err := http.Get(url)
+	if err == nil {
+		resp.Body.Close()
+	}
+	return err
+}
diff --git a/lint/lint.go b/lint/lint.go
new file mode 100644
index 0000000..a3931ab
--- /dev/null
+++ b/lint/lint.go
@@ -0,0 +1,231 @@
+/*
+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 lint provides helper methods for quickly running lint checks
+// against a proposed change on Gerrit.
+package lint
+
+import (
+	"errors"
+	"fmt"
+	"log"
+	"strings"
+
+	"gwt.googlesource.com/buildglue.git/checkstyle"
+	"gwt.googlesource.com/buildglue.git/gerrit"
+	"gwt.googlesource.com/buildglue.git/git"
+)
+
+// Errors that can be returned by Lint.
+var (
+	LintFailed = errors.New("commit failed lint checking")
+)
+
+// Should be kept in sync with GWT's build.xml files.
+var checks = []struct {
+	config   string
+	includes []string
+	excludes []string
+}{
+	{
+		config: "eclipse/settings/code-style/gwt-checkstyle.xml",
+		includes: []string{
+			"dev/core/src/",
+			"dev/core/super/com/google/gwt/dev/jjs/intrinsic/",
+			"user/src/",
+			"user/super/com/google/gwt/emul/",
+			"user/super/com/google/gwt/junit/translatable/",
+		},
+		excludes: []string{
+			"dev/core/src/com/google/gwt/dev/shell/remoteui/RemoteMessageProto.java",
+			"dev/core/src/com/google/gwt/dev/asm/",
+			"dev/core/src/com/google/gwt/dev/js/rhino/",
+			"dev/core/src/org/eclipse/",
+			"dev/core/src/org/apache/",
+			"user/src/javax/validation/",
+			"user/src/org/hibernate/validator/",
+		},
+	},
+	{
+		config: "eclipse/settings/code-style/gwt-checkstyle-tests.xml",
+		includes: []string{
+			"user/test/com/google/",
+			"user/test/test/",
+		},
+	},
+}
+
+// Match returns true if file is a ".java" file that starts with a string
+// from includes but does not start with any strings from excludes.
+func match(file string, includes, excludes []string) bool {
+	if !strings.HasSuffix(file, ".java") {
+		return false
+	}
+	for _, exclude := range excludes {
+		if strings.HasPrefix(file, exclude) {
+			return false
+		}
+	}
+	for _, include := range includes {
+		if strings.HasPrefix(file, include) {
+			return true
+		}
+	}
+	return false
+}
+
+// Matches returns the sublist of files that match the provided includes
+// and excludes rules.
+func matches(files, includes, excludes []string) []string {
+	res := []string{}
+	for _, file := range files {
+		if match(file, includes, excludes) {
+			res = append(res, file)
+		}
+	}
+	return res
+}
+
+type linter struct {
+	rev      string
+	comments map[string][]gerrit.Comment
+	failed   bool
+}
+
+func newLinter(rev string) *linter {
+	return &linter{
+		rev:      rev,
+		comments: make(map[string][]gerrit.Comment),
+	}
+}
+
+func (l *linter) comment(file string, line int, severity, message string) {
+	comment := gerrit.Comment{Line: line, Message: fmt.Sprintf("[%s] %s", severity, message)}
+	l.comments[file] = append(l.comments[file], comment)
+	if severity == "error" {
+		l.failed = true
+	}
+}
+
+func (l *linter) checkStyle(config string, files []string) error {
+	out, err := checkstyle.Run(config, files)
+	if err != nil {
+		log.Println("running checkstyle failed:", err)
+		return err
+	}
+	for _, file := range out {
+		if len(file.Errors) == 0 {
+			continue
+		}
+		blameable, err := git.Blame(l.rev, file.Name)
+		if err != nil {
+			return err
+		}
+		for _, err := range file.Errors {
+			if blameable[err.Line] {
+				l.comment(file.Name, err.Line, err.Severity, err.Message)
+			}
+		}
+	}
+	return nil
+}
+
+func (l *linter) checkMessage(commitmsg []string) {
+	warn := func(line int, message string) {
+		// Gerrit includes some extra header lines before the commit message.
+		// TODO(mdempsky): Is it always exactly six lines?
+		l.comment("/COMMIT_MSG", line+6, "warning", message)
+	}
+
+	if len(commitmsg) >= 1 && len(commitmsg[0]) > 50 {
+		warn(1, "Subject line should be 50 characters or fewer.")
+	}
+	if len(commitmsg) >= 3 && len(commitmsg[1]) > 0 {
+		warn(2, "Subject line and body should be separated by a blank line.")
+	}
+	for i, line := range commitmsg {
+		if i >= 2 && len(line) > 72 {
+			warn(i+1, "Commit message lines should be 72 characters or fewer.")
+			break
+		}
+	}
+}
+
+func (l *linter) review() gerrit.Review {
+	res := gerrit.Review{}
+	if l.failed {
+		res.Message = ("Oops, this change failed the fast style check! " +
+			"Please fix all errors and try again.")
+		res.Labels = &gerrit.Labels{Verified: -1}
+	} else if len(l.comments) != 0 {
+		res.Message = ("This change passed the fast style check, " +
+			"but still triggered some non-error warnings. " +
+			"Please review and fix if appropriate.")
+	} else {
+		res.Message = ("Woo hoo, this change passed the fast style check " +
+			"with ZERO new warnings! You rock!")
+	}
+	if len(l.comments) != 0 {
+		res.Comments = l.comments
+	}
+	return res
+}
+
+// Lint fetches ref from Gerrit, inspects the commit message and runs checkstyle against
+// any added or modified files, and posts a review to Gerrit with the results.
+// Returns a LintFailed error if any lint errors were found.
+func Lint(ref string) error {
+	if err := git.Run("fetch", "https://gwt.googlesource.com/gwt", ref); err != nil {
+		log.Println("fetch failed:", err)
+		return err
+	}
+	rev, err := git.Line("rev-parse", "FETCH_HEAD")
+	if err != nil {
+		return err
+	}
+	if err = git.Run("checkout", rev); err != nil {
+		return err
+	}
+	files, err := git.Lines("diff-tree", "-r", "--name-only", "--diff-filter=AM", rev+"^", rev)
+	if err != nil {
+		return err
+	}
+
+	log.Println("running lint checks")
+
+	linter := newLinter(rev)
+	for _, check := range checks {
+		if err := linter.checkStyle(check.config, matches(files, check.includes, check.excludes)); err != nil {
+			log.Println("checkstyle error:", err)
+			return err
+		}
+	}
+
+	commitmsg, err := git.Lines("show", "-s", "--pretty=format:%B", rev)
+	if err != nil {
+		return err
+	}
+	linter.checkMessage(commitmsg)
+
+	if err = gerrit.Post(ref, linter.review()); err != nil {
+		return err
+	}
+
+	if linter.failed {
+		return LintFailed
+	}
+	return nil
+}