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.
14 extern crate env_logger;
16 extern crate rustfmt_nightly as rustfmt;
18 use std::{env, error};
20 use std::io::{self, Read, Write};
21 use std::path::{Path, PathBuf};
22 use std::str::FromStr;
24 use getopts::{Matches, Options};
26 use rustfmt::{run, Input, Summary};
27 use rustfmt::file_lines::FileLines;
28 use rustfmt::config::{get_toml_path, Config, WriteMode};
30 type FmtError = Box<error::Error + Send + Sync>;
31 type FmtResult<T> = std::result::Result<T, FmtError>;
33 /// Rustfmt operations.
35 /// Format files and their child modules.
38 config_path: Option<PathBuf>,
39 minimal_config_path: Option<String>,
41 /// Print the help message.
43 // Print version information
45 /// Print detailed configuration help.
47 /// Output default config to a file
48 ConfigOutputDefault { path: String },
49 /// No file specified, read from stdin
52 config_path: Option<PathBuf>,
56 /// Parsed command line options.
57 #[derive(Clone, Debug, Default)]
61 write_mode: Option<WriteMode>,
62 file_lines: FileLines, // Default is all lines in all files.
66 fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
67 let mut options = CliOptions::default();
68 options.skip_children = matches.opt_present("skip-children");
69 options.verbose = matches.opt_present("verbose");
71 if let Some(ref write_mode) = matches.opt_str("write-mode") {
72 if let Ok(write_mode) = WriteMode::from_str(write_mode) {
73 options.write_mode = Some(write_mode);
75 return Err(FmtError::from(
76 format!("Invalid write-mode: {}", write_mode),
81 if let Some(ref file_lines) = matches.opt_str("file-lines") {
82 options.file_lines = file_lines.parse()?;
88 fn apply_to(self, config: &mut Config) {
89 config.set().skip_children(self.skip_children);
90 config.set().verbose(self.verbose);
91 config.set().file_lines(self.file_lines);
92 if let Some(write_mode) = self.write_mode {
93 config.set().write_mode(write_mode);
98 /// read the given config file path recursively if present else read the project file path
99 fn match_cli_path_or_file(
100 config_path: Option<PathBuf>,
102 ) -> FmtResult<(Config, Option<PathBuf>)> {
103 if let Some(config_file) = config_path {
104 let toml = Config::from_toml_path(config_file.as_ref())?;
105 return Ok((toml, Some(config_file)));
107 Config::from_resolved_toml_path(input_file).map_err(FmtError::from)
110 fn make_opts() -> Options {
111 let mut opts = Options::new();
112 opts.optflag("h", "help", "show this message");
113 opts.optflag("V", "version", "show version information");
114 opts.optflag("v", "verbose", "print verbose output");
118 "how to write output (not usable when piping from stdin)",
119 "[replace|overwrite|display|plain|diff|coverage|checkstyle]",
121 opts.optflag("", "skip-children", "don't reformat child modules");
126 "show details of rustfmt configuration options",
130 "dump-default-config",
131 "Dumps the default configuration to a file and exits.",
136 "dump-minimal-config",
137 "Dumps configuration options that were checked during formatting to a file.",
143 "Recursively searches the given path for the rustfmt.toml config file. If not \
144 found reverts to the input file path",
145 "[Path for the configuration file]",
150 "Format specified line ranges. See README for more detail on the JSON format.",
157 fn execute(opts: &Options) -> FmtResult<Summary> {
158 let matches = opts.parse(env::args().skip(1))?;
160 match determine_operation(&matches)? {
162 print_usage(opts, "");
163 Summary::print_exit_codes();
164 Ok(Summary::default())
166 Operation::Version => {
168 Ok(Summary::default())
170 Operation::ConfigHelp => {
171 Config::print_docs();
172 Ok(Summary::default())
174 Operation::ConfigOutputDefault { path } => {
175 let mut file = File::create(path)?;
176 let toml = Config::default().all_options().to_toml()?;
177 file.write_all(toml.as_bytes())?;
178 Ok(Summary::default())
180 Operation::Stdin { input, config_path } => {
181 // try to read config from local directory
182 let (mut config, _) =
183 match_cli_path_or_file(config_path, &env::current_dir().unwrap())?;
185 // write_mode is always Plain for Stdin.
186 config.set().write_mode(WriteMode::Plain);
189 if let Some(ref file_lines) = matches.opt_str("file-lines") {
190 config.set().file_lines(file_lines.parse()?);
191 for f in config.file_lines().files() {
193 println!("Warning: Extra file listed in file_lines option '{}'", f);
198 Ok(run(Input::Text(input), &config))
205 let options = CliOptions::from_matches(&matches)?;
207 for f in options.file_lines.files() {
208 if !files.contains(&PathBuf::from(f)) {
209 println!("Warning: Extra file listed in file_lines option '{}'", f);
213 let mut config = Config::default();
214 // Load the config path file if provided
215 if let Some(config_file) = config_path.as_ref() {
216 config = Config::from_toml_path(config_file.as_ref())?;
220 if let Some(path) = config_path.as_ref() {
221 println!("Using rustfmt config file {}", path.display());
225 let mut error_summary = Summary::default();
228 println!("Error: file `{}` does not exist", file.to_str().unwrap());
229 error_summary.add_operational_error();
230 } else if file.is_dir() {
231 println!("Error: `{}` is a directory", file.to_str().unwrap());
232 error_summary.add_operational_error();
234 // Check the file directory if the config-path could not be read or not provided
235 if config_path.is_none() {
236 let (config_tmp, path_tmp) =
237 Config::from_resolved_toml_path(file.parent().unwrap())?;
239 if let Some(path) = path_tmp.as_ref() {
241 "Using rustfmt config file {} for {}",
250 options.clone().apply_to(&mut config);
251 error_summary.add(run(Input::File(file), &config));
255 // If we were given a path via dump-minimal-config, output any options
256 // that were used during formatting as TOML.
257 if let Some(path) = minimal_config_path {
258 let mut file = File::create(path)?;
259 let toml = config.used_options().to_toml()?;
260 file.write_all(toml.as_bytes())?;
269 let _ = env_logger::init();
271 let opts = make_opts();
273 let exit_code = match execute(&opts) {
275 if summary.has_operational_errors() {
277 } else if summary.has_parsing_errors() {
279 } else if summary.has_formatting_errors() {
281 } else if summary.has_diff {
282 // should only happen in diff mode
285 assert!(summary.has_no_errors());
290 print_usage(&opts, &e.to_string());
294 // Make sure standard output is flushed before we exit.
295 std::io::stdout().flush().unwrap();
297 // Exit with given exit code.
299 // NOTE: This immediately terminates the process without doing any cleanup,
300 // so make sure to finish all necessary cleanup before this is called.
301 std::process::exit(exit_code);
304 fn print_usage(opts: &Options, reason: &str) {
305 let reason = format!(
306 "{}\n\nusage: {} [options] <file>...",
308 env::args_os().next().unwrap().to_string_lossy()
310 println!("{}", opts.usage(&reason));
316 env!("CARGO_PKG_VERSION"),
317 include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
321 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
322 if matches.opt_present("h") {
323 return Ok(Operation::Help);
326 if matches.opt_present("config-help") {
327 return Ok(Operation::ConfigHelp);
330 if let Some(path) = matches.opt_str("dump-default-config") {
331 return Ok(Operation::ConfigOutputDefault { path });
334 if matches.opt_present("version") {
335 return Ok(Operation::Version);
338 let config_path_not_found = |path: &str| -> FmtResult<Operation> {
339 Err(FmtError::from(format!(
340 "Error: unable to find a config file for the given path: `{}`",
345 // Read the config_path and convert to parent dir if a file is provided.
346 // If a config file cannot be found from the given path, return error.
347 let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
348 Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
349 Some(ref path) if path.is_dir() => {
350 let config_file_path = get_toml_path(path)?;
351 if config_file_path.is_some() {
354 return config_path_not_found(path.to_str().unwrap());
360 // If no path is given, we won't output a minimal config.
361 let minimal_config_path = matches.opt_str("dump-minimal-config");
363 // if no file argument is supplied, read from stdin
364 if matches.free.is_empty() {
365 let mut buffer = String::new();
366 io::stdin().read_to_string(&mut buffer)?;
368 return Ok(Operation::Stdin {
370 config_path: config_path,
374 let files: Vec<_> = matches
378 let p = PathBuf::from(s);
379 // we will do comparison later, so here tries to canonicalize first
380 // to get the expected behavior.
381 p.canonicalize().unwrap_or(p)
385 Ok(Operation::Format {
387 config_path: config_path,
388 minimal_config_path: minimal_config_path,