1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 extern crate env_logger;
16 extern crate rustfmt_nightly as rustfmt;
20 use std::io::{self, stdout, Read, Write};
21 use std::path::{Path, PathBuf};
25 use getopts::{Matches, Options};
28 emit_post_matter, emit_pre_matter, format_and_emit_report, load_config, CliOptions, Config,
29 FileName, FmtResult, Input, Summary, Verbosity, WriteMode, WRITE_MODE_LIST,
34 let opts = make_opts();
36 let exit_code = match execute(&opts) {
37 Ok((write_mode, summary)) => {
38 if summary.has_operational_errors()
39 || summary.has_parsing_errors()
40 || (summary.has_diff && write_mode == WriteMode::Check)
48 eprintln!("{}", e.to_string());
52 // Make sure standard output is flushed before we exit.
53 std::io::stdout().flush().unwrap();
55 // Exit with given exit code.
57 // NOTE: This immediately terminates the process without doing any cleanup,
58 // so make sure to finish all necessary cleanup before this is called.
59 std::process::exit(exit_code);
62 /// Rustfmt operations.
64 /// Format files and their child modules.
67 minimal_config_path: Option<String>,
69 /// Print the help message.
71 // Print version information
73 /// Output default config to a file, or stdout if None
77 /// No file specified, read from stdin
83 /// Arguments to `--help`
90 fn make_opts() -> Options {
91 let mut opts = Options::new();
93 // Sorted in alphabetical order.
94 opts.optflag("", "backup", "Backup any modified files.");
98 "Run in 'check' mode. Exits with 0 if input if formatted correctly. Exits \
99 with 1 and prints a diff if formatting is required.",
104 "Use colored output (if supported)",
105 "[always|never|auto]",
110 "Recursively searches the given path for the rustfmt.toml config file. If not \
111 found reverts to the input file path",
112 "[Path for the configuration file]",
114 opts.optopt("", "emit", "What data to emit and how", WRITE_MODE_LIST);
118 "Show this message or help about a specific topic: `config` or `file-lines`",
124 "Dumps a default or minimal config to PATH. A minimal config is the \
125 subset of the current config file used for formatting the current program.",
126 "[minimal|default] PATH",
128 opts.optflag("v", "verbose", "Print verbose output");
129 opts.optflag("q", "quiet", "Print less output");
130 opts.optflag("V", "version", "Show version information");
136 "Enables unstable features. Only available on nightly channel.",
140 "error-on-unformatted",
141 "Error if unable to get comments or string literals within max_width, \
142 or they are left with trailing whitespaces (unstable).",
147 "Format specified line ranges. Run with `--help file-lines` for \
148 more detail (unstable).",
154 "Don't reformat child modules (unstable).",
161 fn is_nightly() -> bool {
162 option_env!("CFG_RELEASE_CHANNEL")
163 .map(|c| c == "nightly")
167 fn execute(opts: &Options) -> FmtResult<(WriteMode, Summary)> {
168 let matches = opts.parse(env::args().skip(1))?;
169 let options = CliOptions::from_matches(&matches)?;
171 match determine_operation(&matches)? {
172 Operation::Help(HelpOp::None) => {
173 print_usage_to_stdout(opts, "");
174 Summary::print_exit_codes();
175 Ok((WriteMode::None, Summary::default()))
177 Operation::Help(HelpOp::Config) => {
178 Config::print_docs(&mut stdout(), options.unstable_features);
179 Ok((WriteMode::None, Summary::default()))
181 Operation::Help(HelpOp::FileLines) => {
182 print_help_file_lines();
183 Ok((WriteMode::None, Summary::default()))
185 Operation::Version => {
187 Ok((WriteMode::None, Summary::default()))
189 Operation::ConfigOutputDefault { path } => {
190 let toml = Config::default().all_options().to_toml().map_err(err_msg)?;
191 if let Some(path) = path {
192 let mut file = File::create(path)?;
193 file.write_all(toml.as_bytes())?;
195 io::stdout().write_all(toml.as_bytes())?;
197 Ok((WriteMode::None, Summary::default()))
199 Operation::Stdin { input } => {
200 // try to read config from local directory
201 let (mut config, _) = load_config(Some(Path::new(".")), Some(&options))?;
203 // write_mode is always Display for Stdin.
204 config.set().write_mode(WriteMode::Display);
205 config.set().verbose(Verbosity::Quiet);
208 config.set().file_lines(options.file_lines);
209 for f in config.file_lines().files() {
211 FileName::Custom(ref f) if f == "stdin" => {}
212 _ => eprintln!("Warning: Extra file listed in file_lines option '{}'", f),
216 let mut error_summary = Summary::default();
217 emit_pre_matter(&config)?;
218 match format_and_emit_report(Input::Text(input), &config) {
219 Ok(summary) => error_summary.add(summary),
220 Err(_) => error_summary.add_operational_error(),
222 emit_post_matter(&config)?;
224 Ok((WriteMode::Display, error_summary))
229 } => format(files, minimal_config_path, options),
235 minimal_config_path: Option<String>,
237 ) -> FmtResult<(WriteMode, Summary)> {
238 options.verify_file_lines(&files);
239 let (config, config_path) = load_config(None, Some(&options))?;
241 if config.verbose() == Verbosity::Verbose {
242 if let Some(path) = config_path.as_ref() {
243 println!("Using rustfmt config file {}", path.display());
247 emit_pre_matter(&config)?;
248 let mut error_summary = Summary::default();
252 eprintln!("Error: file `{}` does not exist", file.to_str().unwrap());
253 error_summary.add_operational_error();
254 } else if file.is_dir() {
255 eprintln!("Error: `{}` is a directory", file.to_str().unwrap());
256 error_summary.add_operational_error();
258 // Check the file directory if the config-path could not be read or not provided
259 let local_config = if config_path.is_none() {
260 let (local_config, config_path) =
261 load_config(Some(file.parent().unwrap()), Some(&options))?;
262 if local_config.verbose() == Verbosity::Verbose {
263 if let Some(path) = config_path {
265 "Using rustfmt config file {} for {}",
276 match format_and_emit_report(Input::File(file), &local_config) {
277 Ok(summary) => error_summary.add(summary),
279 error_summary.add_operational_error();
285 emit_post_matter(&config)?;
287 // If we were given a path via dump-minimal-config, output any options
288 // that were used during formatting as TOML.
289 if let Some(path) = minimal_config_path {
290 let mut file = File::create(path)?;
291 let toml = config.used_options().to_toml().map_err(err_msg)?;
292 file.write_all(toml.as_bytes())?;
295 Ok((config.write_mode(), error_summary))
298 fn print_usage_to_stdout(opts: &Options, reason: &str) {
299 let sep = if reason.is_empty() {
302 format!("{}\n\n", reason)
305 "{}Format Rust code\n\nusage: {} [options] <file>...",
307 env::args_os().next().unwrap().to_string_lossy()
309 println!("{}", opts.usage(&msg));
312 fn print_help_file_lines() {
314 "If you want to restrict reformatting to specific sets of lines, you can
315 use the `--file-lines` option. Its argument is a JSON array of objects
316 with `file` and `range` properties, where `file` is a file name, and
317 `range` is an array representing a range of lines like `[7,13]`. Ranges
318 are 1-based and inclusive of both end points. Specifying an empty array
319 will result in no files being formatted. For example,
322 rustfmt --file-lines '[
323 {{\"file\":\"src/lib.rs\",\"range\":[7,13]}},
324 {{\"file\":\"src/lib.rs\",\"range\":[21,29]}},
325 {{\"file\":\"src/foo.rs\",\"range\":[10,11]}},
326 {{\"file\":\"src/foo.rs\",\"range\":[15,15]}}]'
329 would format lines `7-13` and `21-29` of `src/lib.rs`, and lines `10-11`,
330 and `15` of `src/foo.rs`. No other files would be formatted, even if they
331 are included as out of line modules from `src/lib.rs`."
336 let version_info = format!(
338 option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
339 include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
342 println!("rustfmt {}", version_info);
345 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
346 if matches.opt_present("h") {
347 let topic = matches.opt_str("h");
349 return Ok(Operation::Help(HelpOp::None));
350 } else if topic == Some("config".to_owned()) {
351 return Ok(Operation::Help(HelpOp::Config));
352 } else if topic == Some("file-lines".to_owned()) {
353 return Ok(Operation::Help(HelpOp::FileLines));
355 println!("Unknown help topic: `{}`\n", topic.unwrap());
356 return Ok(Operation::Help(HelpOp::None));
360 let mut minimal_config_path = None;
361 if let Some(ref kind) = matches.opt_str("print-config") {
362 let path = matches.free.get(0).cloned();
363 if kind == "default" {
364 return Ok(Operation::ConfigOutputDefault { path });
365 } else if kind == "minimal" {
366 minimal_config_path = path;
367 if minimal_config_path.is_none() {
368 println!("WARNING: PATH required for `--print-config minimal`");
373 if matches.opt_present("version") {
374 return Ok(Operation::Version);
377 // if no file argument is supplied, read from stdin
378 if matches.free.is_empty() {
379 let mut buffer = String::new();
380 io::stdin().read_to_string(&mut buffer)?;
382 return Ok(Operation::Stdin { input: buffer });
385 let files: Vec<_> = matches
389 let p = PathBuf::from(s);
390 // we will do comparison later, so here tries to canonicalize first
391 // to get the expected behavior.
392 p.canonicalize().unwrap_or(p)
396 Ok(Operation::Format {