]> git.lizzy.rs Git - rust.git/blobdiff - src/bin/rustfmt.rs
Fix a typo
[rust.git] / src / bin / rustfmt.rs
index 4d2f1cdc041c6408d86801fc29c7c3430264d075..75b45156acec6d6e7a5f8aaa937fbbd868b13839 100644 (file)
 
 #![cfg(not(test))]
 
-
-extern crate log;
-extern crate rustfmt_nightly as rustfmt;
-extern crate toml;
 extern crate env_logger;
 extern crate getopts;
-
-use rustfmt::{run, Input, Summary};
-use rustfmt::file_lines::FileLines;
-use rustfmt::config::{Config, WriteMode, get_toml_path};
+extern crate rustfmt_nightly as rustfmt;
 
 use std::{env, error};
 use std::fs::File;
 
 use getopts::{Matches, Options};
 
+use rustfmt::{run, Input, Summary};
+use rustfmt::file_lines::FileLines;
+use rustfmt::config::{get_toml_path, Color, Config, WriteMode};
+
 type FmtError = Box<error::Error + Send + Sync>;
 type FmtResult<T> = std::result::Result<T, FmtError>;
 
@@ -46,8 +43,10 @@ enum Operation {
     Version,
     /// Print detailed configuration help.
     ConfigHelp,
-    /// Output default config to a file
-    ConfigOutputDefault { path: String },
+    /// Output default config to a file, or stdout if None
+    ConfigOutputDefault {
+        path: Option<String>,
+    },
     /// No file specified, read from stdin
     Stdin {
         input: String,
@@ -61,7 +60,9 @@ struct CliOptions {
     skip_children: bool,
     verbose: bool,
     write_mode: Option<WriteMode>,
+    color: Option<Color>,
     file_lines: FileLines, // Default is all lines in all files.
+    unstable_features: bool,
 }
 
 impl CliOptions {
@@ -69,20 +70,34 @@ fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
         let mut options = CliOptions::default();
         options.skip_children = matches.opt_present("skip-children");
         options.verbose = matches.opt_present("verbose");
+        let unstable_features = matches.opt_present("unstable-features");
+        let rust_nightly = option_env!("CFG_RELEASE_CHANNEL")
+            .map(|c| c == "nightly")
+            .unwrap_or(false);
+        if unstable_features && !rust_nightly {
+            return Err(FmtError::from(
+                "Unstable features are only available on Nightly channel",
+            ));
+        } else {
+            options.unstable_features = unstable_features;
+        }
 
         if let Some(ref write_mode) = matches.opt_str("write-mode") {
             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
                 options.write_mode = Some(write_mode);
             } else {
-                return Err(FmtError::from(
-                    format!("Invalid write-mode: {}", write_mode),
-                ));
+                return Err(FmtError::from(format!(
+                    "Invalid write-mode: {}",
+                    write_mode
+                )));
+            }
+        }
+
+        if let Some(ref color) = matches.opt_str("color") {
+            match Color::from_str(color) {
+                Ok(color) => options.color = Some(color),
+                _ => return Err(FmtError::from(format!("Invalid color: {}", color))),
             }
-        } else {
-            println!(
-                "Warning: the default write-mode for Rustfmt will soon change to overwrite \
-                 - this will not leave backups of changed files."
-            );
         }
 
         if let Some(ref file_lines) = matches.opt_str("file-lines") {
@@ -96,9 +111,13 @@ fn apply_to(self, config: &mut Config) {
         config.set().skip_children(self.skip_children);
         config.set().verbose(self.verbose);
         config.set().file_lines(self.file_lines);
+        config.set().unstable_features(self.unstable_features);
         if let Some(write_mode) = self.write_mode {
             config.set().write_mode(write_mode);
         }
+        if let Some(color) = self.color {
+            config.set().color(color);
+        }
     }
 }
 
@@ -107,36 +126,53 @@ fn match_cli_path_or_file(
     config_path: Option<PathBuf>,
     input_file: &Path,
 ) -> FmtResult<(Config, Option<PathBuf>)> {
-
     if let Some(config_file) = config_path {
         let toml = Config::from_toml_path(config_file.as_ref())?;
         return Ok((toml, Some(config_file)));
     }
-    Config::from_resolved_toml_path(input_file).map_err(|e| FmtError::from(e))
+    Config::from_resolved_toml_path(input_file).map_err(FmtError::from)
 }
 
 fn make_opts() -> Options {
     let mut opts = Options::new();
-    opts.optflag("h", "help", "show this message");
-    opts.optflag("V", "version", "show version information");
-    opts.optflag("v", "verbose", "print verbose output");
-    opts.optopt(
+
+    opts.optflag("h", "help", "Show this message");
+    opts.optflag("V", "version", "Show version information");
+    opts.optflag("v", "verbose", "Print verbose output");
+    opts.optflag("", "skip-children", "Don't reformat child modules");
+    opts.optflag(
         "",
-        "write-mode",
-        "mode to write in (not usable when piping from stdin)",
-        "[replace|overwrite|display|diff|coverage|checkstyle]",
+        "unstable-features",
+        "Enables unstable features. Only available on nightly channel",
     );
-    opts.optflag("", "skip-children", "don't reformat child modules");
-
     opts.optflag(
         "",
         "config-help",
-        "show details of rustfmt configuration options",
+        "Show details of rustfmt configuration options",
+    );
+    opts.optflag(
+        "",
+        "error-on-unformatted",
+        "Error if unable to get comments or string literals within max_width, \
+         or they are left with trailing whitespaces",
+    );
+
+    opts.optopt(
+        "",
+        "write-mode",
+        "How to write output (not usable when piping from stdin)",
+        "[replace|overwrite|display|plain|diff|coverage|checkstyle]",
+    );
+    opts.optopt(
+        "",
+        "color",
+        "Use colored output (if supported)",
+        "[always|never|auto]",
     );
     opts.optopt(
         "",
         "dump-default-config",
-        "Dumps the default configuration to a file and exits.",
+        "Dumps default configuration to PATH. PATH defaults to stdout, if omitted.",
         "PATH",
     );
     opts.optopt(
@@ -167,23 +203,27 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
 
     match determine_operation(&matches)? {
         Operation::Help => {
-            print_usage(opts, "");
+            print_usage_to_stdout(opts, "");
             Summary::print_exit_codes();
-            Ok(Summary::new())
+            Ok(Summary::default())
         }
         Operation::Version => {
             print_version();
-            Ok(Summary::new())
+            Ok(Summary::default())
         }
         Operation::ConfigHelp => {
             Config::print_docs();
-            Ok(Summary::new())
+            Ok(Summary::default())
         }
         Operation::ConfigOutputDefault { path } => {
-            let mut file = File::create(path)?;
             let toml = Config::default().all_options().to_toml()?;
-            file.write_all(toml.as_bytes())?;
-            Ok(Summary::new())
+            if let Some(path) = path {
+                let mut file = File::create(path)?;
+                file.write_all(toml.as_bytes())?;
+            } else {
+                io::stdout().write_all(toml.as_bytes())?;
+            }
+            Ok(Summary::default())
         }
         Operation::Stdin { input, config_path } => {
             // try to read config from local directory
@@ -198,12 +238,17 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
                 config.set().file_lines(file_lines.parse()?);
                 for f in config.file_lines().files() {
                     if f != "stdin" {
-                        println!("Warning: Extra file listed in file_lines option '{}'", f);
+                        eprintln!("Warning: Extra file listed in file_lines option '{}'", f);
                     }
                 }
             }
 
-            Ok(run(Input::Text(input), &config))
+            let mut error_summary = Summary::default();
+            if config.version_meets_requirement(&mut error_summary) {
+                error_summary.add(run(Input::Text(input), &config));
+            }
+
+            Ok(error_summary)
         }
         Operation::Format {
             files,
@@ -214,7 +259,7 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
 
             for f in options.file_lines.files() {
                 if !files.contains(&PathBuf::from(f)) {
-                    println!("Warning: Extra file listed in file_lines option '{}'", f);
+                    eprintln!("Warning: Extra file listed in file_lines option '{}'", f);
                 }
             }
 
@@ -230,13 +275,13 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
                 }
             }
 
-            let mut error_summary = Summary::new();
+            let mut error_summary = Summary::default();
             for file in files {
                 if !file.exists() {
-                    println!("Error: file `{}` does not exist", file.to_str().unwrap());
+                    eprintln!("Error: file `{}` does not exist", file.to_str().unwrap());
                     error_summary.add_operational_error();
                 } else if file.is_dir() {
-                    println!("Error: `{}` is a directory", file.to_str().unwrap());
+                    eprintln!("Error: `{}` is a directory", file.to_str().unwrap());
                     error_summary.add_operational_error();
                 } else {
                     // Check the file directory if the config-path could not be read or not provided
@@ -255,6 +300,10 @@ fn execute(opts: &Options) -> FmtResult<Summary> {
                         config = config_tmp;
                     }
 
+                    if !config.version_meets_requirement(&mut error_summary) {
+                        break;
+                    }
+
                     options.clone().apply_to(&mut config);
                     error_summary.add(run(Input::File(file), &config));
                 }
@@ -295,7 +344,7 @@ fn main() {
             }
         }
         Err(e) => {
-            print_usage(&opts, &e.to_string());
+            print_usage_to_stderr(&opts, &e.to_string());
             1
         }
     };
@@ -309,13 +358,23 @@ fn main() {
     std::process::exit(exit_code);
 }
 
-fn print_usage(opts: &Options, reason: &str) {
-    let reason = format!(
-        "{}\n\nusage: {} [options] <file>...",
-        reason,
-        env::args_os().next().unwrap().to_string_lossy()
-    );
-    println!("{}", opts.usage(&reason));
+macro_rules! print_usage {
+    ($print:ident, $opts:ident, $reason:expr) => ({
+        let msg = format!(
+            "{}\n\nusage: {} [options] <file>...",
+            $reason,
+            env::args_os().next().unwrap().to_string_lossy()
+        );
+        $print!("{}", $opts.usage(&msg));
+    })
+}
+
+fn print_usage_to_stdout(opts: &Options, reason: &str) {
+    print_usage!(println, opts, reason);
+}
+
+fn print_usage_to_stderr(opts: &Options, reason: &str) {
+    print_usage!(eprintln, opts, reason);
 }
 
 fn print_version() {
@@ -335,8 +394,20 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
         return Ok(Operation::ConfigHelp);
     }
 
-    if let Some(path) = matches.opt_str("dump-default-config") {
-        return Ok(Operation::ConfigOutputDefault { path });
+    if matches.opt_present("dump-default-config") {
+        // NOTE for some reason when configured with HasArg::Maybe + Occur::Optional opt_default
+        // doesn't recognize `--foo bar` as a long flag with an argument but as a long flag with no
+        // argument *plus* a free argument. Thus we check for that case in this branch -- this is
+        // required for backward compatibility.
+        if let Some(path) = matches.free.get(0) {
+            return Ok(Operation::ConfigOutputDefault {
+                path: Some(path.clone()),
+            });
+        } else {
+            return Ok(Operation::ConfigOutputDefault {
+                path: matches.opt_str("dump-default-config"),
+            });
+        }
     }
 
     if matches.opt_present("version") {
@@ -362,7 +433,7 @@ fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
                 return config_path_not_found(path.to_str().unwrap());
             }
         }
-        path @ _ => path,
+        path => path,
     };
 
     // If no path is given, we won't output a minimal config.