From cb3229b8de756324c27c71b308537bb9f000f2f9 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 31 Jul 2018 12:22:54 -0700 Subject: [PATCH] Expose an interface to apply fixes on-by-one This commit exposes an interface that Cargo can use to apply fixes one-by-one and know which fixes failed and which succeeded. --- src/lib.rs | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c109ef7..1532e4b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -210,22 +210,39 @@ pub fn collect_suggestions( } } -pub fn apply_suggestions(code: &str, suggestions: &[Suggestion]) -> Result { - use replace::Data; +pub struct CodeFix { + data: replace::Data, +} - let mut fixed = Data::new(code.as_bytes()); +impl CodeFix { + pub fn new(s: &str) -> CodeFix { + CodeFix { + data: replace::Data::new(s.as_bytes()), + } + } - for sug in suggestions.iter().rev() { - for sol in &sug.solutions { + pub fn apply(&mut self, suggestion: &Suggestion) -> Result<(), Error> { + for sol in &suggestion.solutions { for r in &sol.replacements { - fixed.replace_range( + self.data.replace_range( r.snippet.range.start, r.snippet.range.end.saturating_sub(1), r.replacement.as_bytes(), )?; } } + Ok(()) } - Ok(String::from_utf8(fixed.to_vec())?) + pub fn finish(&self) -> Result { + Ok(String::from_utf8(self.data.to_vec())?) + } +} + +pub fn apply_suggestions(code: &str, suggestions: &[Suggestion]) -> Result { + let mut fix = CodeFix::new(code); + for suggestion in suggestions.iter().rev() { + fix.apply(suggestion)?; + } + fix.finish() }