]> git.lizzy.rs Git - rust.git/blob - src/source_file.rs
Use trait to abstract emit modes (#3616)
[rust.git] / src / source_file.rs
1 use std::fs;
2 use std::io::{self, Write};
3 use std::path::Path;
4
5 use syntax::source_map::SourceMap;
6
7 use crate::config::FileName;
8 use crate::emitter::{self, Emitter};
9
10 #[cfg(test)]
11 use crate::config::Config;
12 #[cfg(test)]
13 use crate::create_emitter;
14 #[cfg(test)]
15 use crate::formatting::FileRecord;
16
17 // Append a newline to the end of each file.
18 pub(crate) fn append_newline(s: &mut String) {
19     s.push_str("\n");
20 }
21
22 #[cfg(test)]
23 pub(crate) fn write_all_files<T>(
24     source_file: &[FileRecord],
25     out: &mut T,
26     config: &Config,
27 ) -> Result<(), io::Error>
28 where
29     T: Write,
30 {
31     let emitter = create_emitter(config);
32
33     emitter.emit_header(out)?;
34     for &(ref filename, ref text) in source_file {
35         write_file(None, filename, text, out, &*emitter)?;
36     }
37     emitter.emit_footer(out)?;
38
39     Ok(())
40 }
41
42 pub(crate) fn write_file<T>(
43     source_map: Option<&SourceMap>,
44     filename: &FileName,
45     formatted_text: &str,
46     out: &mut T,
47     emitter: &dyn Emitter,
48 ) -> Result<emitter::EmitterResult, io::Error>
49 where
50     T: Write,
51 {
52     fn ensure_real_path(filename: &FileName) -> &Path {
53         match *filename {
54             FileName::Real(ref path) => path,
55             _ => panic!("cannot format `{}` and emit to files", filename),
56         }
57     }
58
59     impl From<&FileName> for syntax_pos::FileName {
60         fn from(filename: &FileName) -> syntax_pos::FileName {
61             match filename {
62                 FileName::Real(path) => syntax_pos::FileName::Real(path.to_owned()),
63                 FileName::Stdin => syntax_pos::FileName::Custom("stdin".to_owned()),
64             }
65         }
66     }
67
68     // If parse session is around (cfg(not(test))) then try getting source from
69     // there instead of hitting the file system. This also supports getting
70     // original text for `FileName::Stdin`.
71     let original_text = source_map
72         .and_then(|x| x.get_source_file(&filename.into()))
73         .and_then(|x| x.src.as_ref().map(ToString::to_string));
74     let original_text = match original_text {
75         Some(ori) => ori,
76         None => fs::read_to_string(ensure_real_path(filename))?,
77     };
78
79     let formatted_file = emitter::FormattedFile {
80         filename,
81         original_text: &original_text,
82         formatted_text,
83     };
84
85     emitter.emit_formatted_file(out, formatted_file)
86 }