]> git.lizzy.rs Git - rust.git/blob - src/bin/rustfmt.rs
Merge pull request #790 from kamalmarhubi/handle-rustfmt-toml-dir
[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 let Ok(md) = fs::metadata(&config_file) {
61             // Properly handle unlikely situation of a directory named `rustfmt.toml`.
62             if md.is_file() {
63                 return Ok(config_file);
64             }
65         }
66
67         // If the current directory has no parent, we're done searching.
68         if !current.pop() {
69             return Err(io::Error::new(io::ErrorKind::NotFound, "Config not found"));
70         }
71     }
72 }
73
74 /// Try to find a project file. If it's found, read it.
75 fn lookup_and_read_project_file(input_file: &Path) -> io::Result<(PathBuf, String)> {
76     let path = try!(lookup_project_file(input_file));
77     let mut file = try!(File::open(&path));
78     let mut toml = String::new();
79     try!(file.read_to_string(&mut toml));
80     Ok((path, toml))
81 }
82
83 fn update_config(config: &mut Config, matches: &Matches) {
84     config.verbose = matches.opt_present("verbose");
85     config.skip_children = matches.opt_present("skip-children");
86 }
87
88 fn execute() -> i32 {
89     let mut opts = Options::new();
90     opts.optflag("h", "help", "show this message");
91     opts.optflag("V", "version", "show version information");
92     opts.optflag("v", "verbose", "show progress");
93     opts.optopt("",
94                 "write-mode",
95                 "mode to write in (not usable when piping from stdin)",
96                 "[replace|overwrite|display|diff|coverage|checkstyle]");
97     opts.optflag("", "skip-children", "don't reformat child modules");
98
99     opts.optflag("",
100                  "config-help",
101                  "show details of rustfmt configuration options");
102
103     let matches = match opts.parse(env::args().skip(1)) {
104         Ok(m) => m,
105         Err(e) => {
106             print_usage(&opts, &e.to_string());
107             return 1;
108         }
109     };
110
111     let operation = determine_operation(&matches);
112
113     match operation {
114         Operation::InvalidInput(reason) => {
115             print_usage(&opts, &reason);
116             1
117         }
118         Operation::Help => {
119             print_usage(&opts, "");
120             0
121         }
122         Operation::Version => {
123             print_version();
124             0
125         }
126         Operation::ConfigHelp => {
127             Config::print_docs();
128             0
129         }
130         Operation::Stdin(input, write_mode) => {
131             // try to read config from local directory
132             let config = match lookup_and_read_project_file(&Path::new(".")) {
133                 Ok((_, toml)) => Config::from_toml(&toml),
134                 Err(_) => Default::default(),
135             };
136
137             run_from_stdin(input, write_mode, &config);
138             0
139         }
140         Operation::Format(files, write_mode) => {
141             for file in files {
142                 let mut config = match lookup_and_read_project_file(&file) {
143                     Ok((path, toml)) => {
144                         println!("Using rustfmt config file {} for {}",
145                                  path.display(),
146                                  file.display());
147                         Config::from_toml(&toml)
148                     }
149                     Err(_) => Default::default(),
150                 };
151
152                 update_config(&mut config, &matches);
153                 run(&file, write_mode, &config);
154             }
155             0
156         }
157     }
158 }
159
160 fn main() {
161     let _ = env_logger::init();
162     let exit_code = execute();
163
164     // Make sure standard output is flushed before we exit.
165     std::io::stdout().flush().unwrap();
166
167     // Exit with given exit code.
168     //
169     // NOTE: This immediately terminates the process without doing any cleanup,
170     // so make sure to finish all necessary cleanup before this is called.
171     std::process::exit(exit_code);
172 }
173
174 fn print_usage(opts: &Options, reason: &str) {
175     let reason = format!("{}\nusage: {} [options] <file>...",
176                          reason,
177                          env::args_os().next().unwrap().to_string_lossy());
178     println!("{}", opts.usage(&reason));
179 }
180
181 fn print_version() {
182     println!("{}.{}.{}{}",
183              option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
184              option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
185              option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
186              option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
187 }
188
189 fn determine_operation(matches: &Matches) -> Operation {
190     if matches.opt_present("h") {
191         return Operation::Help;
192     }
193
194     if matches.opt_present("config-help") {
195         return Operation::ConfigHelp;
196     }
197
198     if matches.opt_present("version") {
199         return Operation::Version;
200     }
201
202     // if no file argument is supplied, read from stdin
203     if matches.free.is_empty() {
204
205         let mut buffer = String::new();
206         match io::stdin().read_to_string(&mut buffer) {
207             Ok(..) => (),
208             Err(e) => return Operation::InvalidInput(e.to_string()),
209         }
210
211         // WriteMode is always plain for Stdin
212         return Operation::Stdin(buffer, WriteMode::Plain);
213     }
214
215     let write_mode = match matches.opt_str("write-mode") {
216         Some(mode) => {
217             match mode.parse() {
218                 Ok(mode) => mode,
219                 Err(..) => return Operation::InvalidInput("Unrecognized write mode".into()),
220             }
221         }
222         None => WriteMode::Default,
223     };
224
225     let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
226
227     Operation::Format(files, write_mode)
228 }