Rationalise result and error types

This commit is contained in:
Nick Cameron 2018-05-19 16:44:48 +12:00
parent 432b1cb253
commit abb253df8b
5 changed files with 33 additions and 56 deletions

View File

@ -11,7 +11,6 @@
use std::default::Default; use std::default::Default;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
#[must_use]
#[derive(Debug, Default, Clone, Copy)] #[derive(Debug, Default, Clone, Copy)]
pub struct Summary { pub struct Summary {
// Encountered e.g. an IO error. // Encountered e.g. an IO error.

View File

@ -206,7 +206,7 @@ impl FormattingError {
} }
#[derive(Clone)] #[derive(Clone)]
pub struct FormatReport { struct FormatReport {
// Maps stringified file paths to their associated formatting errors. // Maps stringified file paths to their associated formatting errors.
internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>, internal: Rc<RefCell<(FormatErrorMap, ReportedErrors)>>,
} }
@ -756,21 +756,21 @@ pub fn format_input<T: Write>(
input: Input, input: Input,
config: &Config, config: &Config,
out: Option<&mut T>, out: Option<&mut T>,
) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> { ) -> Result<Summary, (ErrorKind, Summary)> {
syntax::with_globals(|| format_input_inner(input, config, out)) syntax::with_globals(|| format_input_inner(input, config, out)).map(|tup| tup.0)
} }
fn format_input_inner<T: Write>( fn format_input_inner<T: Write>(
input: Input, input: Input,
config: &Config, config: &Config,
mut out: Option<&mut T>, mut out: Option<&mut T>,
) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> { ) -> Result<(Summary, FileMap, FormatReport), (ErrorKind, Summary)> {
let mut summary = Summary::default(); let mut summary = Summary::default();
if config.disable_all_formatting() { if config.disable_all_formatting() {
// When the input is from stdin, echo back the input. // When the input is from stdin, echo back the input.
if let Input::Text(ref buf) = input { if let Input::Text(ref buf) = input {
if let Err(e) = io::stdout().write_all(buf.as_bytes()) { if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
return Err((e, summary)); return Err((From::from(e), summary));
} }
} }
return Ok((summary, FileMap::new(), FormatReport::new())); return Ok((summary, FileMap::new(), FormatReport::new()));
@ -890,7 +890,7 @@ fn format_input_inner<T: Write>(
Ok((summary, file_map, report)) Ok((summary, file_map, report))
} }
Err(e) => Err((e, summary)), Err(e) => Err((From::from(e), summary)),
} }
} }
@ -913,33 +913,20 @@ struct ModifiedLines {
pub chunks: Vec<ModifiedChunk>, pub chunks: Vec<ModifiedChunk>,
} }
/// The successful result of formatting via `get_modified_lines()`.
#[cfg(test)]
struct ModifiedLinesResult {
/// The high level summary details
pub summary: Summary,
/// The result Filemap
pub filemap: FileMap,
/// Map of formatting errors
pub report: FormatReport,
/// The sets of updated lines.
pub modified_lines: ModifiedLines,
}
/// Format a file and return a `ModifiedLines` data structure describing /// Format a file and return a `ModifiedLines` data structure describing
/// the changed ranges of lines. /// the changed ranges of lines.
#[cfg(test)] #[cfg(test)]
fn get_modified_lines( fn get_modified_lines(
input: Input, input: Input,
config: &Config, config: &Config,
) -> Result<ModifiedLinesResult, (io::Error, Summary)> { ) -> Result<ModifiedLines, (ErrorKind, Summary)> {
use std::io::BufRead; use std::io::BufRead;
let mut data = Vec::new(); let mut data = Vec::new();
let mut config = config.clone(); let mut config = config.clone();
config.set().write_mode(config::WriteMode::Modified); config.set().write_mode(config::WriteMode::Modified);
let (summary, filemap, report) = format_input(input, &config, Some(&mut data))?; format_input(input, &config, Some(&mut data))?;
let mut lines = data.lines(); let mut lines = data.lines();
let mut chunks = Vec::new(); let mut chunks = Vec::new();
@ -963,12 +950,7 @@ fn get_modified_lines(
lines: added_lines, lines: added_lines,
}); });
} }
Ok(ModifiedLinesResult { Ok(ModifiedLines { chunks })
summary,
filemap,
report,
modified_lines: ModifiedLines { chunks },
})
} }
#[derive(Debug)] #[derive(Debug)]
@ -982,7 +964,7 @@ pub fn format_and_emit_report(input: Input, config: &Config) -> Result<Summary,
return Err(format_err!("Version mismatch")); return Err(format_err!("Version mismatch"));
} }
let out = &mut stdout(); let out = &mut stdout();
match format_input(input, config, Some(out)) { match syntax::with_globals(|| format_input_inner(input, config, Some(out))) {
Ok((summary, _, report)) => { Ok((summary, _, report)) => {
if report.has_warnings() { if report.has_warnings() {
match term::stderr() { match term::stderr() {

View File

@ -39,7 +39,7 @@ pub struct RewriteContext<'a> {
// When rewriting chain, veto going multi line except the last element // When rewriting chain, veto going multi line except the last element
pub force_one_line_chain: RefCell<bool>, pub force_one_line_chain: RefCell<bool>,
pub snippet_provider: &'a SnippetProvider<'a>, pub snippet_provider: &'a SnippetProvider<'a>,
pub report: FormatReport, pub(crate) report: FormatReport,
} }
impl<'a> RewriteContext<'a> { impl<'a> RewriteContext<'a> {

View File

@ -10,6 +10,8 @@
extern crate assert_cli; extern crate assert_cli;
use syntax;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::env; use std::env;
use std::fs; use std::fs;
@ -143,7 +145,7 @@ fn modified_test() {
let filename = "tests/writemode/source/modified.rs"; let filename = "tests/writemode/source/modified.rs";
let result = get_modified_lines(Input::File(filename.into()), &Config::default()).unwrap(); let result = get_modified_lines(Input::File(filename.into()), &Config::default()).unwrap();
assert_eq!( assert_eq!(
result.modified_lines, result,
ModifiedLines { ModifiedLines {
chunks: vec![ chunks: vec![
ModifiedChunk { ModifiedChunk {
@ -240,19 +242,13 @@ fn self_tests() {
#[test] #[test]
fn stdin_formatting_smoke_test() { fn stdin_formatting_smoke_test() {
let input = Input::Text("fn main () {}".to_owned()); let input = Input::Text("fn main () {}".to_owned());
let config = Config::default(); let mut config = Config::default();
let (error_summary, file_map, _report) = config.set().write_mode(WriteMode::Display);
format_input::<io::Stdout>(input, &config, None).unwrap(); let mut buf: Vec<u8> = vec![];
let error_summary = format_input(input, &config, Some(&mut buf)).unwrap();
assert!(error_summary.has_no_errors()); assert!(error_summary.has_no_errors());
for &(ref file_name, ref text) in &file_map { //eprintln!("{:?}", );
if let FileName::Custom(ref file_name) = *file_name { assert_eq!(buf, "fn main() {}\n".as_bytes());
if file_name == "stdin" {
assert_eq!(text.to_string(), "fn main() {}\n");
return;
}
}
}
panic!("no stdin");
} }
// FIXME(#1990) restore this test // FIXME(#1990) restore this test
@ -284,8 +280,7 @@ fn format_lines_errors_are_reported() {
let input = Input::Text(format!("fn {}() {{}}", long_identifier)); let input = Input::Text(format!("fn {}() {{}}", long_identifier));
let mut config = Config::default(); let mut config = Config::default();
config.set().error_on_line_overflow(true); config.set().error_on_line_overflow(true);
let (error_summary, _file_map, _report) = let error_summary = format_input::<io::Stdout>(input, &config, None).unwrap();
format_input::<io::Stdout>(input, &config, None).unwrap();
assert!(error_summary.has_formatting_errors()); assert!(error_summary.has_formatting_errors());
} }
@ -296,8 +291,7 @@ fn format_lines_errors_are_reported_with_tabs() {
let mut config = Config::default(); let mut config = Config::default();
config.set().error_on_line_overflow(true); config.set().error_on_line_overflow(true);
config.set().hard_tabs(true); config.set().hard_tabs(true);
let (error_summary, _file_map, _report) = let error_summary = format_input::<io::Stdout>(input, &config, None).unwrap();
format_input::<io::Stdout>(input, &config, None).unwrap();
assert!(error_summary.has_formatting_errors()); assert!(error_summary.has_formatting_errors());
} }
@ -382,7 +376,8 @@ fn read_config(filename: &Path) -> Config {
fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (Summary, FileMap, FormatReport) { fn format_file<P: Into<PathBuf>>(filepath: P, config: &Config) -> (Summary, FileMap, FormatReport) {
let filepath = filepath.into(); let filepath = filepath.into();
let input = Input::File(filepath); let input = Input::File(filepath);
format_input::<io::Stdout>(input, config, None).unwrap() //format_input::<io::Stdout>(input, config, None).unwrap()
syntax::with_globals(|| format_input_inner::<io::Stdout>(input, config, None)).unwrap()
} }
pub enum IdempotentCheckError { pub enum IdempotentCheckError {
@ -757,8 +752,7 @@ impl ConfigCodeBlock {
}); });
} }
fn formatted_has_diff(&self, file_map: &FileMap) -> bool { fn formatted_has_diff(&self, text: &str) -> bool {
let &(ref _file_name, ref text) = file_map.first().unwrap();
let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE); let compare = make_diff(self.code_block.as_ref().unwrap(), text, DIFF_CONTEXT_SIZE);
if !compare.is_empty() { if !compare.is_empty() {
self.print_diff(compare); self.print_diff(compare);
@ -778,12 +772,14 @@ impl ConfigCodeBlock {
} }
let input = Input::Text(self.code_block.as_ref().unwrap().to_owned()); let input = Input::Text(self.code_block.as_ref().unwrap().to_owned());
let config = self.get_block_config(); let mut config = self.get_block_config();
config.set().write_mode(WriteMode::Display);
let mut buf: Vec<u8> = vec![];
let (error_summary, file_map, _report) = let error_summary = format_input(input, &config, Some(&mut buf)).unwrap();
format_input::<io::Stdout>(input, &config, None).unwrap();
!self.has_parsing_errors(error_summary) && !self.formatted_has_diff(&file_map) !self.has_parsing_errors(error_summary)
&& !self.formatted_has_diff(&String::from_utf8(buf).unwrap())
} }
// Extract a code block from the iterator. Behavior: // Extract a code block from the iterator. Behavior:

View File

@ -70,7 +70,7 @@ pub struct FmtVisitor<'a> {
pub snippet_provider: &'a SnippetProvider<'a>, pub snippet_provider: &'a SnippetProvider<'a>,
pub line_number: usize, pub line_number: usize,
pub skipped_range: Vec<(usize, usize)>, pub skipped_range: Vec<(usize, usize)>,
pub report: FormatReport, pub(crate) report: FormatReport,
} }
impl<'b, 'a: 'b> FmtVisitor<'a> { impl<'b, 'a: 'b> FmtVisitor<'a> {
@ -561,7 +561,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
) )
} }
pub fn from_codemap( pub(crate) fn from_codemap(
parse_session: &'a ParseSess, parse_session: &'a ParseSess,
config: &'a Config, config: &'a Config,
snippet_provider: &'a SnippetProvider, snippet_provider: &'a SnippetProvider,