|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "encoding/xml" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "regexp" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | +) |
| 13 | + |
| 14 | +var ( |
| 15 | + input = os.Stdin |
| 16 | + output = os.Stdout |
| 17 | + parsable = regexp.MustCompile(`^(?P<file>.+?):(?P<line>\d+):(?P<column>\d+):\s+\[(?P<level>[a-z]+)\]\s+(?P<desc>.+?)(?P<rule>\s+\([a-z-]+\))?\n$`) |
| 18 | +) |
| 19 | + |
| 20 | +type Checkstyle struct { |
| 21 | + XMLName xml.Name `xml:"checkstyle"` |
| 22 | + Version string `xml:"version,attr"` |
| 23 | + Files []*File |
| 24 | +} |
| 25 | + |
| 26 | +type File struct { |
| 27 | + XMLName xml.Name `xml:"file"` |
| 28 | + Name string `xml:"name,attr"` |
| 29 | + Problems []Problem |
| 30 | +} |
| 31 | + |
| 32 | +type Problem struct { |
| 33 | + XMLName xml.Name `xml:"error"` |
| 34 | + Line int `xml:"line,attr"` |
| 35 | + Column int `xml:"column,attr"` |
| 36 | + Severity string `xml:"severity,attr"` |
| 37 | + Source string `xml:"source,attr,omitempty"` |
| 38 | + Message string `xml:"message,attr"` |
| 39 | +} |
| 40 | + |
| 41 | +func main() { |
| 42 | + reader := bufio.NewReader(input) |
| 43 | + err := process(reader, output) |
| 44 | + if err != nil { |
| 45 | + panic(err) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +func process(r *bufio.Reader, w io.Writer) error { |
| 50 | + fileMap := map[string]*File{} |
| 51 | + var fileOrder []string |
| 52 | + |
| 53 | + for { |
| 54 | + line, err := r.ReadString('\n') |
| 55 | + if err != nil { |
| 56 | + break |
| 57 | + } |
| 58 | + |
| 59 | + match := parsable.FindStringSubmatch(line) |
| 60 | + if len(match) < 7 { |
| 61 | + return fmt.Errorf("unparsable line: %s", line) |
| 62 | + } |
| 63 | + |
| 64 | + filename, line_str, column_str, level, desc, rule := match[1], match[2], match[3], match[4], match[5], match[6] |
| 65 | + line_no, _ := strconv.Atoi(line_str) |
| 66 | + column_no, _ := strconv.Atoi(column_str) |
| 67 | + problem := Problem{Line: line_no, Column: column_no, Severity: level, Source: strings.Trim(rule, " ()"), Message: desc} |
| 68 | + |
| 69 | + file, ok := fileMap[filename] |
| 70 | + if !ok { |
| 71 | + fileOrder = append(fileOrder, filename) |
| 72 | + fileMap[filename] = &File{Name: filename, Problems: []Problem{problem}} |
| 73 | + } else { |
| 74 | + file.Problems = append(file.Problems, problem) |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + var files []*File |
| 79 | + for _, filename := range fileOrder { |
| 80 | + files = append(files, fileMap[filename]) |
| 81 | + } |
| 82 | + |
| 83 | + data, err := xml.MarshalIndent(Checkstyle{Version: "5.0", Files: files}, "", " ") |
| 84 | + if err != nil { |
| 85 | + return err |
| 86 | + } |
| 87 | + |
| 88 | + fmt.Fprint(w, xml.Header) |
| 89 | + w.Write(data) |
| 90 | + w.Write([]byte("\n")) |
| 91 | + return nil |
| 92 | +} |
0 commit comments