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.
17 extern crate env_logger;
20 use rustfmt::{run, run_from_stdin};
21 use rustfmt::config::{Config, WriteMode};
24 use std::fs::{self, File};
25 use std::io::{self, Read, Write};
26 use std::path::{Path, PathBuf};
28 use getopts::{Matches, Options};
30 /// Rustfmt operations.
32 /// Format files and their child modules.
33 Format(Vec<PathBuf>, WriteMode),
34 /// Print the help message.
36 // Print version information
38 /// Print detailed configuration help.
40 /// Invalid program input, including reason.
42 /// No file specified, read from stdin
43 Stdin(String, WriteMode),
46 /// Try to find a project file in the input file directory and its parents.
47 fn lookup_project_file(input_file: &Path) -> io::Result<PathBuf> {
48 let mut current = if input_file.is_relative() {
49 try!(env::current_dir()).join(input_file)
51 input_file.to_path_buf()
54 current = try!(fs::canonicalize(current));
57 let config_file = current.join("rustfmt.toml");
58 if let Ok(md) = fs::metadata(&config_file) {
59 // Properly handle unlikely situation of a directory named `rustfmt.toml`.
61 return Ok(config_file);
65 // If the current directory has no parent, we're done searching.
67 return Err(io::Error::new(io::ErrorKind::NotFound, "Config not found"));
72 /// Try to find a project file. If it's found, read it.
73 fn lookup_and_read_project_file(input_file: &Path) -> io::Result<(PathBuf, String)> {
74 let path = try!(lookup_project_file(input_file));
75 let mut file = try!(File::open(&path));
76 let mut toml = String::new();
77 try!(file.read_to_string(&mut toml));
81 fn update_config(config: &mut Config, matches: &Matches) {
82 config.verbose = matches.opt_present("verbose");
83 config.skip_children = matches.opt_present("skip-children");
87 let mut opts = Options::new();
88 opts.optflag("h", "help", "show this message");
89 opts.optflag("V", "version", "show version information");
90 opts.optflag("v", "verbose", "show progress");
93 "mode to write in (not usable when piping from stdin)",
94 "[replace|overwrite|display|diff|coverage|checkstyle]");
95 opts.optflag("", "skip-children", "don't reformat child modules");
99 "show details of rustfmt configuration options");
101 let matches = match opts.parse(env::args().skip(1)) {
104 print_usage(&opts, &e.to_string());
109 let operation = determine_operation(&matches);
112 Operation::InvalidInput(reason) => {
113 print_usage(&opts, &reason);
117 print_usage(&opts, "");
120 Operation::Version => {
124 Operation::ConfigHelp => {
125 Config::print_docs();
128 Operation::Stdin(input, write_mode) => {
129 // try to read config from local directory
130 let config = match lookup_and_read_project_file(&Path::new(".")) {
131 Ok((_, toml)) => Config::from_toml(&toml),
132 Err(_) => Default::default(),
135 run_from_stdin(input, write_mode, &config);
138 Operation::Format(files, write_mode) => {
140 let mut config = match lookup_and_read_project_file(&file) {
141 Ok((path, toml)) => {
142 println!("Using rustfmt config file {} for {}",
145 Config::from_toml(&toml)
147 Err(_) => Default::default(),
150 update_config(&mut config, &matches);
151 run(&file, write_mode, &config);
159 let _ = env_logger::init();
160 let exit_code = execute();
162 // Make sure standard output is flushed before we exit.
163 std::io::stdout().flush().unwrap();
165 // Exit with given exit code.
167 // NOTE: This immediately terminates the process without doing any cleanup,
168 // so make sure to finish all necessary cleanup before this is called.
169 std::process::exit(exit_code);
172 fn print_usage(opts: &Options, reason: &str) {
173 let reason = format!("{}\nusage: {} [options] <file>...",
175 env::args_os().next().unwrap().to_string_lossy());
176 println!("{}", opts.usage(&reason));
180 println!("{}.{}.{}{}",
181 option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
182 option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
183 option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
184 option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
187 fn determine_operation(matches: &Matches) -> Operation {
188 if matches.opt_present("h") {
189 return Operation::Help;
192 if matches.opt_present("config-help") {
193 return Operation::ConfigHelp;
196 if matches.opt_present("version") {
197 return Operation::Version;
200 // if no file argument is supplied, read from stdin
201 if matches.free.is_empty() {
203 let mut buffer = String::new();
204 match io::stdin().read_to_string(&mut buffer) {
206 Err(e) => return Operation::InvalidInput(e.to_string()),
209 // WriteMode is always plain for Stdin
210 return Operation::Stdin(buffer, WriteMode::Plain);
213 let write_mode = match matches.opt_str("write-mode") {
217 Err(..) => return Operation::InvalidInput("Unrecognized write mode".into()),
220 None => WriteMode::Default,
223 let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
225 Operation::Format(files, write_mode)