]> git.lizzy.rs Git - rust.git/blobdiff - src/source_file.rs
Merge commit 'c4416f20dcaec5d93077f72470e83e150fb923b1' into sync-rustfmt
[rust.git] / src / source_file.rs
index b26cd0521fa5d2a98739ddad77a24460b6dd4979..56d4ab4003832f57cda0b4774731766d22fbdf6f 100644 (file)
@@ -1,26 +1,24 @@
-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
 use std::fs;
 use std::io::{self, Write};
+use std::path::Path;
 
-use crate::checkstyle::output_checkstyle_file;
-use crate::config::{Config, EmitMode, FileName, Verbosity};
-use crate::rustfmt_diff::{make_diff, output_modified, print_diff};
+use crate::config::FileName;
+use crate::emitter::{self, Emitter};
+use crate::parse::session::ParseSess;
+use crate::NewlineStyle;
 
+#[cfg(test)]
+use crate::config::Config;
+#[cfg(test)]
+use crate::create_emitter;
 #[cfg(test)]
 use crate::formatting::FileRecord;
 
+use rustc_data_structures::sync::Lrc;
+
 // Append a newline to the end of each file.
-pub fn append_newline(s: &mut String) {
-    s.push_str("\n");
+pub(crate) fn append_newline(s: &mut String) {
+    s.push('\n');
 }
 
 #[cfg(test)]
@@ -32,91 +30,76 @@ pub(crate) fn write_all_files<T>(
 where
     T: Write,
 {
-    if config.emit_mode() == EmitMode::Checkstyle {
-        write!(out, "{}", crate::checkstyle::header())?;
-    }
+    let mut emitter = create_emitter(config);
+
+    emitter.emit_header(out)?;
     for &(ref filename, ref text) in source_file {
-        write_file(text, filename, out, config)?;
-    }
-    if config.emit_mode() == EmitMode::Checkstyle {
-        write!(out, "{}", crate::checkstyle::footer())?;
+        write_file(
+            None,
+            filename,
+            text,
+            out,
+            &mut *emitter,
+            config.newline_style(),
+        )?;
     }
+    emitter.emit_footer(out)?;
 
     Ok(())
 }
 
-pub fn write_file<T>(
-    formatted_text: &str,
+pub(crate) fn write_file<T>(
+    parse_sess: Option<&ParseSess>,
     filename: &FileName,
+    formatted_text: &str,
     out: &mut T,
-    config: &Config,
-) -> Result<bool, io::Error>
+    emitter: &mut dyn Emitter,
+    newline_style: NewlineStyle,
+) -> Result<emitter::EmitterResult, io::Error>
 where
     T: Write,
 {
-    let filename_to_path = || match *filename {
-        FileName::Real(ref path) => path,
-        _ => panic!("cannot format `{}` and emit to files", filename),
-    };
-
-    match config.emit_mode() {
-        EmitMode::Files if config.make_backup() => {
-            let filename = filename_to_path();
-            let ori = fs::read_to_string(filename)?;
-            if ori != formatted_text {
-                // Do a little dance to make writing safer - write to a temp file
-                // rename the original to a .bk, then rename the temp file to the
-                // original.
-                let tmp_name = filename.with_extension("tmp");
-                let bk_name = filename.with_extension("bk");
-
-                fs::write(&tmp_name, formatted_text)?;
-                fs::rename(filename, bk_name)?;
-                fs::rename(tmp_name, filename)?;
-            }
-        }
-        EmitMode::Files => {
-            // Write text directly over original file if there is a diff.
-            let filename = filename_to_path();
-            let ori = fs::read_to_string(filename)?;
-            if ori != formatted_text {
-                fs::write(filename, formatted_text)?;
-            }
+    fn ensure_real_path(filename: &FileName) -> &Path {
+        match *filename {
+            FileName::Real(ref path) => path,
+            _ => panic!("cannot format `{}` and emit to files", filename),
         }
-        EmitMode::Stdout | EmitMode::Coverage => {
-            if config.verbose() != Verbosity::Quiet {
-                println!("{}:\n", filename);
+    }
+
+    impl From<&FileName> for rustc_span::FileName {
+        fn from(filename: &FileName) -> rustc_span::FileName {
+            match filename {
+                FileName::Real(path) => {
+                    rustc_span::FileName::Real(rustc_span::RealFileName::LocalPath(path.to_owned()))
+                }
+                FileName::Stdin => rustc_span::FileName::Custom("stdin".to_owned()),
             }
-            write!(out, "{}", formatted_text)?;
-        }
-        EmitMode::ModifiedLines => {
-            let filename = filename_to_path();
-            let ori = fs::read_to_string(filename)?;
-            let mismatch = make_diff(&ori, formatted_text, 0);
-            let has_diff = !mismatch.is_empty();
-            output_modified(out, mismatch);
-            return Ok(has_diff);
-        }
-        EmitMode::Checkstyle => {
-            let filename = filename_to_path();
-            let ori = fs::read_to_string(filename)?;
-            let diff = make_diff(&ori, formatted_text, 3);
-            output_checkstyle_file(out, filename, diff)?;
-        }
-        EmitMode::Diff => {
-            let filename = filename_to_path();
-            let ori = fs::read_to_string(filename)?;
-            let mismatch = make_diff(&ori, formatted_text, 3);
-            let has_diff = !mismatch.is_empty();
-            print_diff(
-                mismatch,
-                |line_num| format!("Diff in {} at line {}:", filename.display(), line_num),
-                config,
-            );
-            return Ok(has_diff);
         }
     }
 
-    // when we are not in diff mode, don't indicate differing files
-    Ok(false)
+    // SourceFile's in the SourceMap will always have Unix-style line endings
+    // See: https://github.com/rust-lang/rustfmt/issues/3850
+    // So if the user has explicitly overridden the rustfmt `newline_style`
+    // config and `filename` is FileName::Real, then we must check the file system
+    // to get the original file value in order to detect newline_style conflicts.
+    // Otherwise, parse session is around (cfg(not(test))) and newline_style has been
+    // left as the default value, then try getting source from the parse session
+    // source map instead of hitting the file system. This also supports getting
+    // original text for `FileName::Stdin`.
+    let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin {
+        Lrc::new(fs::read_to_string(ensure_real_path(filename))?)
+    } else {
+        match parse_sess.and_then(|sess| sess.get_original_snippet(filename)) {
+            Some(ori) => ori,
+            None => Lrc::new(fs::read_to_string(ensure_real_path(filename))?),
+        }
+    };
+
+    let formatted_file = emitter::FormattedFile {
+        filename,
+        original_text: original_text.as_str(),
+        formatted_text,
+    };
+
+    emitter.emit_formatted_file(out, formatted_file)
 }