]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
docs: Clarify return type of lookup_project_file
[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),
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 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 fn update_config(config: &mut Config, matches: &Matches) {
99     config.verbose = matches.opt_present("verbose");
100     config.skip_children = matches.opt_present("skip-children");
101 }
102
103 fn execute() -> i32 {
104     let mut opts = Options::new();
105     opts.optflag("h", "help", "show this message");
106     opts.optflag("V", "version", "show version information");
107     opts.optflag("v", "verbose", "show progress");
108     opts.optopt("",
109                 "write-mode",
110                 "mode to write in (not usable when piping from stdin)",
111                 "[replace|overwrite|display|diff|coverage|checkstyle]");
112     opts.optflag("", "skip-children", "don't reformat child modules");
113
114     opts.optflag("",
115                  "config-help",
116                  "show details of rustfmt configuration options");
117
118     let matches = match opts.parse(env::args().skip(1)) {
119         Ok(m) => m,
120         Err(e) => {
121             print_usage(&opts, &e.to_string());
122             return 1;
123         }
124     };
125
126     let operation = determine_operation(&matches);
127
128     match operation {
129         Operation::InvalidInput(reason) => {
130             print_usage(&opts, &reason);
131             1
132         }
133         Operation::Help => {
134             print_usage(&opts, "");
135             0
136         }
137         Operation::Version => {
138             print_version();
139             0
140         }
141         Operation::ConfigHelp => {
142             Config::print_docs();
143             0
144         }
145         Operation::Stdin(input, write_mode) => {
146             // try to read config from local directory
147             let (config, _) = resolve_config(&env::current_dir().unwrap())
148                                   .expect("Error resolving config");
149
150             run_from_stdin(input, write_mode, &config);
151             0
152         }
153         Operation::Format(files, write_mode) => {
154             for file in files {
155                 let (mut config, path) = resolve_config(file.parent().unwrap())
156                                              .expect(&format!("Error resolving config for {}",
157                                                               file.display()));
158                 if let Some(path) = path {
159                     println!("Using rustfmt config file {} for {}",
160                              path.display(),
161                              file.display());
162                 }
163
164                 update_config(&mut config, &matches);
165                 run(&file, write_mode, &config);
166             }
167             0
168         }
169     }
170 }
171
172 fn main() {
173     let _ = env_logger::init();
174     let exit_code = execute();
175
176     // Make sure standard output is flushed before we exit.
177     std::io::stdout().flush().unwrap();
178
179     // Exit with given exit code.
180     //
181     // NOTE: This immediately terminates the process without doing any cleanup,
182     // so make sure to finish all necessary cleanup before this is called.
183     std::process::exit(exit_code);
184 }
185
186 fn print_usage(opts: &Options, reason: &str) {
187     let reason = format!("{}\nusage: {} [options] <file>...",
188                          reason,
189                          env::args_os().next().unwrap().to_string_lossy());
190     println!("{}", opts.usage(&reason));
191 }
192
193 fn print_version() {
194     println!("{}.{}.{}{}",
195              option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
196              option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
197              option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
198              option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
199 }
200
201 fn determine_operation(matches: &Matches) -> Operation {
202     if matches.opt_present("h") {
203         return Operation::Help;
204     }
205
206     if matches.opt_present("config-help") {
207         return Operation::ConfigHelp;
208     }
209
210     if matches.opt_present("version") {
211         return Operation::Version;
212     }
213
214     // if no file argument is supplied, read from stdin
215     if matches.free.is_empty() {
216
217         let mut buffer = String::new();
218         match io::stdin().read_to_string(&mut buffer) {
219             Ok(..) => (),
220             Err(e) => return Operation::InvalidInput(e.to_string()),
221         }
222
223         // WriteMode is always plain for Stdin
224         return Operation::Stdin(buffer, WriteMode::Plain);
225     }
226
227     let write_mode = match matches.opt_str("write-mode") {
228         Some(mode) => {
229             match mode.parse() {
230                 Ok(mode) => mode,
231                 Err(..) => return Operation::InvalidInput("Unrecognized write mode".into()),
232             }
233         }
234         None => WriteMode::Default,
235     };
236
237     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
238
239     Operation::Format(files, write_mode)
240 }