From 3463ab7d0f0868862d713ab628380c11cb105e43 Mon Sep 17 00:00:00 2001 From: Amy Boyd Date: Mon, 4 Jul 2016 13:54:44 +0100 Subject: [PATCH] Add fixer for end-of-line characters. --- editorconfig/full_file_fixers.go | 31 +++++++++++++++++++++++++++ editorconfig/full_file_fixers_test.go | 24 +++++++++++++++++++++ editorconfig/utils.go | 7 ++++++ 3 files changed, 62 insertions(+) create mode 100644 editorconfig/full_file_fixers.go create mode 100644 editorconfig/full_file_fixers_test.go diff --git a/editorconfig/full_file_fixers.go b/editorconfig/full_file_fixers.go new file mode 100644 index 0000000..68ad55b --- /dev/null +++ b/editorconfig/full_file_fixers.go @@ -0,0 +1,31 @@ +package editorconfig + +import ( + "regexp" + "strings" +) + +type FullFileFixer func(ruleValue string, fileContent string) string + +func FixEndOfLineRule(ruleValue string, fileContent string) string { + ruleValueLowercase := strings.ToLower(ruleValue) + + if ruleValueLowercase == "lf" { + fileContent = crlfRegexp.ReplaceAllString(fileContent, "\n") + fileContent = crRegexp.ReplaceAllString(fileContent, "\n") + return fileContent + } + + if ruleValueLowercase == "cr" { + fileContent = crlfRegexp.ReplaceAllString(fileContent, "\r") + fileContent = lfRegexp.ReplaceAllString(fileContent, "\r") + return fileContent + } + + if ruleValueLowercase == "crlf" { + fileContent = regexp.MustCompile("(\r\n|\r|\n)").ReplaceAllString(fileContent, "\r\n") + return fileContent + } + + return fileContent +} diff --git a/editorconfig/full_file_fixers_test.go b/editorconfig/full_file_fixers_test.go new file mode 100644 index 0000000..5ecfecb --- /dev/null +++ b/editorconfig/full_file_fixers_test.go @@ -0,0 +1,24 @@ +package editorconfig + +import ( + "testing" +) + +func TestFixEndOfLineRule(t *testing.T) { + input := "\nline\nline 2\rline 3 \n \r\n\r" + + toLfResult := FixEndOfLineRule("lF", input) + if toLfResult != "\nline\nline 2\nline 3 \n \n\n" { + t.Error("Converting to LF did not work, got: " + GetErrorWithLineBreaksVisible(toLfResult)) + } + + toCrResult := FixEndOfLineRule("Cr", input) + if toCrResult != "\rline\rline 2\rline 3 \r \r\r" { + t.Error("Converting to CR did not work, got: " + GetErrorWithLineBreaksVisible(toCrResult)) + } + + toCrlfResult := FixEndOfLineRule("CrlF", input) + if toCrlfResult != "\r\nline\r\nline 2\r\nline 3 \r\n \r\n\r\n" { + t.Error("Converting to CRLR did not work, got: " + GetErrorWithLineBreaksVisible(toCrlfResult)) + } +} diff --git a/editorconfig/utils.go b/editorconfig/utils.go index fefd1a2..33e9619 100644 --- a/editorconfig/utils.go +++ b/editorconfig/utils.go @@ -47,3 +47,10 @@ func ExitBecauseOfInternalError(err string) { fmt.Println(err) os.Exit(2) } + +func GetErrorWithLineBreaksVisible(s string) string { + s = lfRegexp.ReplaceAllString(s, `\n`) + s = crRegexp.ReplaceAllString(s, `\r`) + s = crlfRegexp.ReplaceAllString(s, `\r\n`) + return s +}