]> git.lizzy.rs Git - rust.git/blob - src/checkstyle.rs
rewrite_string: retain blank lines that are trailing
[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 use std::path::Path;
13
14 use rustfmt_diff::{DiffLine, Mismatch};
15
16 /// The checkstyle header - should be emitted before the output of Rustfmt.
17 ///
18 /// Note that emitting checkstyle output is not stable and may removed in a
19 /// future version of Rustfmt.
20 pub fn header() -> String {
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     xml_heading
26 }
27
28 /// The checkstyle footer - should be emitted after the output of Rustfmt.
29 ///
30 /// Note that emitting checkstyle output is not stable and may removed in a
31 /// future version of Rustfmt.
32 pub fn footer() -> String {
33     "</checkstyle>\n".to_owned()
34 }
35
36 pub fn output_checkstyle_file<T>(
37     mut writer: T,
38     filename: &Path,
39     diff: Vec<Mismatch>,
40 ) -> Result<(), io::Error>
41 where
42     T: Write,
43 {
44     write!(writer, "<file name=\"{}\">", filename.display())?;
45     for mismatch in diff {
46         for line in mismatch.lines {
47             // Do nothing with `DiffLine::Context` and `DiffLine::Resulting`.
48             if let DiffLine::Expected(ref str) = line {
49                 let message = xml_escape_str(str);
50                 write!(
51                     writer,
52                     "<error line=\"{}\" severity=\"warning\" message=\"Should be `{}`\" \
53                      />",
54                     mismatch.line_number, message
55                 )?;
56             }
57         }
58     }
59     write!(writer, "</file>")?;
60     Ok(())
61 }
62
63 // Convert special characters into XML entities.
64 // This is needed for checkstyle output.
65 fn xml_escape_str(string: &str) -> String {
66     let mut out = String::new();
67     for c in string.chars() {
68         match c {
69             '<' => out.push_str("&lt;"),
70             '>' => out.push_str("&gt;"),
71             '"' => out.push_str("&quot;"),
72             '\'' => out.push_str("&apos;"),
73             '&' => out.push_str("&amp;"),
74             _ => out.push(c),
75         }
76     }
77     out
78 }