Merge pull request #835 from chiliec/sorted-config-file

Write yacy.conf with alphabetically sorted keys
This commit is contained in:
Michael Christen authored and GitHub committed 2026-09-23 08:34:22 +02:00
commit b50b76bd55
2 files changed
+35 -1

No files matched your search

+2 -1
View File
@@ -56,6 +56,7 @@ import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.GZIPInputStream;
@@ -539,7 +540,7 @@ public final class FileUtils {
final Object lock = SAVE_MAP_LOCKS.computeIfAbsent(lockKey, k -> new Object());
synchronized (lock) {
/* Take the snapshot in write order so delayed callers cannot persist stale state. */
final Map<String, String> propsCopy = new HashMap<>(props);
final Map<String, String> propsCopy = new TreeMap<>(props);
File tf = null;
PrintWriter pw = null;
try {
@@ -23,12 +23,18 @@ package net.yacy.kelondro.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.BeforeClass;
@@ -258,4 +264,31 @@ public class FileUtilsTest {
Assert.assertEquals(sourceBytes.length, FileUtils.read(source, sourceBytes.length + 10).length);
}
}
/**
* Test saving a map to a file writes keys in a stable alphabetical order.
* @throws IOException when a read/write error occurred
*/
@Test
public void testSaveMapSortedKeys() throws IOException {
final Map<String, String> props = new HashMap<>();
props.put("zeta", "1");
props.put("alpha", "2");
props.put("mu", "3");
props.put("beta", "4");
final File file = File.createTempFile("FileUtilsTest", ".conf");
try {
FileUtils.saveMap(file, props, "test");
final List<String> keys = new ArrayList<>();
for (final String line : Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)) {
if (!line.startsWith("#")) {
keys.add(line.substring(0, line.indexOf('=')));
}
}
Assert.assertEquals(List.of("alpha", "beta", "mu", "zeta"), keys);
Assert.assertEquals(props, FileUtils.loadMap(file));
} finally {
file.delete();
}
}
}