]> git.lizzy.rs Git - rust.git/blob - src/checkstyle.rs
Handle special-case macros
[rust.git] / src / checkstyle.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::io::{self, Write};
12
13 use config::WriteMode;
14 use rustfmt_diff::{DiffLine, Mismatch};
15
16 pub fn output_header<T>(out: &mut T, mode: WriteMode) -> Result<(), io::Error>
17 where
18     T: Write,
19 {
20     if mode == WriteMode::Checkstyle {
21         let mut xml_heading = String::new();
22         xml_heading.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
23         xml_heading.push_str("\n");
24         xml_heading.push_str("<checkstyle version=\"4.3\">");
25         write!(out, "{}", xml_heading)?;
26     }
27     Ok(())
28 }
29
30 pub fn output_footer<T>(out: &mut T, mode: WriteMode) -> Result<(), io::Error>
31 where
32     T: Write,
33 {
34     if mode == WriteMode::Checkstyle {
35         let mut xml_tail = String::new();
36         xml_tail.push_str("</checkstyle>\n");
37         write!(out, "{}", xml_tail)?;
38     }
39     Ok(())
40 }
41
42 pub fn output_checkstyle_file<T>(
43     mut writer: T,
44     filename: &str,
45     diff: Vec<Mismatch>,
46 ) -> Result<(), io::Error>
47 where
48     T: Write,
49 {
50     write!(writer, "<file name=\"{}\">", filename)?;
51     for mismatch in diff {
52         for line in mismatch.lines {
53             // Do nothing with `DiffLine::Context` and `DiffLine::Resulting`.
54             if let DiffLine::Expected(ref str) = line {
55                 let message = xml_escape_str(str);
56                 write!(
57                     writer,
58                     "<error line=\"{}\" severity=\"warning\" message=\"Should be `{}`\" \
59                      />",
60                     mismatch.line_number,
61                     message
62                 )?;
63             }
64         }
65     }
66     write!(writer, "</file>")?;
67     Ok(())
68 }
69
70 // Convert special characters into XML entities.
71 // This is needed for checkstyle output.
72 fn xml_escape_str(string: &str) -> String {
73     let mut out = String::new();
74     for c in string.chars() {
75         match c {
76             '<' => out.push_str("&lt;"),
77             '>' => out.push_str("&gt;"),
78             '"' => out.push_str("&quot;"),
79             '\'' => out.push_str("&apos;"),
80             '&' => out.push_str("&amp;"),
81             _ => out.push(c),
82         }
83     }
84     out
85 }