]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
Merge pull request #745 from markstory/checkstyle-output
[rust.git] / src / bin / rustfmt.rs
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.
4 //
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.
10
11 #![cfg(not(test))]
12
13 #[macro_use]
14 extern crate log;
15 extern crate rustfmt;
16 extern crate toml;
17 extern crate env_logger;
18 extern crate getopts;
19
20 use rustfmt::{run, run_from_stdin};
21 use rustfmt::config::{Config, WriteMode};
22
23 use std::env;
24 use std::fs::{self, File};
25 use std::io::{self, Read, Write};
26 use std::path::{Path, PathBuf};
27
28 use getopts::{Matches, Options};
29
30 /// Rustfmt operations.
31 enum Operation {
32     /// Format files and their child modules.
33     Format(Vec<PathBuf>, WriteMode),
34     /// Print the help message.
35     Help,
36     // Print version information
37     Version,
38     /// Print detailed configuration help.
39     ConfigHelp,
40     /// Invalid program input, including reason.
41     InvalidInput(String),
42     /// No file specified, read from stdin
43     Stdin(String, WriteMode),
44 }
45
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)
50     } else {
51         input_file.to_path_buf()
52     };
53
54     // FIXME: We should canonize path to properly handle its parents,
55     // but `canonicalize` function is unstable now (recently added API)
56     // current = try!(fs::canonicalize(current));
57
58     loop {
59         let config_file = current.join("rustfmt.toml");
60         if fs::metadata(&config_file).is_ok() {
61             return Ok(config_file);
62         }
63
64         // If the current directory has no parent, we're done searching.
65         if !current.pop() {
66             return Err(io::Error::new(io::ErrorKind::NotFound, "Config not found"));
67         }
68     }
69 }
70
71 /// Try to find a project file. If it's found, read it.
72 fn lookup_and_read_project_file(input_file: &Path) -> io::Result<(PathBuf, String)> {
73     let path = try!(lookup_project_file(input_file));
74     let mut file = try!(File::open(&path));
75     let mut toml = String::new();
76     try!(file.read_to_string(&mut toml));
77     Ok((path, toml))
78 }
79
80 fn update_config(config: &mut Config, matches: &Matches) {
81     config.verbose = matches.opt_present("verbose");
82     config.skip_children = matches.opt_present("skip-children");
83 }
84
85 fn execute() -> i32 {
86     let mut opts = Options::new();
87     opts.optflag("h", "help", "show this message");
88     opts.optflag("V", "version", "show version information");
89     opts.optflag("v", "verbose", "show progress");
90     opts.optopt("",
91                 "write-mode",
92                 "mode to write in (not usable when piping from stdin)",
93                 "[replace|overwrite|display|diff|coverage|checkstyle]");
94     opts.optflag("", "skip-children", "don't reformat child modules");
95
96     opts.optflag("",
97                  "config-help",
98                  "show details of rustfmt configuration options");
99
100     let matches = match opts.parse(env::args().skip(1)) {
101         Ok(m) => m,
102         Err(e) => {
103             print_usage(&opts, &e.to_string());
104             return 1;
105         }
106     };
107
108     let operation = determine_operation(&matches);
109
110     match operation {
111         Operation::InvalidInput(reason) => {
112             print_usage(&opts, &reason);
113             1
114         }
115         Operation::Help => {
116             print_usage(&opts, "");
117             0
118         }
119         Operation::Version => {
120             print_version();
121             0
122         }
123         Operation::ConfigHelp => {
124             Config::print_docs();
125             0
126         }
127         Operation::Stdin(input, write_mode) => {
128             // try to read config from local directory
129             let config = match lookup_and_read_project_file(&Path::new(".")) {
130                 Ok((_, toml)) => Config::from_toml(&toml),
131                 Err(_) => Default::default(),
132             };
133
134             run_from_stdin(input, write_mode, &config);
135             0
136         }
137         Operation::Format(files, write_mode) => {
138             for file in files {
139                 let mut config = match lookup_and_read_project_file(&file) {
140                     Ok((path, toml)) => {
141                         println!("Using rustfmt config file {} for {}",
142                                  path.display(),
143                                  file.display());
144                         Config::from_toml(&toml)
145                     }
146                     Err(_) => Default::default(),
147                 };
148
149                 update_config(&mut config, &matches);
150                 run(&file, write_mode, &config);
151             }
152             0
153         }
154     }
155 }
156
157 fn main() {
158     let _ = env_logger::init();
159     let exit_code = execute();
160
161     // Make sure standard output is flushed before we exit.
162     std::io::stdout().flush().unwrap();
163
164     // Exit with given exit code.
165     //
166     // NOTE: This immediately terminates the process without doing any cleanup,
167     // so make sure to finish all necessary cleanup before this is called.
168     std::process::exit(exit_code);
169 }
170
171 fn print_usage(opts: &Options, reason: &str) {
172     let reason = format!("{}\nusage: {} [options] <file>...",
173                          reason,
174                          env::args_os().next().unwrap().to_string_lossy());
175     println!("{}", opts.usage(&reason));
176 }
177
178 fn print_version() {
179     println!("{}.{}.{}{}",
180              option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
181              option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
182              option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
183              option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
184 }
185
186 fn determine_operation(matches: &Matches) -> Operation {
187     if matches.opt_present("h") {
188         return Operation::Help;
189     }
190
191     if matches.opt_present("config-help") {
192         return Operation::ConfigHelp;
193     }
194
195     if matches.opt_present("version") {
196         return Operation::Version;
197     }
198
199     // if no file argument is supplied, read from stdin
200     if matches.free.is_empty() {
201
202         let mut buffer = String::new();
203         match io::stdin().read_to_string(&mut buffer) {
204             Ok(..) => (),
205             Err(e) => return Operation::InvalidInput(e.to_string()),
206         }
207
208         // WriteMode is always plain for Stdin
209         return Operation::Stdin(buffer, WriteMode::Plain);
210     }
211
212     let write_mode = match matches.opt_str("write-mode") {
213         Some(mode) => {
214             match mode.parse() {
215                 Ok(mode) => mode,
216                 Err(..) => return Operation::InvalidInput("Unrecognized write mode".into()),
217             }
218         }
219         None => WriteMode::Default,
220     };
221
222     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
223
224     Operation::Format(files, write_mode)
225 }