]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
rustfmt: Add option to specify line ranges for formatting
[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
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, Input, Summary};
21 use rustfmt::file_lines::FileLines;
22 use rustfmt::config::{Config, WriteMode};
23
24 use std::{env, error};
25 use std::fs::{self, File};
26 use std::io::{self, ErrorKind, Read, Write};
27 use std::path::{Path, PathBuf};
28 use std::str::FromStr;
29
30 use getopts::{Matches, Options};
31
32 type FmtError = Box<error::Error + Send + Sync>;
33 type FmtResult<T> = std::result::Result<T, FmtError>;
34
35 /// Rustfmt operations.
36 enum Operation {
37     /// Format files and their child modules.
38     Format {
39         files: Vec<PathBuf>,
40         config_path: Option<PathBuf>,
41     },
42     /// Print the help message.
43     Help,
44     // Print version information
45     Version,
46     /// Print detailed configuration help.
47     ConfigHelp,
48     /// No file specified, read from stdin
49     Stdin {
50         input: String,
51         config_path: Option<PathBuf>,
52     },
53 }
54
55 /// Parsed command line options.
56 #[derive(Clone, Debug, Default)]
57 struct CliOptions {
58     skip_children: bool,
59     verbose: bool,
60     write_mode: Option<WriteMode>,
61     file_lines: FileLines, // Default is all lines in all files.
62 }
63
64 impl CliOptions {
65     fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
66         let mut options = CliOptions::default();
67         options.skip_children = matches.opt_present("skip-children");
68         options.verbose = matches.opt_present("verbose");
69
70         if let Some(ref write_mode) = matches.opt_str("write-mode") {
71             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
72                 options.write_mode = Some(write_mode);
73             } else {
74                 return Err(FmtError::from(format!("Invalid write-mode: {}", write_mode)));
75             }
76         }
77
78         if let Some(ref file_lines) = matches.opt_str("file-lines") {
79             options.file_lines = try!(file_lines.parse());
80         }
81
82         Ok(options)
83     }
84
85     fn apply_to(self, config: &mut Config) {
86         config.skip_children = self.skip_children;
87         config.verbose = self.verbose;
88         config.file_lines = self.file_lines;
89         if let Some(write_mode) = self.write_mode {
90             config.write_mode = write_mode;
91         }
92     }
93 }
94
95 /// Try to find a project file in the given directory and its parents. Returns the path of a the
96 /// nearest project file if one exists, or `None` if no project file was found.
97 fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
98     let mut current = if dir.is_relative() {
99         try!(env::current_dir()).join(dir)
100     } else {
101         dir.to_path_buf()
102     };
103
104     current = try!(fs::canonicalize(current));
105
106     loop {
107         let config_file = current.join("rustfmt.toml");
108         match fs::metadata(&config_file) {
109             // Only return if it's a file to handle the unlikely situation of a directory named
110             // `rustfmt.toml`.
111             Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
112             // Return the error if it's something other than `NotFound`; otherwise we didn't find
113             // the project file yet, and continue searching.
114             Err(e) => {
115                 if e.kind() != ErrorKind::NotFound {
116                     return Err(FmtError::from(e));
117                 }
118             }
119             _ => {}
120         }
121
122         // If the current directory has no parent, we're done searching.
123         if !current.pop() {
124             return Ok(None);
125         }
126     }
127 }
128
129 /// Resolve the config for input in `dir`.
130 ///
131 /// Returns the `Config` to use, and the path of the project file if there was
132 /// one.
133 fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
134     let path = try!(lookup_project_file(dir));
135     if path.is_none() {
136         return Ok((Config::default(), None));
137     }
138     let path = path.unwrap();
139     let mut file = try!(File::open(&path));
140     let mut toml = String::new();
141     try!(file.read_to_string(&mut toml));
142     Ok((Config::from_toml(&toml), Some(path)))
143 }
144
145 /// read the given config file path recursively if present else read the project file path
146 fn match_cli_path_or_file(config_path: Option<PathBuf>,
147                           input_file: &Path)
148                           -> FmtResult<(Config, Option<PathBuf>)> {
149
150     if let Some(config_file) = config_path {
151         let (toml, path) = try!(resolve_config(config_file.as_ref()));
152         if path.is_some() {
153             return Ok((toml, path));
154         }
155     }
156     resolve_config(input_file)
157 }
158
159 fn make_opts() -> Options {
160     let mut opts = Options::new();
161     opts.optflag("h", "help", "show this message");
162     opts.optflag("V", "version", "show version information");
163     opts.optflag("v", "verbose", "show progress");
164     opts.optopt("",
165                 "write-mode",
166                 "mode to write in (not usable when piping from stdin)",
167                 "[replace|overwrite|display|diff|coverage|checkstyle]");
168     opts.optflag("", "skip-children", "don't reformat child modules");
169
170     opts.optflag("",
171                  "config-help",
172                  "show details of rustfmt configuration options");
173     opts.optopt("",
174                 "config-path",
175                 "Recursively searches the given path for the rustfmt.toml config file. If not \
176                  found reverts to the input file path",
177                 "[Path for the configuration file]");
178     opts.optopt("",
179                 "file-lines",
180                 "Format specified line ranges. See README for more detail on the JSON format.",
181                 "JSON");
182
183     opts
184 }
185
186 fn execute(opts: &Options) -> FmtResult<Summary> {
187     let matches = try!(opts.parse(env::args().skip(1)));
188
189     match try!(determine_operation(&matches)) {
190         Operation::Help => {
191             print_usage(&opts, "");
192             Ok(Summary::new())
193         }
194         Operation::Version => {
195             print_version();
196             Ok(Summary::new())
197         }
198         Operation::ConfigHelp => {
199             Config::print_docs();
200             Ok(Summary::new())
201         }
202         Operation::Stdin { input, config_path } => {
203             // try to read config from local directory
204             let (mut config, _) = match_cli_path_or_file(config_path, &env::current_dir().unwrap())
205                 .expect("Error resolving config");
206
207             // write_mode is always Plain for Stdin.
208             config.write_mode = WriteMode::Plain;
209
210             Ok(run(Input::Text(input), &config))
211         }
212         Operation::Format { mut files, config_path } => {
213             let options = try!(CliOptions::from_matches(&matches));
214
215             // Add any additional files that were specified via `--file-lines`.
216             files.extend(options.file_lines.files().cloned().map(PathBuf::from));
217
218             let mut config = Config::default();
219             let mut path = None;
220             // Load the config path file if provided
221             if let Some(config_file) = config_path {
222                 let (cfg_tmp, path_tmp) = resolve_config(config_file.as_ref())
223                     .expect(&format!("Error resolving config for {:?}", config_file));
224                 config = cfg_tmp;
225                 path = path_tmp;
226             };
227             if let Some(path) = path.as_ref() {
228                 println!("Using rustfmt config file {}", path.display());
229             }
230
231             let mut error_summary = Summary::new();
232             for file in files {
233                 // Check the file directory if the config-path could not be read or not provided
234                 if path.is_none() {
235                     let (config_tmp, path_tmp) = resolve_config(file.parent().unwrap())
236                         .expect(&format!("Error resolving config for {}", file.display()));
237                     if let Some(path) = path_tmp.as_ref() {
238                         println!("Using rustfmt config file {} for {}",
239                                  path.display(),
240                                  file.display());
241                     }
242                     config = config_tmp;
243                 }
244
245                 options.clone().apply_to(&mut config);
246                 error_summary.add(run(Input::File(file), &config));
247             }
248             Ok(error_summary)
249         }
250     }
251 }
252
253 fn main() {
254     let _ = env_logger::init();
255
256     let opts = make_opts();
257
258     let exit_code = match execute(&opts) {
259         Ok(summary) => {
260             if summary.has_operational_errors() {
261                 1
262             } else if summary.has_parsing_errors() {
263                 2
264             } else if summary.has_formatting_errors() {
265                 3
266             } else {
267                 assert!(summary.has_no_errors());
268                 0
269             }
270         }
271         Err(e) => {
272             print_usage(&opts, &e.to_string());
273             1
274         }
275     };
276     // Make sure standard output is flushed before we exit.
277     std::io::stdout().flush().unwrap();
278
279     // Exit with given exit code.
280     //
281     // NOTE: This immediately terminates the process without doing any cleanup,
282     // so make sure to finish all necessary cleanup before this is called.
283     std::process::exit(exit_code);
284 }
285
286 fn print_usage(opts: &Options, reason: &str) {
287     let reason = format!("{}\nusage: {} [options] <file>...",
288                          reason,
289                          env::args_os().next().unwrap().to_string_lossy());
290     println!("{}", opts.usage(&reason));
291 }
292
293 fn print_version() {
294     println!("{}.{}.{}{}",
295              option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
296              option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
297              option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
298              option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
299 }
300
301 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
302     if matches.opt_present("h") {
303         return Ok(Operation::Help);
304     }
305
306     if matches.opt_present("config-help") {
307         return Ok(Operation::ConfigHelp);
308     }
309
310     if matches.opt_present("version") {
311         return Ok(Operation::Version);
312     }
313
314     // Read the config_path and convert to parent dir if a file is provided.
315     let config_path: Option<PathBuf> = matches.opt_str("config-path")
316         .map(PathBuf::from)
317         .and_then(|dir| {
318             if dir.is_file() {
319                 return dir.parent().map(|v| v.into());
320             }
321             Some(dir)
322         });
323
324     // if no file argument is supplied and `--file-lines` is not specified, read from stdin
325     if matches.free.is_empty() && !matches.opt_present("file-lines") {
326
327         let mut buffer = String::new();
328         try!(io::stdin().read_to_string(&mut buffer));
329
330         return Ok(Operation::Stdin {
331             input: buffer,
332             config_path: config_path,
333         });
334     }
335
336     // We append files from `--file-lines` later in `execute()`.
337     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
338
339     Ok(Operation::Format {
340         files: files,
341         config_path: config_path,
342     })
343 }