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