From 7f3b2120fe80c5b81a932d3f864e564a43a04e24 Mon Sep 17 00:00:00 2001 From: Jonah Graham Date: Fri, 28 Jul 2017 10:53:01 +0100 Subject: [PATCH] Bug 520257: Avoid touching file with unchanged content When creating the settings.xml, avoid writing to the file unless the contents have actually changed. This avoids a resource delta that caused unneeded rebuilds. Change-Id: I83cea84e96d006f99a1c264f283d4bba4ad68784 --- .../eclipse/cdt/internal/core/XmlUtil.java | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/core/org.eclipse.cdt.core/utils/org/eclipse/cdt/internal/core/XmlUtil.java b/core/org.eclipse.cdt.core/utils/org/eclipse/cdt/internal/core/XmlUtil.java index 8eb2a077426..5f86b3da8c4 100644 --- a/core/org.eclipse.cdt.core/utils/org/eclipse/cdt/internal/core/XmlUtil.java +++ b/core/org.eclipse.cdt.core/utils/org/eclipse/cdt/internal/core/XmlUtil.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; +import java.util.Arrays; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -384,10 +385,14 @@ public class XmlUtil { String utfString = new String(toByteArray(doc), ENCODING_UTF_8); String lineSeparator = Util.getLineSeparator(file); utfString = XmlUtil.replaceLineSeparatorInternal(utfString, lineSeparator); - InputStream input = new ByteArrayInputStream(utfString.getBytes(ENCODING_UTF_8)); + byte[] newContents = utfString.getBytes(ENCODING_UTF_8); + InputStream input = new ByteArrayInputStream(newContents); if (file.exists()) { - file.setContents(input, IResource.FORCE, null); + byte[] existingContents = readFile(file); + if (!Arrays.equals(existingContents, newContents)) { + file.setContents(input, IResource.FORCE, null); + } } else { file.create(input, IResource.FORCE, null); } @@ -395,6 +400,28 @@ public class XmlUtil { } } + /** + * Read whole file, returning null on any error. + */ + private static byte[] readFile(IFile file) { + try (InputStream is = file.getContents(true)) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + + int nRead; + byte[] data = new byte[4096]; + + while ((nRead = is.read(data)) != -1) { + buffer.write(data, 0, nRead); + } + + buffer.flush(); + + return buffer.toByteArray(); + } catch (IOException | CoreException e) { + return null; + } + } + /** * Serialize XML Document into a string. *