From 478471d8866d55b50adf995fac18356d5c16105a Mon Sep 17 00:00:00 2001 From: Auca Coyan Date: Thu, 15 Jun 2023 08:52:14 -0300 Subject: [PATCH] :sparkles: add check if its missing a newline at EOF (#28) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I resolved my git and did properly the #27 PR 😄 --- src/formatting.rs | 12 ++++++++++-- src/lib.rs | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/formatting.rs b/src/formatting.rs index 936864d..5b3d11e 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -137,8 +137,8 @@ pub fn format_inner(contents: &[u8], _config: &Config) -> Vec { // cleanup start = span.end + 1; } - // just before writing, append a new line to the file. - out = insert_newline(out); + // just before writing, check if a new line is needed. + out = add_newline_at_end_of_file(out); // timer = timer.done_formatting() out @@ -156,6 +156,14 @@ fn insert_newline(mut bytes: Vec) -> Vec { bytes } +/// Checks if it missing a new line. If true, adds it. +fn add_newline_at_end_of_file(out: Vec) -> Vec { + match out.last() { + Some(&b'\n') => out, + _ => insert_newline(out), + } +} + /// Given a slice of bytes, strip all spaces, new lines and tabs found within /// /// Because you don't know how the incoming code is formatted, diff --git a/src/lib.rs b/src/lib.rs index 292f22f..ade417e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -120,6 +120,20 @@ myfunc(one) run_test(input, expected); } + #[test] + fn add_new_line() { + let input = "null"; + let expected = "null\n"; + run_test(input, expected); + } + + #[test] + fn remove_additional_lines() { + let input = "let one = 1\n\n\n"; + let expected = "let one = 1\n"; + run_test(input, expected); + } + #[test] fn remove_leading_whitespace() { let input = " 0";