2 use std::io::{self, Write};
5 use crate::config::FileName;
6 use crate::emitter::{self, Emitter};
7 use crate::syntux::session::ParseSess;
8 use crate::NewlineStyle;
11 use crate::config::Config;
13 use crate::create_emitter;
15 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 parse_sess: Option<&ParseSess>,
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 rustc_span::FileName {
69 fn from(filename: &FileName) -> rustc_span::FileName {
71 FileName::Real(path) => {
72 rustc_span::FileName::Real(rustc_span::RealFileName::Named(path.to_owned()))
74 FileName::Stdin => rustc_span::FileName::Custom("stdin".to_owned()),
79 // SourceFile's in the SourceMap will always have Unix-style line endings
80 // See: https://github.com/rust-lang/rustfmt/issues/3850
81 // So if the user has explicitly overridden the rustfmt `newline_style`
82 // config and `filename` is FileName::Real, then we must check the file system
83 // to get the original file value in order to detect newline_style conflicts.
84 // Otherwise, parse session is around (cfg(not(test))) and newline_style has been
85 // left as the default value, then try getting source from the parse session
86 // source map instead of hitting the file system. This also supports getting
87 // original text for `FileName::Stdin`.
88 let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin {
89 Rc::new(fs::read_to_string(ensure_real_path(filename))?)
91 match parse_sess.and_then(|sess| sess.get_original_snippet(filename)) {
93 None => Rc::new(fs::read_to_string(ensure_real_path(filename))?),
97 let formatted_file = emitter::FormattedFile {
99 original_text: original_text.as_str(),
103 emitter.emit_formatted_file(out, formatted_file)