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.

Adam Mackler
  • 1,980
  • 1
  • 18
  • 32

2 Answers2

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()
vvladymyrov
  • 5,715
  • 2
  • 32
  • 50
mirandes
  • 957
  • 10
  • 10
  • 1
    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. – Adam Mackler Jul 31 '13 at 01:17
  • 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. – mirandes Jul 31 '13 at 10:53
  • 1
    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`. – Adam Mackler Jul 31 '13 at 15:13
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:jason@planet57.com">Jason Dillon</a>
 * @since 2.0
 */
public class FileHistory

Compare to Scala REPL internal history.

som-snytt
  • 39,429
  • 2
  • 47
  • 129
  • 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](http://jline.sourceforge.net/apidocs/index.html). Now I see I was looking at the wrong version. And there's no javadocs on the v2 site [here](http://jline.github.io/jline2/project-info.html). Oh yeah, [it's right here](https://github.com/jline/jline2/blob/master/src/main/java/jline/console/history/FileHistory.java). How did I miss that? Thank you! – Adam Mackler Jul 31 '13 at 14:44