about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorMarcus Klaas de Vries <mail@marcusklaas.nl>2015-08-19 21:34:07 +0200
committerMarcus Klaas de Vries <mail@marcusklaas.nl>2015-08-19 21:34:07 +0200
commit2ef0b179558f85a0a0288d8fa1500732cd2512d5 (patch)
treeac2f4bc215434b04b1774644ebea3fce8ee385d5 /src
parentca651ee1acf21a97103e81c38e8e7899dc9b698a (diff)
parent10a80bb8bed24392f6f0cde6a42a7c5f2d578ab8 (diff)
Merge pull request #176 from marcusklaas/no-backup
Add an option to forgo backups
Diffstat (limited to 'src')
-rw-r--r--src/bin/rustfmt.rs28
-rw-r--r--src/filemap.rs70
-rw-r--r--src/lib.rs25
3 files changed, 84 insertions, 39 deletions
diff --git a/src/bin/rustfmt.rs b/src/bin/rustfmt.rs
index a7f65b0bee0..6ec0f9556c8 100644
--- a/src/bin/rustfmt.rs
+++ b/src/bin/rustfmt.rs
@@ -9,23 +9,47 @@
 // except according to those terms.
 
 #![cfg(not(test))]
+#![feature(result_expect)]
 
 extern crate rustfmt;
 
 use rustfmt::{WriteMode, run};
+use rustfmt::config::Config;
 
 use std::fs::File;
 use std::io::Read;
+use std::str::FromStr;
 
 fn main() {
-    let args: Vec<_> = std::env::args().collect();
     let mut def_config_file = File::open("default.toml").unwrap_or_else(|e| {
         panic!("Unable to open configuration file [default.toml] {}",e)
     });
     let mut def_config = String::new();
     def_config_file.read_to_string(&mut def_config).unwrap();
+    let config = Box::new(Config::from_toml(&def_config));
+    let (args, write_mode) = determine_params(std::env::args());
 
-    run(args, WriteMode::Overwrite, &def_config);
+    run(args, write_mode, config);
 
     std::process::exit(0);
 }
+
+fn determine_params<I>(args: I) -> (Vec<String>, WriteMode)
+    where I: Iterator<Item = String>
+{
+    let prefix = "--write-mode=";
+    let mut write_mode = WriteMode::Replace;
+
+    // The NewFile option currently isn't supported because it requires another
+    // parameter, but it can be added later.
+    let args = args.filter(|arg| {
+        if arg.starts_with(prefix) {
+            write_mode = FromStr::from_str(&arg[prefix.len()..]).expect("Unrecognized write mode");
+            false
+        } else {
+            true
+        }
+    }).collect();
+
+    (args, write_mode)
+}
diff --git a/src/filemap.rs b/src/filemap.rs
index 8e09837df0a..ff50522eec6 100644
--- a/src/filemap.rs
+++ b/src/filemap.rs
@@ -73,40 +73,46 @@ fn write_file(text: &StringBuffer,
     }
 
     match mode {
-            WriteMode::Overwrite => {
-                // 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.to_owned() + ".tmp";
-                let bk_name = filename.to_owned() + ".bk";
-                {
-                    // Write text to temp file
-                    let tmp_file = try!(File::create(&tmp_name));
-                    try!(write_system_newlines(tmp_file, text, config));
-                }
-
-                try!(fs::rename(filename, bk_name));
-                try!(fs::rename(tmp_name, filename));
-            }
-            WriteMode::NewFile(extn) => {
-                let filename = filename.to_owned() + "." + extn;
-                let file = try!(File::create(&filename));
-                try!(write_system_newlines(file, text, config));
-            }
-            WriteMode::Display => {
-                println!("{}:\n", filename);
-                let stdout = stdout();
-                let stdout_lock = stdout.lock();
-                try!(write_system_newlines(stdout_lock, text, config));
-            }
-            WriteMode::Return(_) => {
-                // io::Write is not implemented for String, working around with Vec<u8>
-                let mut v = Vec::new();
-                try!(write_system_newlines(&mut v, text, config));
-                // won't panic, we are writing correct utf8
-                return Ok(Some(String::from_utf8(v).unwrap()));
+        WriteMode::Replace => {
+            // 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.to_owned() + ".tmp";
+            let bk_name = filename.to_owned() + ".bk";
+            {
+                // Write text to temp file
+                let tmp_file = try!(File::create(&tmp_name));
+                try!(write_system_newlines(tmp_file, text, config));
             }
+
+            try!(fs::rename(filename, bk_name));
+            try!(fs::rename(tmp_name, filename));
         }
+        WriteMode::Overwrite => {
+            // Write text directly over original file.
+            let file = try!(File::create(filename));
+            try!(write_system_newlines(file, text, config));
+        }
+        WriteMode::NewFile(extn) => {
+            let filename = filename.to_owned() + "." + extn;
+            let file = try!(File::create(&filename));
+            try!(write_system_newlines(file, text, config));
+        }
+        WriteMode::Display => {
+            println!("{}:\n", filename);
+            let stdout = stdout();
+            let stdout_lock = stdout.lock();
+            try!(write_system_newlines(stdout_lock, text, config));
+        }
+        WriteMode::Return(_) => {
+            // io::Write is not implemented for String, working around with
+            // Vec<u8>
+            let mut v = Vec::new();
+            try!(write_system_newlines(&mut v, text, config));
+            // won't panic, we are writing correct utf8
+            return Ok(Some(String::from_utf8(v).unwrap()));
+        }
+    }
 
     Ok(None)
 }
diff --git a/src/lib.rs b/src/lib.rs
index c0aff9a05b3..cc7111aae27 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -42,6 +42,7 @@ use std::path::PathBuf;
 use std::collections::HashMap;
 use std::fmt;
 use std::mem::swap;
+use std::str::FromStr;
 
 use issues::{BadIssueSeeker, Issue};
 use filemap::FileMap;
@@ -71,8 +72,11 @@ const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
 
 #[derive(Copy, Clone)]
 pub enum WriteMode {
+    // Backups the original file and overwrites the orignal.
+    Replace,
+    // Overwrites original file without backup.
     Overwrite,
-    // str is the extension of the new file
+    // str is the extension of the new file.
     NewFile(&'static str),
     // Write the output to stdout.
     Display,
@@ -80,6 +84,19 @@ pub enum WriteMode {
     Return(&'static Fn(HashMap<String, String>)),
 }
 
+impl FromStr for WriteMode {
+    type Err = ();
+
+    fn from_str(s: &str) -> Result<Self, Self::Err> {
+        match s {
+            "replace" => Ok(WriteMode::Replace),
+            "display" => Ok(WriteMode::Display),
+            "overwrite" => Ok(WriteMode::Overwrite),
+            _ => Err(())
+        }
+    }
+}
+
 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
 pub enum NewlineStyle {
     Windows, // \r\n
@@ -343,9 +360,7 @@ impl<'a> CompilerCalls<'a> for RustFmtCalls {
 // to the compiler.
 // write_mode determines what happens to the result of running rustfmt, see
 // WriteMode.
-// default_config is a string of toml data to be used to configure rustfmt.
-pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
-    let config = Some(Box::new(config::Config::from_toml(default_config)));
-    let mut call_ctxt = RustFmtCalls { write_mode: write_mode, config: config };
+pub fn run(args: Vec<String>, write_mode: WriteMode, config: Box<Config>) {
+    let mut call_ctxt = RustFmtCalls { write_mode: write_mode, config: Some(config) };
     rustc_driver::run_compiler(&args, &mut call_ctxt);
 }