rustfmt_nightly/
source_file.rs

1use std::fs;
2use std::io::{self, Write};
3use std::path::Path;
4use std::sync::Arc;
5
6use crate::NewlineStyle;
7use crate::config::FileName;
8use crate::emitter::{self, Emitter};
9use crate::parse::session::ParseSess;
10
11#[cfg(test)]
12use crate::config::Config;
13#[cfg(test)]
14use crate::create_emitter;
15#[cfg(test)]
16use crate::formatting::FileRecord;
17
18// Append a newline to the end of each file.
19pub(crate) fn append_newline(s: &mut String) {
20    s.push('\n');
21}
22
23#[cfg(test)]
24pub(crate) fn write_all_files<T>(
25    source_file: &[FileRecord],
26    out: &mut T,
27    config: &Config,
28) -> Result<(), io::Error>
29where
30    T: Write,
31{
32    let mut emitter = create_emitter(config);
33
34    emitter.emit_header(out)?;
35    for (filename, text) in source_file {
36        write_file(
37            None,
38            filename,
39            text,
40            out,
41            &mut *emitter,
42            config.newline_style(),
43        )?;
44    }
45    emitter.emit_footer(out)?;
46
47    Ok(())
48}
49
50pub(crate) fn write_file<T>(
51    psess: Option<&ParseSess>,
52    filename: &FileName,
53    formatted_text: &str,
54    out: &mut T,
55    emitter: &mut dyn Emitter,
56    newline_style: NewlineStyle,
57) -> Result<emitter::EmitterResult, io::Error>
58where
59    T: Write,
60{
61    fn ensure_real_path(filename: &FileName) -> &Path {
62        match *filename {
63            FileName::Real(ref path) => path,
64            _ => panic!("cannot format `{filename}` and emit to files"),
65        }
66    }
67
68    #[allow(non_local_definitions)]
69    impl From<&FileName> for rustc_span::FileName {
70        fn from(filename: &FileName) -> rustc_span::FileName {
71            match filename {
72                FileName::Real(path) => {
73                    rustc_span::FileName::Real(rustc_span::RealFileName::LocalPath(path.to_owned()))
74                }
75                FileName::Stdin => rustc_span::FileName::Custom("stdin".to_owned()),
76            }
77        }
78    }
79
80    // SourceFile's in the SourceMap will always have Unix-style line endings
81    // See: https://github.com/rust-lang/rustfmt/issues/3850
82    // So if the user has explicitly overridden the rustfmt `newline_style`
83    // config and `filename` is FileName::Real, then we must check the file system
84    // to get the original file value in order to detect newline_style conflicts.
85    // Otherwise, parse session is around (cfg(not(test))) and newline_style has been
86    // left as the default value, then try getting source from the parse session
87    // source map instead of hitting the file system. This also supports getting
88    // original text for `FileName::Stdin`.
89    let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin {
90        Arc::new(fs::read_to_string(ensure_real_path(filename))?)
91    } else {
92        match psess.and_then(|psess| psess.get_original_snippet(filename)) {
93            Some(ori) => ori,
94            None => Arc::new(fs::read_to_string(ensure_real_path(filename))?),
95        }
96    };
97
98    let formatted_file = emitter::FormattedFile {
99        filename,
100        original_text: original_text.as_str(),
101        formatted_text,
102    };
103
104    emitter.emit_formatted_file(out, formatted_file)
105}