2 use std::io::{self, Write};
5 use syntax::source_map::SourceMap;
7 use crate::config::FileName;
8 use crate::emitter::{self, Emitter};
9 use crate::NewlineStyle;
12 use crate::config::Config;
14 use crate::create_emitter;
16 use crate::formatting::FileRecord;
18 // Append a newline to the end of each file.
19 pub(crate) fn append_newline(s: &mut String) {
24 pub(crate) fn write_all_files<T>(
25 source_file: &[FileRecord],
28 ) -> Result<(), io::Error>
32 let mut emitter = create_emitter(config);
34 emitter.emit_header(out)?;
35 for &(ref filename, ref text) in source_file {
42 config.newline_style(),
45 emitter.emit_footer(out)?;
50 pub(crate) fn write_file<T>(
51 source_map: Option<&SourceMap>,
55 emitter: &mut dyn Emitter,
56 newline_style: NewlineStyle,
57 ) -> Result<emitter::EmitterResult, io::Error>
61 fn ensure_real_path(filename: &FileName) -> &Path {
63 FileName::Real(ref path) => path,
64 _ => panic!("cannot format `{}` and emit to files", filename),
68 impl From<&FileName> for syntax_pos::FileName {
69 fn from(filename: &FileName) -> syntax_pos::FileName {
71 FileName::Real(path) => syntax_pos::FileName::Real(path.to_owned()),
72 FileName::Stdin => syntax_pos::FileName::Custom("stdin".to_owned()),
77 // SourceFile's in the SourceMap will always have Unix-style line endings
78 // See: https://github.com/rust-lang/rustfmt/issues/3850
79 // So if the user has explicitly overridden the rustfmt `newline_style`
80 // config and `filename` is FileName::Real, then we must check the file system
81 // to get the original file value in order to detect newline_style conflicts.
82 // Otherwise, parse session is around (cfg(not(test))) and newline_style has been
83 // left as the default value, then try getting source from the parse session
84 // source map instead of hitting the file system. This also supports getting
85 // original text for `FileName::Stdin`.
86 let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin {
87 fs::read_to_string(ensure_real_path(filename))?
90 .and_then(|x| x.get_source_file(&filename.into()))
91 .and_then(|x| x.src.as_ref().map(ToString::to_string))
94 None => fs::read_to_string(ensure_real_path(filename))?,
98 let formatted_file = emitter::FormattedFile {
100 original_text: &original_text,
104 emitter.emit_formatted_file(out, formatted_file)