sbt/util/complete/HistoryCommands.scala

84 lines
2.3 KiB
Scala
Raw Normal View History

/* sbt -- Simple Build Tool
* Copyright 2010 Mark Harrah
*/
package sbt
package complete
2010-05-05 04:22:30 +02:00
object HistoryCommands
{
val Start = "!"
// second characters
val Contains = "?"
val Last = "!"
val ListCommands = ":"
def ContainsFull = h(Contains)
def LastFull = h(Last)
def ListFull = h(ListCommands)
def ListN = ListFull + "n"
2010-05-16 20:42:41 +02:00
def ContainsString = ContainsFull + "string"
def StartsWithString = Start + "string"
2010-05-05 04:22:30 +02:00
def Previous = Start + "-n"
def Nth = Start + "n"
private def h(s: String) = Start + s
def plainCommands = Seq(ListFull, Start, LastFull, ContainsFull)
def descriptions = Seq(
LastFull -> "Execute the last command again",
ListFull -> "Show all previous commands",
ListN -> "Show the last n commands",
2010-05-16 20:42:41 +02:00
Nth -> ("Execute the command with index n, as shown by the " + ListFull + " command"),
2010-05-05 04:22:30 +02:00
Previous -> "Execute the nth command before this one",
2010-05-16 20:42:41 +02:00
StartsWithString -> "Execute the most recent command starting with 'string'",
ContainsString -> "Execute the most recent command containing 'string'"
2010-05-05 04:22:30 +02:00
)
def helpString = "History commands:\n " + (descriptions.map{ case (c,d) => c + " " + d}).mkString("\n ")
def printHelp(): Unit =
println(helpString)
2010-05-05 04:22:30 +02:00
def apply(s: String, historyPath: Option[Path], maxLines: Int, error: String => Unit): Option[List[String]] =
2010-05-05 04:22:30 +02:00
if(s.isEmpty)
{
printHelp()
2010-05-05 04:22:30 +02:00
Some(Nil)
}
else
{
val lines = historyPath.toList.flatMap(h => IO.readLines(h.asFile) ).toArray
2010-05-05 04:22:30 +02:00
if(lines.isEmpty)
{
error("No history")
2010-05-05 04:22:30 +02:00
None
}
else
{
val history = complete.History(lines, error)
2010-05-05 04:22:30 +02:00
if(s.startsWith(ListCommands))
{
val rest = s.substring(ListCommands.length)
val show = complete.History.number(rest).getOrElse(lines.length)
printHistory(history, maxLines, show)
Some(Nil)
}
else
{
val command = historyCommand(history, s)
2010-05-05 04:22:30 +02:00
command.foreach(lines(lines.length - 1) = _)
historyPath foreach { h => IO.writeLines(h.asFile, lines) }
2010-05-05 04:22:30 +02:00
Some(command.toList)
}
}
}
def printHistory(history: complete.History, historySize: Int, show: Int): Unit = history.list(historySize, show).foreach(println)
def historyCommand(history: complete.History, s: String): Option[String] =
2010-05-05 04:22:30 +02:00
{
if(s == Last)
history !!
else if(s.startsWith(Contains))
history !? s.substring(Contains.length)
else
history ! s
}
}