]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
Merge pull request #799 from kamalmarhubi/const-instead-of-static
[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, ErrorKind, 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, Option<PathBuf>),
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, Option<PathBuf>),
44 }
45
46 /// Try to find a project file in the given directory and its parents. Returns the path of a the
47 /// nearest project file if one exists, or `None` if no project file was found.
48 fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
49     let mut current = if dir.is_relative() {
50         try!(env::current_dir()).join(dir)
51     } else {
52         dir.to_path_buf()
53     };
54
55     current = try!(fs::canonicalize(current));
56
57     loop {
58         let config_file = current.join("rustfmt.toml");
59         match fs::metadata(&config_file) {
60             Ok(md) => {
61                 // Properly handle unlikely situation of a directory named `rustfmt.toml`.
62                 if md.is_file() {
63                     return Ok(Some(config_file));
64                 }
65             }
66             // If it's not found, we continue searching; otherwise something went wrong and we
67             // return the error.
68             Err(e) => {
69                 if e.kind() != ErrorKind::NotFound {
70                     return Err(e);
71                 }
72             }
73         }
74
75         // If the current directory has no parent, we're done searching.
76         if !current.pop() {
77             return Ok(None);
78         }
79     }
80 }
81
82 /// Resolve the config for input in `dir`.
83 ///
84 /// Returns the `Config` to use, and the path of the project file if there was
85 /// one.
86 fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
87     let path = try!(lookup_project_file(dir));
88     if path.is_none() {
89         return Ok((Config::default(), None));
90     }
91     let path = path.unwrap();
92     let mut file = try!(File::open(&path));
93     let mut toml = String::new();
94     try!(file.read_to_string(&mut toml));
95     Ok((Config::from_toml(&toml), Some(path)))
96 }
97
98 /// read the given config file path recursively if present else read the project file path
99 fn match_cli_path_or_file(config_path: Option<PathBuf>,
100                           input_file: &Path)
101                           -> io::Result<(Config, Option<PathBuf>)> {
102
103     if let Some(config_file) = config_path {
104         let (toml, path) = try!(resolve_config(config_file.as_ref()));
105         if path.is_some() {
106             return Ok((toml, path));
107         }
108     }
109     resolve_config(input_file)
110 }
111
112 fn update_config(config: &mut Config, matches: &Matches) {
113     config.verbose = matches.opt_present("verbose");
114     config.skip_children = matches.opt_present("skip-children");
115 }
116
117 fn execute() -> i32 {
118     let mut opts = Options::new();
119     opts.optflag("h", "help", "show this message");
120     opts.optflag("V", "version", "show version information");
121     opts.optflag("v", "verbose", "show progress");
122     opts.optopt("",
123                 "write-mode",
124                 "mode to write in (not usable when piping from stdin)",
125                 "[replace|overwrite|display|diff|coverage|checkstyle]");
126     opts.optflag("", "skip-children", "don't reformat child modules");
127
128     opts.optflag("",
129                  "config-help",
130                  "show details of rustfmt configuration options");
131     opts.optopt("",
132                 "config-path",
133                 "Recursively searches the given path for the rustfmt.toml config file. If not \
134                  found reverts to the input file path",
135                 "[Path for the configuration file]");
136
137     let matches = match opts.parse(env::args().skip(1)) {
138         Ok(m) => m,
139         Err(e) => {
140             print_usage(&opts, &e.to_string());
141             return 1;
142         }
143     };
144
145     let operation = determine_operation(&matches);
146
147     match operation {
148         Operation::InvalidInput(reason) => {
149             print_usage(&opts, &reason);
150             1
151         }
152         Operation::Help => {
153             print_usage(&opts, "");
154             0
155         }
156         Operation::Version => {
157             print_version();
158             0
159         }
160         Operation::ConfigHelp => {
161             Config::print_docs();
162             0
163         }
164         Operation::Stdin(input, write_mode, config_path) => {
165             // try to read config from local directory
166             let (config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
167                                   .expect("Error resolving config");
168
169             run_from_stdin(input, write_mode, &config);
170             0
171         }
172         Operation::Format(files, write_mode, config_path) => {
173             let mut config = Config::default();
174             let mut path = None;
175             // Load the config path file if provided
176             if let Some(config_file) = config_path {
177                 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
178                                               .expect(&format!("Error resolving config for {:?}",
179                                                                config_file));
180                 config = cfg_tmp;
181                 path = path_tmp;
182             };
183             if let Some(path) = path.as_ref() {
184                 println!("Using rustfmt config file {}", path.display());
185             }
186             for file in files {
187                 // Check the file directory if the config-path could not be read or not provided
188                 if path.is_none() {
189                     let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
190                                                      .expect(&format!("Error resolving config \
191                                                                        for {}",
192                                                                       file.display()));
193                     if let Some(path) = path_tmp.as_ref() {
194                         println!("Using rustfmt config file {} for {}",
195                                  path.display(),
196                                  file.display());
197                     }
198                     config = config_tmp;
199                 }
200
201                 update_config(&mut config, &matches);
202                 run(&file, write_mode, &config);
203             }
204             0
205         }
206     }
207 }
208
209 fn main() {
210     let _ = env_logger::init();
211     let exit_code = execute();
212
213     // Make sure standard output is flushed before we exit.
214     std::io::stdout().flush().unwrap();
215
216     // Exit with given exit code.
217     //
218     // NOTE: This immediately terminates the process without doing any cleanup,
219     // so make sure to finish all necessary cleanup before this is called.
220     std::process::exit(exit_code);
221 }
222
223 fn print_usage(opts: &Options, reason: &str) {
224     let reason = format!("{}\nusage: {} [options] <file>...",
225                          reason,
226                          env::args_os().next().unwrap().to_string_lossy());
227     println!("{}", opts.usage(&reason));
228 }
229
230 fn print_version() {
231     println!("{}.{}.{}{}",
232              option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
233              option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
234              option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
235              option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
236 }
237
238 fn determine_operation(matches: &Matches) -> Operation {
239     if matches.opt_present("h") {
240         return Operation::Help;
241     }
242
243     if matches.opt_present("config-help") {
244         return Operation::ConfigHelp;
245     }
246
247     if matches.opt_present("version") {
248         return Operation::Version;
249     }
250
251     // Read the config_path and convert to parent dir if a file is provided.
252     let config_path: Option<PathBuf> = matches.opt_str("config-path")
253                                               .map(PathBuf::from)
254                                               .and_then(|dir| {
255                                                   if dir.is_file() {
256                                                       return dir.parent().map(|v| v.into());
257                                                   }
258                                                   Some(dir)
259                                               });
260
261     // if no file argument is supplied, read from stdin
262     if matches.free.is_empty() {
263
264         let mut buffer = String::new();
265         match io::stdin().read_to_string(&mut buffer) {
266             Ok(..) => (),
267             Err(e) => return Operation::InvalidInput(e.to_string()),
268         }
269
270         // WriteMode is always plain for Stdin
271         return Operation::Stdin(buffer, WriteMode::Plain, config_path);
272     }
273
274     let write_mode = match matches.opt_str("write-mode") {
275         Some(mode) => {
276             match mode.parse() {
277                 Ok(mode) => mode,
278                 Err(..) => return Operation::InvalidInput("Unrecognized write mode".into()),
279             }
280         }
281         None => WriteMode::Default,
282     };
283
284     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
285
286     Operation::Format(files, write_mode, config_path)
287 }