sbt/util/complete/LineReader.scala

88 lines
2.2 KiB
Scala
Raw Normal View History

2010-07-28 05:01:45 +02:00
/* sbt -- Simple Build Tool
* Copyright 2008, 2009 Mark Harrah
*/
package sbt
import jline.{Completor, ConsoleReader}
import java.io.File
import complete.Parser
2010-07-28 05:01:45 +02:00
abstract class JLine extends LineReader
{
protected[this] val reader: ConsoleReader
2011-10-13 08:12:30 +02:00
def readLine(prompt: String, mask: Option[Char] = None) = JLine.withJLine { unsynchronizedReadLine(prompt, mask) }
private[this] def unsynchronizedReadLine(prompt: String, mask: Option[Char]) =
(mask match {
case Some(m) => reader.readLine(prompt, m)
case None => reader.readLine(prompt)
}) match
2010-07-28 05:01:45 +02:00
{
case null => None
case x => Some(x.trim)
}
}
private object JLine
{
def terminal = jline.Terminal.getTerminal
def resetTerminal() = withTerminal { _ => jline.Terminal.resetTerminal }
private def withTerminal[T](f: jline.Terminal => T): T =
synchronized
{
val t = terminal
t.synchronized { f(t) }
}
def createReader() =
withTerminal { t =>
val cr = new ConsoleReader
t.enableEcho()
cr.setBellEnabled(false)
cr
}
def withJLine[T](action: => T): T =
withTerminal { t =>
t.disableEcho()
try { action }
finally { t.enableEcho() }
}
private[sbt] def initializeHistory(cr: ConsoleReader, historyPath: Option[File]): Unit =
2010-07-28 05:01:45 +02:00
for(historyLocation <- historyPath)
{
val historyFile = historyLocation.getAbsoluteFile
2010-07-28 05:01:45 +02:00
ErrorHandling.wideConvert
{
historyFile.getParentFile.mkdirs()
val history = cr.getHistory
history.setMaxSize(MaxHistorySize)
history.setHistoryFile(historyFile)
}
}
def simple(historyPath: Option[File]): SimpleReader = new SimpleReader(historyPath)
2010-07-28 05:01:45 +02:00
val MaxHistorySize = 500
}
trait LineReader
2010-07-28 05:01:45 +02:00
{
2011-10-13 08:12:30 +02:00
def readLine(prompt: String, mask: Option[Char] = None): Option[String]
2010-07-28 05:01:45 +02:00
}
final class FullReader(historyPath: Option[File], complete: Parser[_]) extends JLine
2010-07-28 05:01:45 +02:00
{
protected[this] val reader =
{
val cr = new ConsoleReader
cr.setBellEnabled(false)
JLine.initializeHistory(cr, historyPath)
sbt.complete.JLineCompletion.installCustomCompletor(cr, complete)
2010-07-28 05:01:45 +02:00
cr
}
}
class SimpleReader private[sbt] (historyPath: Option[File]) extends JLine
2010-07-28 05:01:45 +02:00
{
protected[this] val reader = JLine.createReader()
JLine.initializeHistory(reader, historyPath)
}
object SimpleReader extends JLine
{
protected[this] val reader = JLine.createReader()
2011-10-13 08:12:30 +02:00
}