]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
Merge pull request #1724 from topecongiro/multiline-string-lit
[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_nightly as 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, get_toml_path};
23
24 use std::{env, error};
25 use std::fs::File;
26 use std::io::{self, 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         minimal_config_path: Option<String>,
42     },
43     /// Print the help message.
44     Help,
45     // Print version information
46     Version,
47     /// Print detailed configuration help.
48     ConfigHelp,
49     /// Output default config to a file
50     ConfigOutputDefault { path: String },
51     /// No file specified, read from stdin
52     Stdin {
53         input: String,
54         config_path: Option<PathBuf>,
55     },
56 }
57
58 /// Parsed command line options.
59 #[derive(Clone, Debug, Default)]
60 struct CliOptions {
61     skip_children: bool,
62     verbose: bool,
63     write_mode: Option<WriteMode>,
64     file_lines: FileLines, // Default is all lines in all files.
65 }
66
67 impl CliOptions {
68     fn from_matches(matches: &Matches) -> FmtResult<CliOptions> {
69         let mut options = CliOptions::default();
70         options.skip_children = matches.opt_present("skip-children");
71         options.verbose = matches.opt_present("verbose");
72
73         if let Some(ref write_mode) = matches.opt_str("write-mode") {
74             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
75                 options.write_mode = Some(write_mode);
76             } else {
77                 return Err(FmtError::from(
78                     format!("Invalid write-mode: {}", write_mode),
79                 ));
80             }
81         }
82
83         if let Some(ref file_lines) = matches.opt_str("file-lines") {
84             options.file_lines = file_lines.parse()?;
85         }
86
87         Ok(options)
88     }
89
90     fn apply_to(self, config: &mut Config) {
91         config.set().skip_children(self.skip_children);
92         config.set().verbose(self.verbose);
93         config.set().file_lines(self.file_lines);
94         if let Some(write_mode) = self.write_mode {
95             config.set().write_mode(write_mode);
96         }
97     }
98 }
99
100 /// read the given config file path recursively if present else read the project file path
101 fn match_cli_path_or_file(
102     config_path: Option<PathBuf>,
103     input_file: &Path,
104 ) -> FmtResult<(Config, Option<PathBuf>)> {
105
106     if let Some(config_file) = config_path {
107         let toml = Config::from_toml_path(config_file.as_ref())?;
108         return Ok((toml, Some(config_file)));
109     }
110     Config::from_resolved_toml_path(input_file).map_err(|e| FmtError::from(e))
111 }
112
113 fn make_opts() -> Options {
114     let mut opts = Options::new();
115     opts.optflag("h", "help", "show this message");
116     opts.optflag("V", "version", "show version information");
117     opts.optflag("v", "verbose", "print verbose output");
118     opts.optopt(
119         "",
120         "write-mode",
121         "mode to write in (not usable when piping from stdin)",
122         "[replace|overwrite|display|diff|coverage|checkstyle]",
123     );
124     opts.optflag("", "skip-children", "don't reformat child modules");
125
126     opts.optflag(
127         "",
128         "config-help",
129         "show details of rustfmt configuration options",
130     );
131     opts.optopt(
132         "",
133         "dump-default-config",
134         "Dumps the default configuration to a file and exits.",
135         "PATH",
136     );
137     opts.optopt(
138         "",
139         "dump-minimal-config",
140         "Dumps configuration options that were checked during formatting to a file.",
141         "PATH",
142     );
143     opts.optopt(
144         "",
145         "config-path",
146         "Recursively searches the given path for the rustfmt.toml config file. If not \
147          found reverts to the input file path",
148         "[Path for the configuration file]",
149     );
150     opts.optopt(
151         "",
152         "file-lines",
153         "Format specified line ranges. See README for more detail on the JSON format.",
154         "JSON",
155     );
156
157     opts
158 }
159
160 fn execute(opts: &Options) -> FmtResult<Summary> {
161     let matches = opts.parse(env::args().skip(1))?;
162
163     match determine_operation(&matches)? {
164         Operation::Help => {
165             print_usage(opts, "");
166             Summary::print_exit_codes();
167             Ok(Summary::new())
168         }
169         Operation::Version => {
170             print_version();
171             Ok(Summary::new())
172         }
173         Operation::ConfigHelp => {
174             Config::print_docs();
175             Ok(Summary::new())
176         }
177         Operation::ConfigOutputDefault { path } => {
178             let mut file = File::create(path)?;
179             let toml = Config::default().all_options().to_toml()?;
180             file.write_all(toml.as_bytes())?;
181             Ok(Summary::new())
182         }
183         Operation::Stdin { input, config_path } => {
184             // try to read config from local directory
185             let (mut config, _) =
186                 match_cli_path_or_file(config_path, &env::current_dir().unwrap())?;
187
188             // write_mode is always Plain for Stdin.
189             config.set().write_mode(WriteMode::Plain);
190
191             // parse file_lines
192             if let Some(ref file_lines) = matches.opt_str("file-lines") {
193                 config.set().file_lines(file_lines.parse()?);
194                 for f in config.file_lines().files() {
195                     if f != "stdin" {
196                         println!("Warning: Extra file listed in file_lines option '{}'", f);
197                     }
198                 }
199             }
200
201             Ok(run(Input::Text(input), &config))
202         }
203         Operation::Format {
204             files,
205             config_path,
206             minimal_config_path,
207         } => {
208             let options = CliOptions::from_matches(&matches)?;
209
210             for f in options.file_lines.files() {
211                 if !files.contains(&PathBuf::from(f)) {
212                     println!("Warning: Extra file listed in file_lines option '{}'", f);
213                 }
214             }
215
216             let mut config = Config::default();
217             // Load the config path file if provided
218             if let Some(config_file) = config_path.as_ref() {
219                 config = Config::from_toml_path(config_file.as_ref())?;
220             };
221
222             if options.verbose {
223                 if let Some(path) = config_path.as_ref() {
224                     println!("Using rustfmt config file {}", path.display());
225                 }
226             }
227
228             let mut error_summary = Summary::new();
229             for file in files {
230                 if !file.exists() {
231                     println!("Error: file `{}` does not exist", file.to_str().unwrap());
232                     error_summary.add_operational_error();
233                 } else if file.is_dir() {
234                     println!("Error: `{}` is a directory", file.to_str().unwrap());
235                     error_summary.add_operational_error();
236                 } else {
237                     // Check the file directory if the config-path could not be read or not provided
238                     if config_path.is_none() {
239                         let (config_tmp, path_tmp) =
240                             Config::from_resolved_toml_path(file.parent().unwrap())?;
241                         if options.verbose {
242                             if let Some(path) = path_tmp.as_ref() {
243                                 println!(
244                                     "Using rustfmt config file {} for {}",
245                                     path.display(),
246                                     file.display()
247                                 );
248                             }
249                         }
250                         config = config_tmp;
251                     }
252
253                     options.clone().apply_to(&mut config);
254                     error_summary.add(run(Input::File(file), &config));
255                 }
256             }
257
258             // If we were given a path via dump-minimal-config, output any options
259             // that were used during formatting as TOML.
260             if let Some(path) = minimal_config_path {
261                 let mut file = File::create(path)?;
262                 let toml = config.used_options().to_toml()?;
263                 file.write_all(toml.as_bytes())?;
264             }
265
266             Ok(error_summary)
267         }
268     }
269 }
270
271 fn main() {
272     let _ = env_logger::init();
273
274     let opts = make_opts();
275
276     let exit_code = match execute(&opts) {
277         Ok(summary) => {
278             if summary.has_operational_errors() {
279                 1
280             } else if summary.has_parsing_errors() {
281                 2
282             } else if summary.has_formatting_errors() {
283                 3
284             } else if summary.has_diff {
285                 // should only happen in diff mode
286                 4
287             } else {
288                 assert!(summary.has_no_errors());
289                 0
290             }
291         }
292         Err(e) => {
293             print_usage(&opts, &e.to_string());
294             1
295         }
296     };
297     // Make sure standard output is flushed before we exit.
298     std::io::stdout().flush().unwrap();
299
300     // Exit with given exit code.
301     //
302     // NOTE: This immediately terminates the process without doing any cleanup,
303     // so make sure to finish all necessary cleanup before this is called.
304     std::process::exit(exit_code);
305 }
306
307 fn print_usage(opts: &Options, reason: &str) {
308     let reason = format!(
309         "{}\n\nusage: {} [options] <file>...",
310         reason,
311         env::args_os().next().unwrap().to_string_lossy()
312     );
313     println!("{}", opts.usage(&reason));
314 }
315
316 fn print_version() {
317     println!(
318         "{}-nightly{}",
319         env!("CARGO_PKG_VERSION"),
320         include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
321     )
322 }
323
324 fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
325     if matches.opt_present("h") {
326         return Ok(Operation::Help);
327     }
328
329     if matches.opt_present("config-help") {
330         return Ok(Operation::ConfigHelp);
331     }
332
333     if let Some(path) = matches.opt_str("dump-default-config") {
334         return Ok(Operation::ConfigOutputDefault { path });
335     }
336
337     if matches.opt_present("version") {
338         return Ok(Operation::Version);
339     }
340
341     let config_path_not_found = |path: &str| -> FmtResult<Operation> {
342         Err(FmtError::from(format!(
343             "Error: unable to find a config file for the given path: `{}`",
344             path
345         )))
346     };
347
348     // Read the config_path and convert to parent dir if a file is provided.
349     // If a config file cannot be found from the given path, return error.
350     let config_path: Option<PathBuf> = match matches.opt_str("config-path").map(PathBuf::from) {
351         Some(ref path) if !path.exists() => return config_path_not_found(path.to_str().unwrap()),
352         Some(ref path) if path.is_dir() => {
353             let config_file_path = get_toml_path(path)?;
354             if config_file_path.is_some() {
355                 config_file_path
356             } else {
357                 return config_path_not_found(path.to_str().unwrap());
358             }
359         }
360         path @ _ => path,
361     };
362
363     // If no path is given, we won't output a minimal config.
364     let minimal_config_path = matches.opt_str("dump-minimal-config");
365
366     // if no file argument is supplied, read from stdin
367     if matches.free.is_empty() {
368         let mut buffer = String::new();
369         io::stdin().read_to_string(&mut buffer)?;
370
371         return Ok(Operation::Stdin {
372             input: buffer,
373             config_path: config_path,
374         });
375     }
376
377     let files: Vec<_> = matches
378         .free
379         .iter()
380         .map(|s| {
381             let p = PathBuf::from(s);
382             // we will do comparison later, so here tries to canonicalize first
383             // to get the expected behavior.
384             p.canonicalize().unwrap_or(p)
385         })
386         .collect();
387
388     Ok(Operation::Format {
389         files: files,
390         config_path: config_path,
391         minimal_config_path: minimal_config_path,
392     })
393 }