blob: 454a367d30b21530222acb3e71aacbbe1126b3a1 [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
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
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 (
var checkstylejar = flag.String("checkstylejar", "../tools/antlib/checkstyle-5.7-all.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, pathPrefix string) ([]File, error) {
var res struct {
Files []File `xml:"file"`
if err := xml.NewDecoder(reader).Decode(&res); err != nil {
return nil, err
if !strings.HasSuffix(pathPrefix, "/") {
pathPrefix += "/"
for i := range res.Files {
// Make sure the filenames are relative.
res.Files[i].Name = strings.TrimPrefix(res.Files[i].Name, pathPrefix)
return res.Files, nil
// 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
workingDir, err := os.Getwd()
if err != nil {
return nil, err
cmd := exec.Command("java", append([]string{"-cp", *checkstylejar,
"", "-f", "xml", "-c", config},
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, workingDir)