|
| 1 | +// Copyright 2017 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 Clang's clang-format-diff: |
| 12 | +// |
| 13 | +// https://github.com/llvm-mirror/clang/blob/master/tools/clang-format/clang-format-diff.py |
| 14 | + |
| 15 | +#![deny(warnings)] |
| 16 | + |
| 17 | +extern crate getopts; |
| 18 | +extern crate regex; |
| 19 | +extern crate serde; |
| 20 | +#[macro_use] |
| 21 | +extern crate serde_derive; |
| 22 | +extern crate serde_json as json; |
| 23 | + |
| 24 | +use std::{env, fmt, process}; |
| 25 | +use std::collections::HashSet; |
| 26 | +use std::error::Error; |
| 27 | +use std::io::{self, BufRead}; |
| 28 | + |
| 29 | +use regex::Regex; |
| 30 | + |
| 31 | +/// The default pattern of files to format. |
| 32 | +/// |
| 33 | +/// We only want to format rust files by default. |
| 34 | +const DEFAULT_PATTERN: &'static str = r".*\.rs"; |
| 35 | + |
| 36 | +#[derive(Debug)] |
| 37 | +enum FormatDiffError { |
| 38 | + IncorrectOptions(getopts::Fail), |
| 39 | + IncorrectFilter(regex::Error), |
| 40 | + IoError(io::Error), |
| 41 | +} |
| 42 | + |
| 43 | +impl fmt::Display for FormatDiffError { |
| 44 | + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
| 45 | + fmt::Display::fmt(self.cause().unwrap(), f) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl Error for FormatDiffError { |
| 50 | + fn description(&self) -> &str { |
| 51 | + self.cause().unwrap().description() |
| 52 | + } |
| 53 | + |
| 54 | + fn cause(&self) -> Option<&Error> { |
| 55 | + Some(match *self { |
| 56 | + FormatDiffError::IoError(ref e) => e, |
| 57 | + FormatDiffError::IncorrectFilter(ref e) => e, |
| 58 | + FormatDiffError::IncorrectOptions(ref e) => e, |
| 59 | + }) |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +impl From<getopts::Fail> for FormatDiffError { |
| 64 | + fn from(fail: getopts::Fail) -> Self { |
| 65 | + FormatDiffError::IncorrectOptions(fail) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +impl From<regex::Error> for FormatDiffError { |
| 70 | + fn from(err: regex::Error) -> Self { |
| 71 | + FormatDiffError::IncorrectFilter(err) |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +impl From<io::Error> for FormatDiffError { |
| 76 | + fn from(fail: io::Error) -> Self { |
| 77 | + FormatDiffError::IoError(fail) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +fn main() { |
| 82 | + let mut opts = getopts::Options::new(); |
| 83 | + opts.optflag("h", "help", "show this message"); |
| 84 | + opts.optflag("v", "verbose", "use verbose output"); |
| 85 | + opts.optopt( |
| 86 | + "p", |
| 87 | + "skip-prefix", |
| 88 | + "skip the smallest prefix containing NUMBER slashes", |
| 89 | + "NUMBER", |
| 90 | + ); |
| 91 | + opts.optopt( |
| 92 | + "f", |
| 93 | + "filter", |
| 94 | + "custom pattern selecting file paths to reformat", |
| 95 | + "PATTERN", |
| 96 | + ); |
| 97 | + |
| 98 | + if let Err(e) = run(&opts) { |
| 99 | + println!("{}", opts.usage(e.description())); |
| 100 | + process::exit(1); |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] |
| 105 | +struct Range { |
| 106 | + file: String, |
| 107 | + range: [u32; 2], |
| 108 | +} |
| 109 | + |
| 110 | +fn run(opts: &getopts::Options) -> Result<(), FormatDiffError> { |
| 111 | + let matches = opts.parse(env::args().skip(1))?; |
| 112 | + |
| 113 | + if matches.opt_present("h") { |
| 114 | + println!("{}", opts.usage("usage: ")); |
| 115 | + return Ok(()); |
| 116 | + } |
| 117 | + |
| 118 | + let verbose = matches.opt_present("v"); |
| 119 | + |
| 120 | + let filter = matches |
| 121 | + .opt_str("f") |
| 122 | + .unwrap_or_else(|| DEFAULT_PATTERN.into()); |
| 123 | + |
| 124 | + |
| 125 | + let skip_prefix = matches |
| 126 | + .opt_str("p") |
| 127 | + .and_then(|p| p.parse::<u32>().ok()) |
| 128 | + .unwrap_or(0); |
| 129 | + |
| 130 | + let (files, ranges) = scan_diff(io::stdin(), skip_prefix, &filter)?; |
| 131 | + |
| 132 | + run_rustfmt(&files, &ranges, verbose) |
| 133 | +} |
| 134 | + |
| 135 | +fn run_rustfmt( |
| 136 | + files: &HashSet<String>, |
| 137 | + ranges: &[Range], |
| 138 | + verbose: bool, |
| 139 | +) -> Result<(), FormatDiffError> { |
| 140 | + if files.is_empty() || ranges.is_empty() { |
| 141 | + if verbose { |
| 142 | + println!("No files to format found"); |
| 143 | + } |
| 144 | + return Ok(()); |
| 145 | + } |
| 146 | + |
| 147 | + let ranges_as_json = json::to_string(ranges).unwrap(); |
| 148 | + if verbose { |
| 149 | + print!("rustfmt"); |
| 150 | + for file in files { |
| 151 | + print!(" {:?}", file); |
| 152 | + } |
| 153 | + print!(" --file-lines {:?}", ranges_as_json); |
| 154 | + } |
| 155 | + |
| 156 | + let exit_status = process::Command::new("rustfmt") |
| 157 | + .args(files) |
| 158 | + .arg("--file-lines") |
| 159 | + .arg(ranges_as_json) |
| 160 | + .status()?; |
| 161 | + |
| 162 | + if !exit_status.success() { |
| 163 | + return Err(FormatDiffError::IoError(io::Error::new( |
| 164 | + io::ErrorKind::Other, |
| 165 | + format!("rustfmt failed with {}", exit_status), |
| 166 | + ))); |
| 167 | + } |
| 168 | + Ok(()) |
| 169 | +} |
| 170 | + |
| 171 | +/// Scans a diff from `from`, and returns the set of files found, and the ranges |
| 172 | +/// in those files. |
| 173 | +fn scan_diff<R>( |
| 174 | + from: R, |
| 175 | + skip_prefix: u32, |
| 176 | + file_filter: &str, |
| 177 | +) -> Result<(HashSet<String>, Vec<Range>), FormatDiffError> |
| 178 | +where |
| 179 | + R: io::Read, |
| 180 | +{ |
| 181 | + let diff_pattern = format!(r"^\+\+\+\s(?:.*?/){{{}}}(\S*)", skip_prefix); |
| 182 | + let diff_pattern = Regex::new(&diff_pattern).unwrap(); |
| 183 | + |
| 184 | + let lines_pattern = Regex::new(r"^@@.*\+(\d+)(,(\d+))?").unwrap(); |
| 185 | + |
| 186 | + let file_filter = Regex::new(&format!("^{}$", file_filter))?; |
| 187 | + |
| 188 | + let mut current_file = None; |
| 189 | + |
| 190 | + let mut files = HashSet::new(); |
| 191 | + let mut ranges = vec![]; |
| 192 | + for line in io::BufReader::new(from).lines() { |
| 193 | + let line = line.unwrap(); |
| 194 | + |
| 195 | + if let Some(captures) = diff_pattern.captures(&line) { |
| 196 | + current_file = Some(captures.get(1).unwrap().as_str().to_owned()); |
| 197 | + } |
| 198 | + |
| 199 | + let file = match current_file { |
| 200 | + Some(ref f) => &**f, |
| 201 | + None => continue, |
| 202 | + }; |
| 203 | + |
| 204 | + // TODO(emilio): We could avoid this most of the time if needed, but |
| 205 | + // it's not clear it's worth it. |
| 206 | + if !file_filter.is_match(file) { |
| 207 | + continue; |
| 208 | + } |
| 209 | + |
| 210 | + let lines_captures = match lines_pattern.captures(&line) { |
| 211 | + Some(captures) => captures, |
| 212 | + None => continue, |
| 213 | + }; |
| 214 | + |
| 215 | + let start_line = lines_captures |
| 216 | + .get(1) |
| 217 | + .unwrap() |
| 218 | + .as_str() |
| 219 | + .parse::<u32>() |
| 220 | + .unwrap(); |
| 221 | + let line_count = match lines_captures.get(3) { |
| 222 | + Some(line_count) => line_count.as_str().parse::<u32>().unwrap(), |
| 223 | + None => 1, |
| 224 | + }; |
| 225 | + |
| 226 | + if line_count == 0 { |
| 227 | + continue; |
| 228 | + } |
| 229 | + |
| 230 | + let end_line = start_line + line_count - 1; |
| 231 | + files.insert(file.to_owned()); |
| 232 | + ranges.push(Range { |
| 233 | + file: file.to_owned(), |
| 234 | + range: [start_line, end_line], |
| 235 | + }); |
| 236 | + } |
| 237 | + |
| 238 | + Ok((files, ranges)) |
| 239 | +} |
| 240 | + |
| 241 | +#[test] |
| 242 | +fn scan_simple_git_diff() { |
| 243 | + const DIFF: &'static str = include_str!("test/bindgen.diff"); |
| 244 | + let (files, ranges) = scan_diff(DIFF.as_bytes(), 1, r".*\.rs").expect("scan_diff failed?"); |
| 245 | + |
| 246 | + assert!( |
| 247 | + files.contains("src/ir/traversal.rs"), |
| 248 | + "Should've matched the filter" |
| 249 | + ); |
| 250 | + |
| 251 | + assert!( |
| 252 | + !files.contains("tests/headers/anon_enum.hpp"), |
| 253 | + "Shouldn't have matched the filter" |
| 254 | + ); |
| 255 | + |
| 256 | + assert_eq!( |
| 257 | + &ranges, |
| 258 | + &[ |
| 259 | + Range { |
| 260 | + file: "src/ir/item.rs".into(), |
| 261 | + range: [148, 158], |
| 262 | + }, |
| 263 | + Range { |
| 264 | + file: "src/ir/item.rs".into(), |
| 265 | + range: [160, 170], |
| 266 | + }, |
| 267 | + Range { |
| 268 | + file: "src/ir/traversal.rs".into(), |
| 269 | + range: [9, 16], |
| 270 | + }, |
| 271 | + Range { |
| 272 | + file: "src/ir/traversal.rs".into(), |
| 273 | + range: [35, 43], |
| 274 | + } |
| 275 | + ] |
| 276 | + ); |
| 277 | +} |
0 commit comments