@@ -6,6 +6,7 @@ use syntax::source_map::SourceMap;
66
77use crate :: config:: FileName ;
88use crate :: emitter:: { self , Emitter } ;
9+ use crate :: NewlineStyle ;
910
1011#[ cfg( test) ]
1112use crate :: config:: Config ;
3233
3334 emitter. emit_header ( out) ?;
3435 for & ( ref filename, ref text) in source_file {
35- write_file ( None , filename, text, out, & mut * emitter) ?;
36+ write_file (
37+ None ,
38+ filename,
39+ text,
40+ out,
41+ & mut * emitter,
42+ config. newline_style ( ) ,
43+ ) ?;
3644 }
3745 emitter. emit_footer ( out) ?;
3846
@@ -45,6 +53,7 @@ pub(crate) fn write_file<T>(
4553 formatted_text : & str ,
4654 out : & mut T ,
4755 emitter : & mut dyn Emitter ,
56+ newline_style : NewlineStyle ,
4857) -> Result < emitter:: EmitterResult , io:: Error >
4958where
5059 T : Write ,
@@ -65,15 +74,25 @@ where
6574 }
6675 }
6776
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
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
7085 // 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) ) ?,
86+ let original_text = if newline_style != NewlineStyle :: Auto && * filename != FileName :: Stdin {
87+ fs:: read_to_string ( ensure_real_path ( filename) ) ?
88+ } else {
89+ match source_map
90+ . and_then ( |x| x. get_source_file ( & filename. into ( ) ) )
91+ . and_then ( |x| x. src . as_ref ( ) . map ( ToString :: to_string) )
92+ {
93+ Some ( ori) => ori,
94+ None => fs:: read_to_string ( ensure_real_path ( filename) ) ?,
95+ }
7796 } ;
7897
7998 let formatted_file = emitter:: FormattedFile {
0 commit comments