How to save and load history between invocations of Scala JLine
Asked Answered
C

2

4

I'm using Scala JLine in my CLI program. It's working fine, but it forgets my history every time I restart my program. I see a class called FileHistory, and I see the ConsoleReader class has a method called setHistory() which takes an instance of FileHistory. I would expect calling that method would cause it to create or load and save a file containing my history. But it doesn't.

Unfortunately the documentation is nigh nonexistent. How can I make it so the next time I run my JLine-enabled program it remembers the commands that I had typed in the previous run?

Update

Correct answer given below by mirandes. Thanks to mirandes and som-snytt both for their helpful (yea solvent) responses.

Carcassonne answered 29/7, 2013 at 22:18 Comment(3)
JLine is actually a separate library, Scala only has it embedded in its distribution.Nonoccurrence
My flush answer arrived first... BTW.Bucci
Your response did arrive first by seven hours, som-snytt. I agree. Kudos to you for speed.Carcassonne
W
6

This worked for me:

import scala.tools.jline.console.ConsoleReader
import scala.tools.jline.console.history.FileHistory
import java.io.File

val reader : ConsoleReader = new ConsoleReader() 

val history = new FileHistory(new File(".history"))
reader.setHistory(history) 

Before exiting the app, make sure you flush the history.

reader.getHistory.asInstanceOf[FileHistory].flush()
Wholehearted answered 31/7, 2013 at 1:9 Comment(3)
And it's saving a file called .history in the same directory from which you run the program? Are you doing anything to save the file before your program exits? Maybe I'm quitting my program wrong.Carcassonne
I have edited the answer to add a necessary flush() in the end. It can save in the current dir, or at any full path you want.Wholehearted
Works, thanks!! One thing though: I had to change new File(".history") to (new File(".history")).getAbsoluteFile for some reason. I'm guessing it has something to do with sbt.Carcassonne
B
1

There's a comment. I thought you said there wasn't any documentation?

/**
 * {@link History} using a file for persistent backing.
 * <p/>
 * Implementers should install shutdown hook to call {@link FileHistory#flush}
 * to save history to disk.
 *
 * @author <a href="mailto:[email protected]">Jason Dillon</a>
 * @since 2.0
 */
public class FileHistory

Compare to Scala REPL internal history.

Bucci answered 31/7, 2013 at 8:11 Comment(1)
Obviously I need to work on my documentation-finding skills. I don't see this in the javadocs jar that comes with the Scala-version maven artifact, nor did I see it when I looked at the Java version docs here. Now I see I was looking at the wrong version. And there's no javadocs on the v2 site here. Oh yeah, it's right here. How did I miss that? Thank you!Carcassonne

© 2022 - 2024 — McMap. All rights reserved.