Skip to content

Commit 9a7fac6

Browse files
committed
Remove format_and_emit_report from the API
Also changes the header/footer stuff
1 parent 95d6b64 commit 9a7fac6

File tree

7 files changed

+94
-93
lines changed

7 files changed

+94
-93
lines changed

src/bin/main.rs

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
// except according to those terms.
1010

1111
#![cfg(not(test))]
12+
#![feature(extern_prelude)]
1213

1314
extern crate env_logger;
1415
#[macro_use]
@@ -27,8 +28,8 @@ use failure::err_msg;
2728
use getopts::{Matches, Options};
2829

2930
use rustfmt::{
30-
emit_post_matter, emit_pre_matter, format_and_emit_report, load_config, CliOptions, Color,
31-
Config, EmitMode, ErrorKind, FileLines, FileName, Input, Summary, Verbosity,
31+
checkstyle_footer, checkstyle_header, format_input, load_config, use_colored_tty, CliOptions,
32+
Color, Config, EmitMode, ErrorKind, FileLines, FileName, Input, Summary, Verbosity,
3233
};
3334

3435
fn main() {
@@ -221,12 +222,12 @@ fn execute(opts: &Options) -> Result<(ExitCodeMode, Summary), failure::Error> {
221222
}
222223

223224
let mut error_summary = Summary::default();
224-
emit_pre_matter(&config)?;
225+
emit_pre_matter(&config);
225226
match format_and_emit_report(Input::Text(input), &config) {
226227
Ok(summary) => error_summary.add(summary),
227228
Err(_) => error_summary.add_operational_error(),
228229
}
229-
emit_post_matter(&config)?;
230+
emit_post_matter(&config);
230231

231232
Ok((ExitCodeMode::Normal, error_summary))
232233
}
@@ -251,7 +252,7 @@ fn format(
251252
}
252253
}
253254

254-
emit_pre_matter(&config)?;
255+
emit_pre_matter(&config);
255256
let mut error_summary = Summary::default();
256257

257258
for file in files {
@@ -289,7 +290,7 @@ fn format(
289290
}
290291
}
291292
}
292-
emit_post_matter(&config)?;
293+
emit_post_matter(&config);
293294

294295
// If we were given a path via dump-minimal-config, output any options
295296
// that were used during formatting as TOML.
@@ -307,6 +308,49 @@ fn format(
307308
Ok((exit_mode, error_summary))
308309
}
309310

311+
fn format_and_emit_report(input: Input, config: &Config) -> Result<Summary, failure::Error> {
312+
let out = &mut stdout();
313+
314+
match format_input(input, config, Some(out)) {
315+
Ok((summary, report)) => {
316+
if report.has_warnings() {
317+
match term::stderr() {
318+
Some(ref t)
319+
if use_colored_tty(config.color())
320+
&& t.supports_color()
321+
&& t.supports_attr(term::Attr::Bold) =>
322+
{
323+
match report.fancy_print(term::stderr().unwrap()) {
324+
Ok(..) => (),
325+
Err(..) => panic!("Unable to write to stderr: {}", report),
326+
}
327+
}
328+
_ => eprintln!("{}", report),
329+
}
330+
}
331+
332+
Ok(summary)
333+
}
334+
Err((msg, mut summary)) => {
335+
eprintln!("Error writing files: {}", msg);
336+
summary.add_operational_error();
337+
Ok(summary)
338+
}
339+
}
340+
}
341+
342+
fn emit_pre_matter(config: &Config) {
343+
if config.emit_mode() == EmitMode::Checkstyle {
344+
println!("{}", checkstyle_header());
345+
}
346+
}
347+
348+
fn emit_post_matter(config: &Config) {
349+
if config.emit_mode() == EmitMode::Checkstyle {
350+
println!("{}", checkstyle_footer());
351+
}
352+
}
353+
310354
fn print_usage_to_stdout(opts: &Options, reason: &str) {
311355
let sep = if reason.is_empty() {
312356
String::new()

src/checkstyle.rs

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,16 @@ use std::path::Path;
1313

1414
use rustfmt_diff::{DiffLine, Mismatch};
1515

16-
pub fn output_header<T>(out: &mut T) -> Result<(), io::Error>
17-
where
18-
T: Write,
19-
{
16+
pub fn header() -> String {
2017
let mut xml_heading = String::new();
2118
xml_heading.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
2219
xml_heading.push_str("\n");
2320
xml_heading.push_str("<checkstyle version=\"4.3\">");
24-
write!(out, "{}", xml_heading)
21+
xml_heading
2522
}
2623

27-
pub fn output_footer<T>(out: &mut T) -> Result<(), io::Error>
28-
where
29-
T: Write,
30-
{
31-
let mut xml_tail = String::new();
32-
xml_tail.push_str("</checkstyle>\n");
33-
write!(out, "{}", xml_tail)
24+
pub fn footer() -> String {
25+
"</checkstyle>\n".to_owned()
3426
}
3527

3628
pub fn output_checkstyle_file<T>(

src/filemap.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,13 @@ where
3636
T: Write,
3737
{
3838
if config.emit_mode() == EmitMode::Checkstyle {
39-
::checkstyle::output_header(out)?;
39+
write!(out, "{}", ::checkstyle::header())?;
4040
}
4141
for &(ref filename, ref text) in file_map {
4242
write_file(text, filename, out, config)?;
4343
}
4444
if config.emit_mode() == EmitMode::Checkstyle {
45-
::checkstyle::output_footer(out)?;
45+
write!(out, "{}", ::checkstyle::footer())?;
4646
}
4747

4848
Ok(())

src/git-rustfmt/main.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,14 @@ extern crate log;
1515
extern crate rustfmt_nightly as rustfmt;
1616

1717
use std::env;
18+
use std::io::stdout;
1819
use std::path::{Path, PathBuf};
1920
use std::process::Command;
2021
use std::str::FromStr;
2122

2223
use getopts::{Matches, Options};
2324

24-
use rustfmt::{format_and_emit_report, load_config, CliOptions, Input};
25+
use rustfmt::{format_input, load_config, CliOptions, Input};
2526

2627
fn prune_files(files: Vec<&str>) -> Vec<&str> {
2728
let prefixes: Vec<_> = files
@@ -73,7 +74,14 @@ fn fmt_files(files: &[&str]) -> i32 {
7374

7475
let mut exit_code = 0;
7576
for file in files {
76-
let summary = format_and_emit_report(Input::File(PathBuf::from(file)), &config).unwrap();
77+
let (summary, report) = format_input(
78+
Input::File(PathBuf::from(file)),
79+
&config,
80+
Some(&mut stdout()),
81+
).unwrap();
82+
if report.has_warnings() {
83+
eprintln!("{}", report);
84+
}
7785
if !summary.has_no_errors() {
7886
exit_code = 1;
7987
}

src/lib.rs

Lines changed: 24 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@
1313
#![allow(unused_attributes)]
1414
#![feature(type_ascription)]
1515
#![feature(unicode_internals)]
16+
#![feature(extern_prelude)]
1617

1718
#[macro_use]
1819
extern crate derive_new;
1920
extern crate diff;
20-
#[macro_use]
2121
extern crate failure;
2222
extern crate itertools;
2323
#[cfg(test)]
@@ -32,14 +32,13 @@ extern crate serde;
3232
extern crate serde_derive;
3333
extern crate serde_json;
3434
extern crate syntax;
35-
extern crate term;
3635
extern crate toml;
3736
extern crate unicode_segmentation;
3837

3938
use std::cell::RefCell;
4039
use std::collections::HashMap;
4140
use std::fmt;
42-
use std::io::{self, stdout, Write};
41+
use std::io::{self, Write};
4342
use std::panic::{catch_unwind, AssertUnwindSafe};
4443
use std::path::PathBuf;
4544
use std::rc::Rc;
@@ -55,13 +54,14 @@ use comment::{CharClasses, FullCodeCharKind, LineClasses};
5554
use failure::Fail;
5655
use issues::{BadIssueSeeker, Issue};
5756
use shape::Indent;
58-
use utils::use_colored_tty;
5957
use visitor::{FmtVisitor, SnippetProvider};
6058

59+
pub use checkstyle::{footer as checkstyle_footer, header as checkstyle_header};
6160
pub use config::summary::Summary;
6261
pub use config::{
6362
load_config, CliOptions, Color, Config, EmitMode, FileLines, FileName, Verbosity,
6463
};
64+
pub use utils::use_colored_tty;
6565

6666
#[macro_use]
6767
mod utils;
@@ -129,6 +129,8 @@ pub enum ErrorKind {
129129
BadAttr,
130130
#[fail(display = "io error: {}", _0)]
131131
IoError(io::Error),
132+
#[fail(display = "Version mismatch")]
133+
VersionMismatch,
132134
}
133135

134136
impl From<io::Error> for ErrorKind {
@@ -168,7 +170,7 @@ impl FormattingError {
168170
ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace | ErrorKind::IoError(_) => {
169171
"internal error:"
170172
}
171-
ErrorKind::LicenseCheck | ErrorKind::BadAttr => "error:",
173+
ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
172174
ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
173175
}
174176
}
@@ -203,7 +205,7 @@ impl FormattingError {
203205
}
204206

205207
#[derive(Clone)]
206-
struct FormatReport {
208+
pub struct FormatReport {
207209
// Maps stringified file paths to their associated formatting errors.
208210
internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
209211
}
@@ -246,7 +248,8 @@ impl FormatReport {
246248
ErrorKind::BadIssue(_)
247249
| ErrorKind::LicenseCheck
248250
| ErrorKind::DeprecatedAttr
249-
| ErrorKind::BadAttr => {
251+
| ErrorKind::BadAttr
252+
| ErrorKind::VersionMismatch => {
250253
errs.has_check_errors = true;
251254
}
252255
_ => {}
@@ -263,11 +266,11 @@ impl FormatReport {
263266
.sum()
264267
}
265268

266-
fn has_warnings(&self) -> bool {
269+
pub fn has_warnings(&self) -> bool {
267270
self.warning_count() > 0
268271
}
269272

270-
fn print_warnings_fancy(
273+
pub fn fancy_print(
271274
&self,
272275
mut t: Box<term::Terminal<Output = io::Stderr>>,
273276
) -> Result<(), term::Error> {
@@ -749,12 +752,22 @@ fn format_code_block(code_snippet: &str, config: &Config) -> Option<String> {
749752
Some(result)
750753
}
751754

755+
#[derive(Debug)]
756+
pub enum Input {
757+
File(PathBuf),
758+
Text(String),
759+
}
760+
752761
pub fn format_input<T: Write>(
753762
input: Input,
754763
config: &Config,
755764
out: Option<&mut T>,
756-
) -> Result<Summary, (ErrorKind, Summary)> {
757-
syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| tup.0)
765+
) -> Result<(Summary, FormatReport), (ErrorKind, Summary)> {
766+
if !config.version_meets_requirement() {
767+
return Err((ErrorKind::VersionMismatch, Summary::default()));
768+
}
769+
770+
syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| (tup.0, tup.2))
758771
}
759772

760773
fn format_input_inner<T: Write>(
@@ -950,61 +963,6 @@ fn get_modified_lines(
950963
Ok(ModifiedLines { chunks })
951964
}
952965

953-
#[derive(Debug)]
954-
pub enum Input {
955-
File(PathBuf),
956-
Text(String),
957-
}
958-
959-
pub fn format_and_emit_report(input: Input, config: &Config) -> Result<Summary, failure::Error> {
960-
if !config.version_meets_requirement() {
961-
return Err(format_err!("Version mismatch"));
962-
}
963-
let out = &mut stdout();
964-
match syntax::with_globals(|| format_input_inner(input, config, Some(out))) {
965-
Ok((summary, _, report)) => {
966-
if report.has_warnings() {
967-
match term::stderr() {
968-
Some(ref t)
969-
if use_colored_tty(config.color())
970-
&& t.supports_color()
971-
&& t.supports_attr(term::Attr::Bold) =>
972-
{
973-
match report.print_warnings_fancy(term::stderr().unwrap()) {
974-
Ok(..) => (),
975-
Err(..) => panic!("Unable to write to stderr: {}", report),
976-
}
977-
}
978-
_ => eprintln!("{}", report),
979-
}
980-
}
981-
982-
Ok(summary)
983-
}
984-
Err((msg, mut summary)) => {
985-
eprintln!("Error writing files: {}", msg);
986-
summary.add_operational_error();
987-
Ok(summary)
988-
}
989-
}
990-
}
991-
992-
pub fn emit_pre_matter(config: &Config) -> Result<(), ErrorKind> {
993-
if config.emit_mode() == EmitMode::Checkstyle {
994-
let mut out = &mut stdout();
995-
checkstyle::output_header(&mut out)?;
996-
}
997-
Ok(())
998-
}
999-
1000-
pub fn emit_post_matter(config: &Config) -> Result<(), ErrorKind> {
1001-
if config.emit_mode() == EmitMode::Checkstyle {
1002-
let mut out = &mut stdout();
1003-
checkstyle::output_footer(&mut out)?;
1004-
}
1005-
Ok(())
1006-
}
1007-
1008966
#[cfg(test)]
1009967
mod unit_tests {
1010968
use super::{format_code_block, format_snippet, Config};

src/rustfmt_diff.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ use diff;
1313
use std::collections::VecDeque;
1414
use std::io;
1515
use std::io::Write;
16-
use term;
1716
use utils::use_colored_tty;
1817

1918
#[derive(Debug, PartialEq)]

0 commit comments

Comments
 (0)