]> git.lizzy.rs Git - rust.git/blob - src/bin/cargo-fmt.rs
Handle proc-macro crates in cargo-fmt
[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) => {
94             if status.success() {
95                 success
96             } else {
97                 status.code().unwrap_or(failure)
98             }
99         }
100     }
101 }
102
103 fn print_usage(opts: &Options, reason: &str) {
104     let msg = format!("{}\nusage: cargo fmt [options]", reason);
105     println!(
106         "{}\nThis utility formats all bin and lib files of the current crate using rustfmt. \
107          Arguments after `--` are passed to rustfmt.",
108         opts.usage(&msg)
109     );
110 }
111
112 #[derive(Debug, Clone, Copy, PartialEq)]
113 pub enum Verbosity {
114     Verbose,
115     Normal,
116     Quiet,
117 }
118
119 fn format_crate(
120     verbosity: Verbosity,
121     workspace_hitlist: WorkspaceHitlist,
122 ) -> Result<ExitStatus, std::io::Error> {
123     let targets = get_targets(workspace_hitlist)?;
124
125     // Currently only bin and lib files get formatted
126     let files: Vec<_> = targets
127         .into_iter()
128         .filter(|t| t.kind.should_format())
129         .inspect(|t| if verbosity == Verbosity::Verbose {
130             println!("[{:?}] {:?}", t.kind, t.path)
131         })
132         .map(|t| t.path)
133         .collect();
134
135     format_files(&files, &get_fmt_args(), verbosity)
136 }
137
138 fn get_fmt_args() -> Vec<String> {
139     // All arguments after -- are passed to rustfmt
140     env::args().skip_while(|a| a != "--").skip(1).collect()
141 }
142
143 #[derive(Debug)]
144 enum TargetKind {
145     Lib, // dylib, staticlib, lib
146     Bin, // bin
147     Example, // example file
148     Test, // test file
149     Bench, // bench file
150     CustomBuild, // build script
151     ProcMacro, // a proc macro implementation
152     Other, // plugin,...
153 }
154
155 impl TargetKind {
156     fn should_format(&self) -> bool {
157         match *self {
158             TargetKind::Lib | TargetKind::Bin | TargetKind::Example | TargetKind::Test |
159             TargetKind::Bench | TargetKind::CustomBuild | TargetKind::ProcMacro => true,
160             _ => false,
161         }
162     }
163 }
164
165 #[derive(Debug)]
166 pub struct Target {
167     path: PathBuf,
168     kind: TargetKind,
169 }
170
171 #[derive(Debug, PartialEq, Eq)]
172 pub enum WorkspaceHitlist {
173     All,
174     Some(Vec<String>),
175     None,
176 }
177
178 impl WorkspaceHitlist {
179     pub fn get_some<'a>(&'a self) -> Option<&'a [String]> {
180         if let &WorkspaceHitlist::Some(ref hitlist) = self {
181             Some(&hitlist)
182         } else {
183             None
184         }
185     }
186
187     pub fn from_matches(matches: &Matches) -> WorkspaceHitlist {
188         match (matches.opt_present("all"), matches.opt_present("p")) {
189             (false, false) => WorkspaceHitlist::None,
190             (true, _) => WorkspaceHitlist::All,
191             (false, true) => WorkspaceHitlist::Some(matches.opt_strs("p")),
192         }
193     }
194 }
195
196 // Returns a vector of all compile targets of a crate
197 fn get_targets(workspace_hitlist: WorkspaceHitlist) -> Result<Vec<Target>, std::io::Error> {
198     let mut targets: Vec<Target> = vec![];
199     if workspace_hitlist == WorkspaceHitlist::None {
200         let output = Command::new("cargo").arg("read-manifest").output()?;
201         if output.status.success() {
202             // None of the unwraps should fail if output of `cargo read-manifest` is correct
203             let data = &String::from_utf8(output.stdout).unwrap();
204             let json: Value = json::from_str(data).unwrap();
205             let json_obj = json.as_object().unwrap();
206             let jtargets = json_obj.get("targets").unwrap().as_array().unwrap();
207             for jtarget in jtargets {
208                 targets.push(target_from_json(jtarget));
209             }
210
211             return Ok(targets);
212         }
213         return Err(std::io::Error::new(
214             std::io::ErrorKind::NotFound,
215             str::from_utf8(&output.stderr).unwrap(),
216         ));
217     }
218     // This happens when cargo-fmt is not used inside a crate or
219     // is used inside a workspace.
220     // To ensure backward compatability, we only use `cargo metadata` for workspaces.
221     // TODO: Is it possible only use metadata or read-manifest
222     let output = Command::new("cargo")
223         .arg("metadata")
224         .arg("--no-deps")
225         .output()?;
226     if output.status.success() {
227         let data = &String::from_utf8(output.stdout).unwrap();
228         let json: Value = json::from_str(data).unwrap();
229         let json_obj = json.as_object().unwrap();
230         let mut hitlist: HashSet<&String> = if workspace_hitlist != WorkspaceHitlist::All {
231             HashSet::from_iter(workspace_hitlist.get_some().unwrap())
232         } else {
233             HashSet::new() // Unused
234         };
235         let members: Vec<&Value> = json_obj
236             .get("packages")
237             .unwrap()
238             .as_array()
239             .unwrap()
240             .into_iter()
241             .filter(|member| if workspace_hitlist == WorkspaceHitlist::All {
242                 true
243             } else {
244                 let member_obj = member.as_object().unwrap();
245                 let member_name = member_obj.get("name").unwrap().as_str().unwrap();
246                 hitlist.take(&member_name.to_string()).is_some()
247             })
248             .collect();
249         if hitlist.len() != 0 {
250             // Mimick cargo of only outputting one <package> spec.
251             return Err(std::io::Error::new(
252                 std::io::ErrorKind::InvalidInput,
253                 format!(
254                     "package `{}` is not a member of the workspace",
255                     hitlist.iter().next().unwrap()
256                 ),
257             ));
258         }
259         for member in members {
260             let member_obj = member.as_object().unwrap();
261             let jtargets = member_obj.get("targets").unwrap().as_array().unwrap();
262             for jtarget in jtargets {
263                 targets.push(target_from_json(jtarget));
264             }
265         }
266         return Ok(targets);
267     }
268     Err(std::io::Error::new(
269         std::io::ErrorKind::NotFound,
270         str::from_utf8(&output.stderr).unwrap(),
271     ))
272
273 }
274
275 fn target_from_json(jtarget: &Value) -> Target {
276     let jtarget = jtarget.as_object().unwrap();
277     let path = PathBuf::from(jtarget.get("src_path").unwrap().as_str().unwrap());
278     let kinds = jtarget.get("kind").unwrap().as_array().unwrap();
279     let kind = match kinds[0].as_str().unwrap() {
280         "bin" => TargetKind::Bin,
281         "lib" | "dylib" | "staticlib" | "cdylib" | "rlib" => TargetKind::Lib,
282         "test" => TargetKind::Test,
283         "example" => TargetKind::Example,
284         "bench" => TargetKind::Bench,
285         "custom-build" => TargetKind::CustomBuild,
286         "proc-macro" => TargetKind::ProcMacro,
287         _ => TargetKind::Other,
288     };
289
290     Target {
291         path: path,
292         kind: kind,
293     }
294 }
295
296 fn format_files(
297     files: &[PathBuf],
298     fmt_args: &[String],
299     verbosity: Verbosity,
300 ) -> Result<ExitStatus, std::io::Error> {
301     let stdout = if verbosity == Verbosity::Quiet {
302         std::process::Stdio::null()
303     } else {
304         std::process::Stdio::inherit()
305     };
306     if verbosity == Verbosity::Verbose {
307         print!("rustfmt");
308         for a in fmt_args.iter() {
309             print!(" {}", a);
310         }
311         for f in files.iter() {
312             print!(" {}", f.display());
313         }
314         println!("");
315     }
316     let mut command = Command::new("rustfmt")
317         .stdout(stdout)
318         .args(files)
319         .args(fmt_args)
320         .spawn()
321         .map_err(|e| match e.kind() {
322             std::io::ErrorKind::NotFound => {
323                 std::io::Error::new(
324                     std::io::ErrorKind::Other,
325                     "Could not run rustfmt, please make sure it is in your PATH.",
326                 )
327             }
328             _ => e,
329         })?;
330     command.wait()
331 }