]> git.lizzy.rs Git - rust.git/blob - src/checkstyle.rs
Add trailing comma when using mixed layout with block indent
[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 config::WriteMode;
15 use rustfmt_diff::{DiffLine, Mismatch};
16
17 pub fn output_header<T>(out: &mut T, mode: WriteMode) -> Result<(), io::Error>
18 where
19     T: Write,
20 {
21     if mode == WriteMode::Checkstyle {
22         let mut xml_heading = String::new();
23         xml_heading.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
24         xml_heading.push_str("\n");
25         xml_heading.push_str("<checkstyle version=\"4.3\">");
26         write!(out, "{}", xml_heading)?;
27     }
28     Ok(())
29 }
30
31 pub fn output_footer<T>(out: &mut T, mode: WriteMode) -> Result<(), io::Error>
32 where
33     T: Write,
34 {
35     if mode == WriteMode::Checkstyle {
36         let mut xml_tail = String::new();
37         xml_tail.push_str("</checkstyle>\n");
38         write!(out, "{}", xml_tail)?;
39     }
40     Ok(())
41 }
42
43 pub fn output_checkstyle_file<T>(
44     mut writer: T,
45     filename: &Path,
46     diff: Vec<Mismatch>,
47 ) -> Result<(), io::Error>
48 where
49     T: Write,
50 {
51     write!(writer, "<file name=\"{}\">", filename.display())?;
52     for mismatch in diff {
53         for line in mismatch.lines {
54             // Do nothing with `DiffLine::Context` and `DiffLine::Resulting`.
55             if let DiffLine::Expected(ref str) = line {
56                 let message = xml_escape_str(str);
57                 write!(
58                     writer,
59                     "<error line=\"{}\" severity=\"warning\" message=\"Should be `{}`\" \
60                      />",
61                     mismatch.line_number, 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 }