internal/cmd: print generated filename only when contents change

Printing the filenames of regenerated files only when the contents
change makes it easier to tell when a change has produced the expected
result in the generated file output.

Change-Id: I74d0020be1de3d287bb8400ba290131008859bf1
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/220356
Reviewed-by: Joe Tsai <joetsai@google.com>
diff --git a/internal/cmd/generate-protos/main.go b/internal/cmd/generate-protos/main.go
index 00dc876..c217e66 100644
--- a/internal/cmd/generate-protos/main.go
+++ b/internal/cmd/generate-protos/main.go
@@ -7,6 +7,7 @@
 package main
 
 import (
+	"bytes"
 	"flag"
 	"fmt"
 	"go/format"
@@ -304,8 +305,9 @@
 		dstPath := filepath.Join(dstDir, relPath)
 
 		if run {
-			fmt.Println("#", relPath)
-			copyFile(dstPath, srcPath)
+			if copyFile(dstPath, srcPath) {
+				fmt.Println("#", relPath)
+			}
 		} else {
 			cmd := exec.Command("diff", dstPath, srcPath, "-N", "-u")
 			cmd.Stdout = os.Stdout
@@ -315,11 +317,16 @@
 	})
 }
 
-func copyFile(dstPath, srcPath string) {
-	b, err := ioutil.ReadFile(srcPath)
+func copyFile(dstPath, srcPath string) (changed bool) {
+	src, err := ioutil.ReadFile(srcPath)
 	check(err)
 	check(os.MkdirAll(filepath.Dir(dstPath), 0775))
-	check(ioutil.WriteFile(dstPath, b, 0664))
+	dst, _ := ioutil.ReadFile(dstPath)
+	if bytes.Equal(src, dst) {
+		return false
+	}
+	check(ioutil.WriteFile(dstPath, src, 0664))
+	return true
 }
 
 func protoMapOpt() string {
diff --git a/internal/cmd/generate-types/main.go b/internal/cmd/generate-types/main.go
index 62e147a..bf1da2b 100644
--- a/internal/cmd/generate-types/main.go
+++ b/internal/cmd/generate-types/main.go
@@ -226,8 +226,11 @@
 
 	absFile := filepath.Join(repoRoot, file)
 	if run {
-		fmt.Println("#", file)
-		check(ioutil.WriteFile(absFile, b, 0664))
+		prev, _ := ioutil.ReadFile(absFile)
+		if !bytes.Equal(b, prev) {
+			fmt.Println("#", file)
+			check(ioutil.WriteFile(absFile, b, 0664))
+		}
 	} else {
 		check(ioutil.WriteFile(absFile+".tmp", b, 0664))
 		defer os.Remove(absFile + ".tmp")