Skip to content

Commit

Permalink
Fix history trim for non-timestamped files (#873)
Browse files Browse the repository at this point in the history
  • Loading branch information
derklaro authored Oct 20, 2023
1 parent cde17f7 commit 7ca9dc2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -247,12 +247,16 @@ protected void trimHistory(Path path, int max) throws IOException {
Log.trace("Trimming history path: ", path);
// Load all history entries
LinkedList<Entry> allItems = new LinkedList<>();
try (BufferedReader reader = Files.newBufferedReader(path)) {
reader.lines().forEach(l -> {
int idx = l.indexOf(':');
Instant time = Instant.ofEpochMilli(Long.parseLong(l.substring(0, idx)));
String line = unescape(l.substring(idx + 1));
allItems.add(createEntry(allItems.size(), time, line));
try (BufferedReader historyFileReader = Files.newBufferedReader(path)) {
historyFileReader.lines().forEach(l -> {
if (reader.isSet(LineReader.Option.HISTORY_TIMESTAMPED)) {
int idx = l.indexOf(':');
Instant time = Instant.ofEpochMilli(Long.parseLong(l.substring(0, idx)));
String line = unescape(l.substring(idx + 1));
allItems.add(createEntry(allItems.size(), time, line));
} else {
allItems.add(createEntry(allItems.size(), Instant.now(), unescape(l)));
}
});
}
// Remove duplicates
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
Expand All @@ -19,6 +20,7 @@
import org.jline.reader.LineReader;
import org.jline.reader.impl.ReaderTestSupport;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

Expand Down Expand Up @@ -97,4 +99,32 @@ public void testFileHistory() throws Exception {
lines = Files.readAllLines(Paths.get("test"));
assertEquals(cmdsPerThread * (nbThreads + 1), lines.size());
}

private void testHistoryTrim(boolean timestamped) {
reader.unsetOpt(LineReader.Option.HISTORY_INCREMENTAL);
reader.option(LineReader.Option.HISTORY_TIMESTAMPED, timestamped);
reader.setVariable(LineReader.HISTORY_FILE_SIZE, 5);
reader.setVariable(LineReader.HISTORY_FILE, Paths.get("test"));

DefaultHistory history = new DefaultHistory(reader);
for (int i = 0; i < 50; i++) {
history.add(Instant.now(), "Hello " + i);
if (i % 5 == 0) {
Assertions.assertDoesNotThrow(history::save);
}
}

Assertions.assertDoesNotThrow(history::load);
Assertions.assertEquals(5, history.size());
}

@Test
public void testHistoryTrimNonTimestamped() {
testHistoryTrim(false);
}

@Test
public void testHistoryTrimTimestamped() {
testHistoryTrim(true);
}
}

0 comments on commit 7ca9dc2

Please sign in to comment.