Skip to content

Commit 4238baa

Browse files
committed
bin: Add a very simple rustfmt-format-diff.
This patch introduces a super-simple format-diff tool, that allows you to do: ``` git diff | rustfmt-format-diff -p 1 ``` To format your current changes. For now it doesn't accept too much customisation, and it basically calls rustfmt with the default configuration, but more customisation can be added in the future if needed.
1 parent 74f5a51 commit 4238baa

File tree

3 files changed

+349
-1
lines changed

3 files changed

+349
-1
lines changed

Cargo.toml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,13 @@ name = "rustfmt"
2020
[[bin]]
2121
name = "cargo-fmt"
2222

23+
[[bin]]
24+
name = "rustfmt-format-diff"
25+
2326
[features]
24-
default = ["cargo-fmt"]
27+
default = ["cargo-fmt", "rustfmt-format-diff"]
2528
cargo-fmt = []
29+
rustfmt-format-diff = []
2630

2731
[dependencies]
2832
toml = "0.4"

src/bin/rustfmt-format-diff.rs

Lines changed: 277 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,277 @@
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+
}

src/bin/test/bindgen.diff

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
diff --git a/src/ir/item.rs b/src/ir/item.rs
2+
index 7f3afefb..90d15e96 100644
3+
--- a/src/ir/item.rs
4+
+++ b/src/ir/item.rs
5+
@@ -148,7 +148,11 @@ impl<'a, 'b> Iterator for ItemAncestorsIter<'a, 'b>
6+
impl AsTemplateParam for ItemId {
7+
type Extra = ();
8+
9+
- fn as_template_param(&self, ctx: &BindgenContext, _: &()) -> Option<ItemId> {
10+
+ fn as_template_param(
11+
+ &self,
12+
+ ctx: &BindgenContext,
13+
+ _: &(),
14+
+ ) -> Option<ItemId> {
15+
ctx.resolve_item(*self).as_template_param(ctx, &())
16+
}
17+
}
18+
@@ -156,7 +160,11 @@ impl AsTemplateParam for ItemId {
19+
impl AsTemplateParam for Item {
20+
type Extra = ();
21+
22+
- fn as_template_param(&self, ctx: &BindgenContext, _: &()) -> Option<ItemId> {
23+
+ fn as_template_param(
24+
+ &self,
25+
+ ctx: &BindgenContext,
26+
+ _: &(),
27+
+ ) -> Option<ItemId> {
28+
self.kind.as_template_param(ctx, self)
29+
}
30+
}
31+
diff --git a/src/ir/traversal.rs b/src/ir/traversal.rs
32+
index 762a3e2d..b9c9dd4e 100644
33+
--- a/src/ir/traversal.rs
34+
+++ b/src/ir/traversal.rs
35+
@@ -9,6 +9,8 @@ use std::collections::{BTreeMap, VecDeque};
36+
///
37+
/// from --> to
38+
///
39+
+/// Random content to generate a diff.
40+
+///
41+
/// The `from` is left implicit: it is the concrete `Trace` implementer which
42+
/// yielded this outgoing edge.
43+
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
44+
@@ -33,7 +35,9 @@ impl Into<ItemId> for Edge {
45+
}
46+
}
47+
48+
-/// The kind of edge reference. This is useful when we wish to only consider
49+
+/// The kind of edge reference.
50+
+///
51+
+/// This is useful when we wish to only consider
52+
/// certain kinds of edges for a particular traversal or analysis.
53+
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
54+
pub enum EdgeKind {
55+
diff --git a/tests/headers/anon_enum.hpp b/tests/headers/anon_enum.hpp
56+
index 1961fe6c..34759df3 100644
57+
--- a/tests/headers/anon_enum.hpp
58+
+++ b/tests/headers/anon_enum.hpp
59+
@@ -1,7 +1,7 @@
60+
struct Test {
61+
int foo;
62+
float bar;
63+
- enum { T_NONE };
64+
+ enum { T_NONE, T_SOME };
65+
};
66+
67+
typedef enum {

0 commit comments

Comments
 (0)