]> git.lizzy.rs Git - rust.git/blob - src/bin/cargo-fmt.rs
Format source codes
[rust.git] / src / bin / cargo-fmt.rs
1 // Copyright 2015-2016 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 // Inspired by Paul Woolcock's cargo-fmt (https://github.com/pwoolcoc/cargo-fmt/)
12
13 #![cfg(not(test))]
14 #![deny(warnings)]
15
16 extern crate getopts;
17 extern crate serde_json as json;
18
19 use std::env;
20 use std::io::Write;
21 use std::path::PathBuf;
22 use std::process::{Command, ExitStatus};
23 use std::str;
24 use std::collections::HashSet;
25 use std::iter::FromIterator;
26
27 use json::Value;
28
29 use getopts::{Options, Matches};
30
31 fn main() {
32     let exit_status = execute();
33     std::io::stdout().flush().unwrap();
34     std::process::exit(exit_status);
35 }
36
37 fn execute() -> i32 {
38     let success = 0;
39     let failure = 1;
40
41     let mut opts = getopts::Options::new();
42     opts.optflag("h", "help", "show this message");
43     opts.optflag("q", "quiet", "no output printed to stdout");
44     opts.optflag("v", "verbose", "use verbose output");
45     opts.optmulti(
46         "p",
47         "package",
48         "specify package to format (only usable in workspaces)",
49         "<package>",
50     );
51     opts.optflag("", "all", "format all packages (only usable in workspaces)");
52
53     // If there is any invalid argument passed to `cargo fmt`, return without formatting.
54     if let Some(arg) = env::args()
55         .skip(2)
56         .take_while(|a| a != "--")
57         .find(|a| !a.starts_with('-'))
58     {
59         print_usage(&opts, &format!("Invalid argument: `{}`.", arg));
60         return failure;
61     }
62
63     let matches = match opts.parse(env::args().skip(1).take_while(|a| a != "--")) {
64         Ok(m) => m,
65         Err(e) => {
66             print_usage(&opts, &e.to_string());
67             return failure;
68         }
69     };
70
71     let verbosity = match (matches.opt_present("v"), matches.opt_present("q")) {
72         (false, false) => Verbosity::Normal,
73         (false, true) => Verbosity::Quiet,
74         (true, false) => Verbosity::Verbose,
75         (true, true) => {
76             print_usage(&opts, "quiet mode and verbose mode are not compatible");
77             return failure;
78         }
79     };
80
81     if matches.opt_present("h") {
82         print_usage(&opts, "");
83         return success;
84     }
85
86     let workspace_hitlist = WorkspaceHitlist::from_matches(&matches);
87
88     match format_crate(verbosity, workspace_hitlist) {
89         Err(e) => {
90             print_usage(&opts, &e.to_string());
91             failure
92         }
93         Ok(status) => if status.success() {
94             success
95         } else {
96             status.code().unwrap_or(failure)
97         },
98     }
99 }
100
101 fn print_usage(opts: &Options, reason: &str) {
102     let msg = format!("{}\nusage: cargo fmt [options]", reason);
103     println!(
104         "{}\nThis utility formats all bin and lib files of the current crate using rustfmt. \
105          Arguments after `--` are passed to rustfmt.",
106         opts.usage(&msg)
107     );
108 }
109
110 #[derive(Debug, Clone, Copy, PartialEq)]
111 pub enum Verbosity {
112     Verbose,
113     Normal,
114     Quiet,
115 }
116
117 fn format_crate(
118     verbosity: Verbosity,
119     workspace_hitlist: WorkspaceHitlist,
120 ) -> Result<ExitStatus, std::io::Error> {
121     let targets = get_targets(workspace_hitlist)?;
122
123     // Currently only bin and lib files get formatted
124     let files: Vec<_> = targets
125         .into_iter()
126         .filter(|t| t.kind.should_format())
127         .inspect(|t| if verbosity == Verbosity::Verbose {
128             println!("[{:?}] {:?}", t.kind, t.path)
129         })
130         .map(|t| t.path)
131         .collect();
132
133     format_files(&files, &get_fmt_args(), verbosity)
134 }
135
136 fn get_fmt_args() -> Vec<String> {
137     // All arguments after -- are passed to rustfmt
138     env::args().skip_while(|a| a != "--").skip(1).collect()
139 }
140
141 #[derive(Debug)]
142 enum TargetKind {
143     Lib,         // dylib, staticlib, lib
144     Bin,         // bin
145     Example,     // example file
146     Test,        // test file
147     Bench,       // bench file
148     CustomBuild, // build script
149     ProcMacro,   // a proc macro implementation
150     Other,       // plugin,...
151 }
152
153 impl TargetKind {
154     fn should_format(&self) -> bool {
155         match *self {
156             TargetKind::Lib |
157             TargetKind::Bin |
158             TargetKind::Example |
159             TargetKind::Test |
160             TargetKind::Bench |
161             TargetKind::CustomBuild |
162             TargetKind::ProcMacro => true,
163             _ => false,
164         }
165     }
166 }
167
168 #[derive(Debug)]
169 pub struct Target {
170     path: PathBuf,
171     kind: TargetKind,
172 }
173
174 #[derive(Debug, PartialEq, Eq)]
175 pub enum WorkspaceHitlist {
176     All,
177     Some(Vec<String>),
178     None,
179 }
180
181 impl WorkspaceHitlist {
182     pub fn get_some<'a>(&'a self) -> Option<&'a [String]> {
183         if let &WorkspaceHitlist::Some(ref hitlist) = self {
184             Some(&hitlist)
185         } else {
186             None
187         }
188     }
189
190     pub fn from_matches(matches: &Matches) -> WorkspaceHitlist {
191         match (matches.opt_present("all"), matches.opt_present("p")) {
192             (false, false) => WorkspaceHitlist::None,
193             (true, _) => WorkspaceHitlist::All,
194             (false, true) => WorkspaceHitlist::Some(matches.opt_strs("p")),
195         }
196     }
197 }
198
199 // Returns a vector of all compile targets of a crate
200 fn get_targets(workspace_hitlist: WorkspaceHitlist) -> Result<Vec<Target>, std::io::Error> {
201     let mut targets: Vec<Target> = vec![];
202     if workspace_hitlist == WorkspaceHitlist::None {
203         let output = Command::new("cargo").arg("read-manifest").output()?;
204         if output.status.success() {
205             // None of the unwraps should fail if output of `cargo read-manifest` is correct
206             let data = &String::from_utf8(output.stdout).unwrap();
207             let json: Value = json::from_str(data).unwrap();
208             let json_obj = json.as_object().unwrap();
209             let jtargets = json_obj.get("targets").unwrap().as_array().unwrap();
210             for jtarget in jtargets {
211                 targets.push(target_from_json(jtarget));
212             }
213
214             return Ok(targets);
215         }
216         return Err(std::io::Error::new(
217             std::io::ErrorKind::NotFound,
218             str::from_utf8(&output.stderr).unwrap(),
219         ));
220     }
221     // This happens when cargo-fmt is not used inside a crate or
222     // is used inside a workspace.
223     // To ensure backward compatability, we only use `cargo metadata` for workspaces.
224     // TODO: Is it possible only use metadata or read-manifest
225     let output = Command::new("cargo")
226         .arg("metadata")
227         .arg("--no-deps")
228         .output()?;
229     if output.status.success() {
230         let data = &String::from_utf8(output.stdout).unwrap();
231         let json: Value = json::from_str(data).unwrap();
232         let json_obj = json.as_object().unwrap();
233         let mut hitlist: HashSet<&String> = if workspace_hitlist != WorkspaceHitlist::All {
234             HashSet::from_iter(workspace_hitlist.get_some().unwrap())
235         } else {
236             HashSet::new() // Unused
237         };
238         let members: Vec<&Value> = json_obj
239             .get("packages")
240             .unwrap()
241             .as_array()
242             .unwrap()
243             .into_iter()
244             .filter(|member| if workspace_hitlist == WorkspaceHitlist::All {
245                 true
246             } else {
247                 let member_obj = member.as_object().unwrap();
248                 let member_name = member_obj.get("name").unwrap().as_str().unwrap();
249                 hitlist.take(&member_name.to_string()).is_some()
250             })
251             .collect();
252         if hitlist.len() != 0 {
253             // Mimick cargo of only outputting one <package> spec.
254             return Err(std::io::Error::new(
255                 std::io::ErrorKind::InvalidInput,
256                 format!(
257                     "package `{}` is not a member of the workspace",
258                     hitlist.iter().next().unwrap()
259                 ),
260             ));
261         }
262         for member in members {
263             let member_obj = member.as_object().unwrap();
264             let jtargets = member_obj.get("targets").unwrap().as_array().unwrap();
265             for jtarget in jtargets {
266                 targets.push(target_from_json(jtarget));
267             }
268         }
269         return Ok(targets);
270     }
271     Err(std::io::Error::new(
272         std::io::ErrorKind::NotFound,
273         str::from_utf8(&output.stderr).unwrap(),
274     ))
275
276 }
277
278 fn target_from_json(jtarget: &Value) -> Target {
279     let jtarget = jtarget.as_object().unwrap();
280     let path = PathBuf::from(jtarget.get("src_path").unwrap().as_str().unwrap());
281     let kinds = jtarget.get("kind").unwrap().as_array().unwrap();
282     let kind = match kinds[0].as_str().unwrap() {
283         "bin" => TargetKind::Bin,
284         "lib" | "dylib" | "staticlib" | "cdylib" | "rlib" => TargetKind::Lib,
285         "test" => TargetKind::Test,
286         "example" => TargetKind::Example,
287         "bench" => TargetKind::Bench,
288         "custom-build" => TargetKind::CustomBuild,
289         "proc-macro" => TargetKind::ProcMacro,
290         _ => TargetKind::Other,
291     };
292
293     Target {
294         path: path,
295         kind: kind,
296     }
297 }
298
299 fn format_files(
300     files: &[PathBuf],
301     fmt_args: &[String],
302     verbosity: Verbosity,
303 ) -> Result<ExitStatus, std::io::Error> {
304     let stdout = if verbosity == Verbosity::Quiet {
305         std::process::Stdio::null()
306     } else {
307         std::process::Stdio::inherit()
308     };
309     if verbosity == Verbosity::Verbose {
310         print!("rustfmt");
311         for a in fmt_args.iter() {
312             print!(" {}", a);
313         }
314         for f in files.iter() {
315             print!(" {}", f.display());
316         }
317         println!("");
318     }
319     let mut command = Command::new("rustfmt")
320         .stdout(stdout)
321         .args(files)
322         .args(fmt_args)
323         .spawn()
324         .map_err(|e| match e.kind() {
325             std::io::ErrorKind::NotFound => std::io::Error::new(
326                 std::io::ErrorKind::Other,
327                 "Could not run rustfmt, please make sure it is in your PATH.",
328             ),
329             _ => e,
330         })?;
331     command.wait()
332 }