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    // SourceFile's in the SourceMap will always have Unix-style line endings
69    // See: https://github.com/rust-lang/rustfmt/issues/3850
70    // So if the user has explicitly overridden the rustfmt `newline_style`
71    // config and `filename` is FileName::Real, then we must check the file system
72    // to get the original file value in order to detect newline_style conflicts.
73    // Otherwise, parse session is around (cfg(not(test))) and newline_style has been
74    // left as the default value, then try getting source from the parse session
75    // source map instead of hitting the file system. This also supports getting
76    // original text for `FileName::Stdin`.
77    let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin {
78        Arc::new(fs::read_to_string(ensure_real_path(filename))?)
79    } else {
80        match psess.and_then(|psess| psess.get_original_snippet(filename)) {
81            Some(ori) => ori,
82            None => Arc::new(fs::read_to_string(ensure_real_path(filename))?),
83        }
84    };
85
86    let formatted_file = emitter::FormattedFile {
87        filename,
88        original_text: original_text.as_str(),
89        formatted_text,
90    };
91
92    emitter.emit_formatted_file(out, formatted_file)
93}