From 434d3f155d6f98b942d21dc79fb7e183c47c9635 Mon Sep 17 00:00:00 2001 From: Zxilly Date: Wed, 13 Nov 2024 18:31:37 +0800 Subject: [PATCH] cmd/goimports: ignore line breaks when comparing --- cmd/goimports/goimports.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/cmd/goimports/goimports.go b/cmd/goimports/goimports.go index dcb5023a2e7..3598f81d7b9 100644 --- a/cmd/goimports/goimports.go +++ b/cmd/goimports/goimports.go @@ -143,7 +143,7 @@ func processFile(filename string, in io.Reader, out io.Writer, argType argumentT return err } - if !bytes.Equal(src, res) { + if !compareByLine(src, res) { // formatting has changed if *list { fmt.Fprintln(out, filename) @@ -183,6 +183,26 @@ func processFile(filename string, in io.Reader, out io.Writer, argType argumentT return err } +func compareByLine(src, dst []byte) bool { + src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1) + // dst is already normalized by imports.Process + + linesA := bytes.Split(src, []byte("\n")) + linesB := bytes.Split(dst, []byte("\n")) + + if len(linesA) != len(linesB) { + return false + } + + for i := range linesA { + if !bytes.Equal(linesA[i], linesB[i]) { + return false + } + } + + return true +} + func visitFile(path string, f os.FileInfo, err error) error { if err == nil && isGoFile(f) { err = processFile(path, nil, os.Stdout, multipleArg)