Repository: dotenv-linter/dotenv-linter
Pull request #263 (2020-08-16 13:10:36)

Implement EndingBlankLineFixer
Implements a fixer to add trailing blank lines to files.

Closes: https://github.com/dotenv-linter/dotenv-linter/issues/244 (see that thread for some minor discussion on approach).

#### ✔ Checklist:
<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->

- [x] This PR has been added to [CHANGELOG.md](https://github.com/dotenv-linter/dotenv-linter/blob/master/CHANGELOG.md) (at the top of the list);
- [x] Tests for the changes have been added (for bug fixes / features);
- [ ] Docs have been added / updated (for bug fixes / features).

<!-- _NOTE: these things are not required to open a PR and can be done afterwards / while the PR is open._ -->



Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e75b671..81e23d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ # Changelog
 
 ## [Unreleased]
 ### 🚀 Added
+- Add autofix for EndingBlankLine [#263](https://github.com/dotenv-linter/dotenv-linter/pull/263) ([@baile320](https://github.com/baile320))
 - Add test for two keys that only differ in case [#269](https://github.com/dotenv-linter/dotenv-linter/pull/269) ([@yanakad](https://github.com/yanakad))
 - Add autofix for TrailingWhitespace [#255](https://github.com/dotenv-linter/dotenv-linter/pull/255) ([@gregcline](https://github.com/gregcline))
 - Add fixer: KeyWithoutValueFixer [#254](https://github.com/dotenv-linter/dotenv-linter/pull/254) ([@unexge](https://github.com/unexge))
diff --git a/src/fixes.rs b/src/fixes.rs
index 4733683..b324fdd 100644
--- a/src/fixes.rs
+++ b/src/fixes.rs
@@ -1,5 +1,6 @@
 use crate::common::*;
 
+mod ending_blank_line;
 mod key_without_value;
 mod lowercase_key;
 mod quote_character;
@@ -45,6 +46,7 @@ fn fixlist() -> Vec<Box<dyn Fix>> {
         // Then we should run the fixers that handle the line entry collection at whole.
         // And at the end we should run the fixer for ExtraBlankLine check (because the previous
         // fixers can create additional extra blank lines).
+        Box::new(ending_blank_line::EndingBlankLineFixer::default()),
     ]
 }
 
diff --git a/src/fixes/ending_blank_line.rs b/src/fixes/ending_blank_line.rs
new file mode 100644
index 0000000..fc31e60
--- /dev/null
+++ b/src/fixes/ending_blank_line.rs
@@ -0,0 +1,113 @@
+use super::Fix;
+use crate::common::*;
+
+pub(crate) struct EndingBlankLineFixer<'a> {
+    name: &'a str,
+}
+
+impl Default for EndingBlankLineFixer<'_> {
+    fn default() -> Self {
+        Self {
+            name: "EndingBlankLine",
+        }
+    }
+}
+
+impl Fix for EndingBlankLineFixer<'_> {
+    fn name(&self) -> &str {
+        self.name
+    }
+
+    fn fix_warnings(
+        &self,
+        warnings: Vec<&mut Warning>,
+        lines: &mut Vec<LineEntry>,
+    ) -> Option<usize> {
+        let file = lines.first()?.file.clone();
+        let last_line = lines.last()?;
+
+        if !last_line.raw_string.ends_with(LF) {
+            lines.push(LineEntry {
+                number: lines.len() + 1,
+                file,
+                raw_string: LF.to_string(),
+            });
+
+            for warning in warnings {
+                warning.mark_as_fixed()
+            }
+
+            return Some(1);
+        }
+
+        Some(0)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::path::PathBuf;
+
+    #[test]
+    fn fix_warnings_test() {
+        let fixer = EndingBlankLineFixer::default();
+        let mut lines = vec![
+            LineEntry {
+                number: 1,
+                file: FileEntry {
+                    path: PathBuf::from(".env"),
+                    file_name: ".env".to_string(),
+                    total_lines: 2,
+                },
+                raw_string: String::from("FOO=BAR"),
+            },
+            LineEntry {
+                number: 2,
+                file: FileEntry {
+                    path: PathBuf::from(".env"),
+                    file_name: ".env".to_string(),
+                    total_lines: 2,
+                },
+                raw_string: String::from("Z=Y"),
+            },
+        ];
+        let mut warning = Warning::new(
+            lines[1].clone(),
+            "EndingBlankLine",
+            String::from("No blank line at the end of the file"),
+        );
+
+        assert_eq!(Some(1), fixer.fix_warnings(vec![&mut warning], &mut lines));
+        assert_eq!("\n", lines[2].raw_string);
+        assert!(warning.is_fixed);
+    }
+
+    #[test]
+    fn ending_blank_line_exist_test() {
+        let fixer = EndingBlankLineFixer::default();
+        let mut lines = vec![
+            LineEntry {
+                number: 1,
+                file: FileEntry {
+                    path: PathBuf::from(".env"),
+                    file_name: ".env".to_string(),
+                    total_lines: 2,
+                },
+                raw_string: String::from("FOO=BAR"),
+            },
+            LineEntry {
+                number: 2,
+                file: FileEntry {
+                    path: PathBuf::from(".env"),
+                    file_name: ".env".to_string(),
+                    total_lines: 2,
+                },
+                raw_string: String::from(LF),
+            },
+        ];
+
+        assert_eq!(Some(0), fixer.fix_warnings(vec![], &mut lines));
+        assert_eq!(lines.len(), 2);
+    }
+}


Test patch:
diff --git a/tests/fixes/ending_blank_line.rs b/tests/fixes/ending_blank_line.rs
new file mode 100644
index 0000000..f33efec
--- /dev/null
+++ b/tests/fixes/ending_blank_line.rs
@@ -0,0 +1,16 @@
+use crate::common::TestDir;
+
+#[test]
+fn ending_blank_line() {
+    let testdir = TestDir::new();
+    let testfile = testdir.create_testfile(".env", "ABC=DEF\nFOO=BAR");
+    let expected_output = String::from(
+        "Fixed warnings:\n\
+        .env:2 EndingBlankLine: No blank line at the end of the file\n",
+    );
+    testdir.test_command_fix_success(expected_output);
+
+    assert_eq!(testfile.contents().as_str(), "ABC=DEF\nFOO=BAR\n");
+
+    testdir.close();
+}
diff --git a/tests/fixes/mod.rs b/tests/fixes/mod.rs
index 31e4ac7..99ff55a 100644
--- a/tests/fixes/mod.rs
+++ b/tests/fixes/mod.rs
@@ -2,6 +2,7 @@
 
 use crate::common::TestDir;
 
+mod ending_blank_line;
 mod space_character;
 mod trailing_whitespace;