Makes the timestamp in the properties files header reproducible when SOURCE_DATE_EPOC...
authorEmmanuel Bourg <ebourg@apache.org>
Wed, 17 Jan 2024 11:09:47 +0000 (12:09 +0100)
committerMatthias Klose <doko@ubuntu.com>
Wed, 17 Jan 2024 11:09:47 +0000 (12:09 +0100)
Forwarded: no

Gbp-Pq: Name reproducible-properties-timestamp.diff

src/java.base/share/classes/java/util/Properties.java

index 21b2982b82c86fa8b40aa25b82c05fbbf18b9311..602203d14c0981583ef4b12e45731ac4ab78035c 100644 (file)
@@ -54,6 +54,9 @@ import jdk.internal.misc.Unsafe;
 import jdk.internal.util.ArraysSupport;
 import jdk.internal.util.xml.PropertiesDefaultHandler;
 
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+
 /**
  * The {@code Properties} class represents a persistent set of
  * properties. The {@code Properties} can be saved to a stream
@@ -903,7 +906,7 @@ public class Properties extends Hashtable<Object,Object> {
         if (comments != null) {
             writeComments(bw, comments);
         }
-        bw.write("#" + new Date().toString());
+        bw.write("#" + getFormattedTimestamp());
         bw.newLine();
         synchronized (this) {
             for (Map.Entry<Object, Object> e : entrySet()) {
@@ -1555,4 +1558,27 @@ public class Properties extends Hashtable<Object,Object> {
         }
         this.map = map;
     }
+
+    /**
+     * Returns a formatted timestamp to be used in the properties file header.
+     * The date used is the current date, unless the SOURCE_DATE_EPOCH
+     * environment variable is specified. In this case the format used is
+     * locale and timezone insensitive to ensure the output is reproducible.
+     */
+    @SuppressWarnings("removal")
+    private String getFormattedTimestamp() {
+        String epoch = AccessController.doPrivileged(new PrivilegedAction<String>(){
+            public String run() { return System.getenv("SOURCE_DATE_EPOCH"); }
+        });
+
+        if (epoch == null) {
+            return new Date().toString();
+        } else {
+            // Use the SOURCE_DATE_EPOCH timestamp and make the format locale/timezone insensitive
+            java.text.SimpleDateFormat fmt = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", java.util.Locale.ENGLISH);
+            fmt.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
+            Date date = new Date(1000 * Long.parseLong(epoch));
+            return fmt.format(date);
+        }
+    }
 }