internal/lsp: do not format the file on import organization

Updates golang/go#30843
Updates golang/go#35114

Change-Id: Id3f66d20b1ada9e53298b2370214b23b87bb0680
Reviewed-on: https://go-review.googlesource.com/c/tools/+/204557
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
diff --git a/internal/lsp/cache/session.go b/internal/lsp/cache/session.go
index 6b5b900..f2eaa7a 100644
--- a/internal/lsp/cache/session.go
+++ b/internal/lsp/cache/session.go
@@ -18,7 +18,6 @@
 	"golang.org/x/tools/internal/lsp/source"
 	"golang.org/x/tools/internal/lsp/telemetry"
 	"golang.org/x/tools/internal/span"
-	"golang.org/x/tools/internal/telemetry/log"
 	"golang.org/x/tools/internal/telemetry/trace"
 	"golang.org/x/tools/internal/xcontext"
 	errors "golang.org/x/xerrors"
@@ -320,13 +319,11 @@
 		hash:      hashContents(data),
 		unchanged: true,
 	}
-	_, hash, err := s.cache.GetFile(uri, kind).Read(ctx)
-	if err != nil {
-		log.Error(ctx, "failed to read", err, telemetry.File)
-		return
-	}
-	if hash == s.overlays[uri].hash {
-		s.overlays[uri].sameContentOnDisk = true
+	// If the file is on disk, check if its content is the same as the overlay.
+	if _, hash, err := s.cache.GetFile(uri, kind).Read(ctx); err == nil {
+		if hash == s.overlays[uri].hash {
+			s.overlays[uri].sameContentOnDisk = true
+		}
 	}
 }
 
diff --git a/internal/lsp/source/format.go b/internal/lsp/source/format.go
index 23d5860..7a2608a 100644
--- a/internal/lsp/source/format.go
+++ b/internal/lsp/source/format.go
@@ -197,6 +197,10 @@
 		if err != nil {
 			return err
 		}
+		// Do not change the file if there are no import fixes.
+		if len(fixes) == 0 {
+			return nil
+		}
 		// Apply all of the import fixes to the file.
 		formatted, err := imports.ApplyFixes(fixes, f.URI().Filename(), data, options)
 		if err != nil {
diff --git a/internal/lsp/testdata/imports/good_imports.go b/internal/lsp/testdata/imports/good_imports.go
index 667487c..40283fa 100644
--- a/internal/lsp/testdata/imports/good_imports.go
+++ b/internal/lsp/testdata/imports/good_imports.go
@@ -4,4 +4,4 @@
 
 func _() {
 	fmt.Println("")
-}
\ No newline at end of file
+}