From 324a333e671ed521138ad50fe463ed187874176e Mon Sep 17 00:00:00 2001 From: Akshay Date: Sat, 6 Nov 2021 14:51:55 +0530 Subject: introducing "streaming" option to check, fix and single --- bin/src/fix.rs | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 86 insertions(+), 2 deletions(-) (limited to 'bin/src/fix.rs') diff --git a/bin/src/fix.rs b/bin/src/fix.rs index c378c13..e4ea94d 100644 --- a/bin/src/fix.rs +++ b/bin/src/fix.rs @@ -3,10 +3,10 @@ use std::borrow::Cow; use rnix::TextRange; mod all; -pub use all::all; +use all::all; mod single; -pub use single::single; +use single::single; type Source<'a> = Cow<'a, str>; @@ -30,3 +30,87 @@ impl<'a> FixResult<'a> { } } } + +pub mod main { + use std::borrow::Cow; + + use crate::{ + config::{Fix as FixConfig, FixOut, Single as SingleConfig}, + err::{FixErr, StatixErr}, + }; + + use similar::TextDiff; + + pub fn all(fix_config: FixConfig) -> Result<(), StatixErr> { + let vfs = fix_config.vfs()?; + for entry in vfs.iter() { + match (fix_config.out(), super::all(entry.contents)) { + (FixOut::Diff, fix_result) => { + let src = fix_result + .map(|r| r.src) + .unwrap_or(Cow::Borrowed(entry.contents)); + let text_diff = TextDiff::from_lines(entry.contents, &src); + let old_file = format!("{}", entry.file_path.display()); + let new_file = format!("{} [fixed]", entry.file_path.display()); + println!( + "{}", + text_diff + .unified_diff() + .context_radius(4) + .header(&old_file, &new_file) + ); + } + (FixOut::Stream, fix_result) => { + let src = fix_result + .map(|r| r.src) + .unwrap_or(Cow::Borrowed(entry.contents)); + println!("{}", &src) + } + (FixOut::Write, Some(fix_result)) => { + let path = entry.file_path; + std::fs::write(path, &*fix_result.src).map_err(FixErr::InvalidPath)?; + } + _ => (), + }; + } + Ok(()) + } + + pub fn single(single_config: SingleConfig) -> Result<(), StatixErr> { + let vfs = single_config.vfs()?; + let entry = vfs.iter().next().unwrap(); + let path = entry.file_path.display().to_string(); + let original_src = entry.contents; + let (line, col) = single_config.position; + + match (single_config.out(), super::single(line, col, original_src)) { + (FixOut::Diff, single_result) => { + let fixed_src = single_result + .map(|r| r.src) + .unwrap_or(Cow::Borrowed(original_src)); + let text_diff = TextDiff::from_lines(original_src, &fixed_src); + let old_file = &path; + let new_file = format!("{} [fixed]", &path); + println!( + "{}", + text_diff + .unified_diff() + .context_radius(4) + .header(&old_file, &new_file) + ); + } + (FixOut::Stream, single_result) => { + let src = single_result + .map(|r| r.src) + .unwrap_or(Cow::Borrowed(original_src)); + println!("{}", &src) + } + (FixOut::Write, Ok(single_result)) => { + let path = entry.file_path; + std::fs::write(path, &*single_result.src).map_err(FixErr::InvalidPath)?; + } + (_, Err(e)) => return Err(e.into()), + }; + Ok(()) + } +} -- cgit v1.2.3