From 0e16bc12552f680fd5c8cecbba7fb87978cbe2a4 Mon Sep 17 00:00:00 2001 From: Amy Boyd Date: Mon, 4 Jul 2016 14:04:58 +0100 Subject: [PATCH] Add fixer for trailing new-line rule. --- editorconfig/full_file_fixers.go | 21 ++++++++++++++++++ editorconfig/full_file_fixers_test.go | 32 +++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/editorconfig/full_file_fixers.go b/editorconfig/full_file_fixers.go index 68ad55b..3b48c4a 100644 --- a/editorconfig/full_file_fixers.go +++ b/editorconfig/full_file_fixers.go @@ -29,3 +29,24 @@ func FixEndOfLineRule(ruleValue string, fileContent string) string { return fileContent } + +/** + * This must be called before FixEndOfLineRule so the \n added will be converted to whatever the + * 'end_of_line' rule dictates. + */ +func FixInsertFinalNewLineRule(ruleValue string, fileContent string) string { + ruleValueLowercase := strings.ToLower(ruleValue) + + if ruleValueLowercase == "true" && !endsWithFinalNewLineRegexp.MatchString(fileContent) { + return fileContent + "\n" + } + + if ruleValueLowercase == "false" { + for endsWithFinalNewLineRegexp.MatchString(fileContent) { + fileContent = endsWithFinalNewLineRegexp.ReplaceAllString(fileContent, "") + } + return fileContent + } + + return fileContent +} diff --git a/editorconfig/full_file_fixers_test.go b/editorconfig/full_file_fixers_test.go index 5ecfecb..da20ddc 100644 --- a/editorconfig/full_file_fixers_test.go +++ b/editorconfig/full_file_fixers_test.go @@ -22,3 +22,35 @@ func TestFixEndOfLineRule(t *testing.T) { t.Error("Converting to CRLR did not work, got: " + GetErrorWithLineBreaksVisible(toCrlfResult)) } } + +func TestFixInsertFinalNewLineRule(t *testing.T) { + input1 := "a\nb\nc\n" + result1 := FixInsertFinalNewLineRule("true", input1) + if result1 != input1 { + t.Error("String was changed despite already having a line at the end") + } + + input2 := "a\rb\rc\r\r" + result2 := FixInsertFinalNewLineRule("true", input2) + if result2 != input2 { + t.Error("String was changed despite already having a line at the end") + } + + input3 := "a\r\nb\r\nc\r\n" + result3 := FixInsertFinalNewLineRule("true", input3) + if result3 != input3 { + t.Error("String was changed despite already having a line at the end") + } + + input4 := "a\nb" + result4 := FixInsertFinalNewLineRule("true", input4) + if result4 != "a\nb\n" { + t.Error("Line was not added at the end") + } + + input5 := "a\r\nb\r\nc\r\n\n\n\r" + result5 := FixInsertFinalNewLineRule("false", input5) + if result5 != "a\r\nb\r\nc" { + t.Error("Trailing lines were not removed") + } +}