inject 'log' method to State as convenience for CommandSupport.logger

This commit is contained in:
Mark Harrah 2011-10-16 17:27:36 -04:00
parent ed4935f3fb
commit ddd70fcc77
12 changed files with 21 additions and 25 deletions

View File

@ -3,7 +3,6 @@
*/ */
package sbt package sbt
import CommandSupport.logger
import Project.ScopedKey import Project.ScopedKey
import Load.BuildStructure import Load.BuildStructure
import Keys.{aggregate, showSuccess, showTiming, timingFormat} import Keys.{aggregate, showSuccess, showTiming, timingFormat}
@ -83,7 +82,7 @@ final object Aggregation
val start = System.currentTimeMillis val start = System.currentTimeMillis
val (newS, result) = withStreams(structure){ str => runTask(toRun, s,str, structure.index.triggers, maxWorkers = workers)(nodeView(s, str, extra.tasks, extra.values)) } val (newS, result) = withStreams(structure){ str => runTask(toRun, s,str, structure.index.triggers, maxWorkers = workers)(nodeView(s, str, extra.tasks, extra.values)) }
val stop = System.currentTimeMillis val stop = System.currentTimeMillis
val log = logger(newS) val log = newS.log
val success = result match { case Value(_) => true; case Inc(_) => false } val success = result match { case Value(_) => true; case Inc(_) => false }
try { onResult(result, log) { results => if(show) printSettings(results, log) } } try { onResult(result, log) { results => if(show) printSettings(results, log) } }
@ -148,7 +147,7 @@ final object Aggregation
case xs @ KeyValue(_, _: InputStatic[t]) :: _ => applyTasks(s, structure, maps(xs.asInstanceOf[Values[InputStatic[t]]])(_.parser(s)), show) case xs @ KeyValue(_, _: InputStatic[t]) :: _ => applyTasks(s, structure, maps(xs.asInstanceOf[Values[InputStatic[t]]])(_.parser(s)), show)
case xs @ KeyValue(_, _: InputDynamic[t]) :: _ => applyDynamicTasks(s, structure, xs.asInstanceOf[Values[InputDynamic[t]]], show) case xs @ KeyValue(_, _: InputDynamic[t]) :: _ => applyDynamicTasks(s, structure, xs.asInstanceOf[Values[InputDynamic[t]]], show)
case xs @ KeyValue(_, _: Task[t]) :: _ => applyTasks(s, structure, maps(xs.asInstanceOf[Values[Task[t]]])(x => success(x)), show) case xs @ KeyValue(_, _: Task[t]) :: _ => applyTasks(s, structure, maps(xs.asInstanceOf[Values[Task[t]]])(x => success(x)), show)
case xs => success(() => { printSettings(xs, logger(s)); s} ) case xs => success(() => { printSettings(xs, s.log); s} )
} }
private[this] def maps[T, S](vs: Values[T])(f: T => S): Values[S] = private[this] def maps[T, S](vs: Values[T])(f: T => S): Values[S] =
vs map { case KeyValue(k,v) => KeyValue(k, f(v)) } vs map { case KeyValue(k,v) => KeyValue(k, f(v)) }

View File

@ -5,7 +5,6 @@ package sbt
import java.io.File import java.io.File
import complete.{DefaultParsers, EditDistance, Parser} import complete.{DefaultParsers, EditDistance, Parser}
import CommandSupport.logger
sealed trait Command { sealed trait Command {
def help: Seq[Help] def help: Seq[Help]
@ -92,7 +91,7 @@ object Command
case Left(failures) => case Left(failures) =>
val (msgs,pos) = failures() val (msgs,pos) = failures()
val errMsg = commandError(command, msgs, pos) val errMsg = commandError(command, msgs, pos)
logger(state).error(errMsg) state.log.error(errMsg)
state.fail state.fail
} }
} }

View File

@ -42,7 +42,7 @@ object GlobalPlugin
val p: Scope = Scope.GlobalScope in ProjectRef(root, rootProject(root)) val p: Scope = Scope.GlobalScope in ProjectRef(root, rootProject(root))
val taskInit = (projectID, projectDependencies, projectDescriptors, resolvers, fullClasspath in Runtime, internalDependencyClasspath in Runtime, exportedProducts in Runtime, ivyModule) map { val taskInit = (projectID, projectDependencies, projectDescriptors, resolvers, fullClasspath in Runtime, internalDependencyClasspath in Runtime, exportedProducts in Runtime, ivyModule) map {
(pid, pdeps, pdescs, rs, cp, intcp, prods, mod) => (pid, pdeps, pdescs, rs, cp, intcp, prods, mod) =>
val depMap = pdescs + mod.dependencyMapping(log(state)) val depMap = pdescs + mod.dependencyMapping(state.log)
GlobalPluginData(pid, pdeps, depMap, rs, cp, prods ++ intcp) GlobalPluginData(pid, pdeps, depMap, rs, cp, prods ++ intcp)
} }
val task = taskInit mapReferenced Project.mapScope(Scope replaceThis p) evaluate data val task = taskInit mapReferenced Project.mapScope(Scope replaceThis p) evaluate data
@ -54,10 +54,9 @@ object GlobalPlugin
withStreams(structure) { str => withStreams(structure) { str =>
val nv = nodeView(state, str) val nv = nodeView(state, str)
val (newS, result) = runTask(t, state, str, structure.index.triggers)(nv) val (newS, result) = runTask(t, state, str, structure.index.triggers)(nv)
(newS, processResult(result, log(newS))) (newS, processResult(result, newS.log))
} }
} }
private[this] def log(s: State) = CommandSupport.logger(s)
val globalPluginSettings = inScope(Scope.GlobalScope in LocalRootProject)(Seq( val globalPluginSettings = inScope(Scope.GlobalScope in LocalRootProject)(Seq(
organization := "org.scala-tools.sbt", organization := "org.scala-tools.sbt",
onLoadMessage <<= Keys.baseDirectory("Loading global plugins from " + _), onLoadMessage <<= Keys.baseDirectory("Loading global plugins from " + _),

View File

@ -13,11 +13,11 @@ object IvyConsole
final val Name = "ivy-console" final val Name = "ivy-console"
lazy val command = lazy val command =
Command.command(Name) { state => Command.command(Name) { state =>
val Dependencies(managed, repos, unmanaged) = parseDependencies(state.remainingCommands, CommandSupport.logger(state)) val Dependencies(managed, repos, unmanaged) = parseDependencies(state.remainingCommands, state.log)
val base = new File(CommandSupport.bootDirectory(state), Name) val base = new File(CommandSupport.bootDirectory(state), Name)
IO.createDirectory(base) IO.createDirectory(base)
val (eval, structure) = Load.defaultLoad(state, base, CommandSupport.logger(state)) val (eval, structure) = Load.defaultLoad(state, base, state.log)
val session = Load.initialSession(structure, eval) val session = Load.initialSession(structure, eval)
val extracted = Project.extract(session, structure) val extracted = Project.extract(session, structure)
import extracted._ import extracted._

View File

@ -310,7 +310,7 @@ object BuiltinCommands
def history = Command.custom(historyParser, historyHelp) def history = Command.custom(historyParser, historyHelp)
def historyParser(s: State): Parser[() => State] = def historyParser(s: State): Parser[() => State] =
Command.applyEffect(HistoryCommands.actionParser) { histFun => Command.applyEffect(HistoryCommands.actionParser) { histFun =>
val logError = (msg: String) => CommandSupport.logger(s).error(msg) val logError = (msg: String) => s.log.error(msg)
val hp = s get historyPath.key getOrElse None val hp = s get historyPath.key getOrElse None
val lines = hp.toList.flatMap( p => IO.readLines(p) ).toIndexedSeq val lines = hp.toList.flatMap( p => IO.readLines(p) ).toIndexedSeq
histFun( complete.History(lines, hp, logError) ) match histFun( complete.History(lines, hp, logError) ) match

View File

@ -9,7 +9,6 @@ package sbt
import Keys.{appConfiguration, stateBuildStructure, commands, configuration, historyPath, projectCommand, sessionSettings, sessionVars, shellPrompt, thisProject, thisProjectRef, watch} import Keys.{appConfiguration, stateBuildStructure, commands, configuration, historyPath, projectCommand, sessionSettings, sessionVars, shellPrompt, thisProject, thisProjectRef, watch}
import Scope.{GlobalScope,ThisScope} import Scope.{GlobalScope,ThisScope}
import Load.BuildStructure import Load.BuildStructure
import CommandSupport.logger
import Types.{idFun, Id} import Types.{idFun, Id}
sealed trait ProjectDefinition[PR <: ProjectReference] sealed trait ProjectDefinition[PR <: ProjectReference]
@ -79,7 +78,7 @@ final case class Extracted(structure: BuildStructure, session: SessionSettings,
val rkey = Project.mapScope(Scope.resolveScope(GlobalScope, currentRef.build, rootProject) )( key.scopedKey ) val rkey = Project.mapScope(Scope.resolveScope(GlobalScope, currentRef.build, rootProject) )( key.scopedKey )
val value: Option[(State, Result[T])] = apply(structure, key.task.scopedKey, state, currentRef) val value: Option[(State, Result[T])] = apply(structure, key.task.scopedKey, state, currentRef)
val (newS, result) = getOrError(rkey.scope, rkey.key, value) val (newS, result) = getOrError(rkey.scope, rkey.key, value)
(newS, processResult(result, logger(newS))) (newS, processResult(result, newS.log))
} }
private def getOrError[T](scope: Scope, key: AttributeKey[_], value: Option[T])(implicit display: Show[ScopedKey[_]]): T = private def getOrError[T](scope: Scope, key: AttributeKey[_], value: Option[T])(implicit display: Show[ScopedKey[_]]): T =
value getOrElse error(display(ScopedKey(scope, key)) + " is undefined.") value getOrElse error(display(ScopedKey(scope, key)) + " is undefined.")
@ -179,7 +178,7 @@ object Project extends Init[Scope] with ProjectExtra
val ref = Project.current(s) val ref = Project.current(s)
val project = Load.getProject(structure.units, ref.build, ref.project) val project = Load.getProject(structure.units, ref.build, ref.project)
val msg = Keys.onLoadMessage in ref get structure.data getOrElse "" val msg = Keys.onLoadMessage in ref get structure.data getOrElse ""
if(!msg.isEmpty) logger(s).info(msg) if(!msg.isEmpty) s.log.info(msg)
def get[T](k: SettingKey[T]): Option[T] = k in ref get structure.data def get[T](k: SettingKey[T]): Option[T] = k in ref get structure.data
def commandsIn(axis: ResolvedReference) = commands in axis get structure.data toList ; def commandsIn(axis: ResolvedReference) = commands in axis get structure.data toList ;

View File

@ -6,7 +6,6 @@ package sbt
import ProjectNavigation._ import ProjectNavigation._
import Project.updateCurrent import Project.updateCurrent
import Keys.sessionSettings import Keys.sessionSettings
import CommandSupport.logger
import complete.{DefaultParsers, Parser} import complete.{DefaultParsers, Parser}
import DefaultParsers._ import DefaultParsers._
import java.net.URI import java.net.URI
@ -39,7 +38,7 @@ final class ProjectNavigation(s: State)
if(to.length > 1) gotoParent(to.length - 1, nav, s) else s */ // semantics currently undefined if(to.length > 1) gotoParent(to.length - 1, nav, s) else s */ // semantics currently undefined
} }
def show(): Unit = logger(s).info(currentRef.project + " (in build " + currentRef.build + ")") def show(): Unit = s.log.info(currentRef.project + " (in build " + currentRef.build + ")")
def selectProject(uri: URI, to: String): State = def selectProject(uri: URI, to: String): State =
if( structure.units(uri).defined.contains(to) ) if( structure.units(uri).defined.contains(to) )
setProject(uri, to) setProject(uri, to)
@ -54,7 +53,7 @@ final class ProjectNavigation(s: State)
def fail(msg: String): State = def fail(msg: String): State =
{ {
logger(s).error(msg) s.log.error(msg)
s.fail s.fail
} }

View File

@ -19,7 +19,7 @@ object Script
val base = new File(CommandSupport.bootDirectory(state), hash) val base = new File(CommandSupport.bootDirectory(state), hash)
IO.createDirectory(base) IO.createDirectory(base)
val (eval, structure) = Load.defaultLoad(state, base, CommandSupport.logger(state)) val (eval, structure) = Load.defaultLoad(state, base, state.log)
val session = Load.initialSession(structure, eval) val session = Load.initialSession(structure, eval)
val extracted = Project.extract(session, structure) val extracted = Project.extract(session, structure)
import extracted._ import extracted._

View File

@ -7,7 +7,6 @@ package sbt
import java.net.URI import java.net.URI
import Project._ import Project._
import Types.Endo import Types.Endo
import CommandSupport.logger
import compiler.Eval import compiler.Eval
import SessionSettings._ import SessionSettings._
@ -47,7 +46,7 @@ object SessionSettings
import extracted._ import extracted._
if(session.append.isEmpty) if(session.append.isEmpty)
{ {
logger(s).info("No session settings defined.") s.log.info("No session settings defined.")
s s
} }
else else
@ -59,7 +58,7 @@ object SessionSettings
{ {
val oldSettings = (oldState get Keys.sessionSettings).toList.flatMap(_.append).flatMap(_._2) val oldSettings = (oldState get Keys.sessionSettings).toList.flatMap(_.append).flatMap(_._2)
if(newSession.append.isEmpty && !oldSettings.isEmpty) if(newSession.append.isEmpty && !oldSettings.isEmpty)
logger(oldState).warn("Discarding " + pluralize(oldSettings.size, " session setting") + ". Use 'session save' to persist session settings.") oldState.log.warn("Discarding " + pluralize(oldSettings.size, " session setting") + ". Use 'session save' to persist session settings.")
} }
def removeRanges[T](in: Seq[T], ranges: Seq[(Int,Int)]): Seq[T] = def removeRanges[T](in: Seq[T], ranges: Seq[(Int,Int)]): Seq[T] =
{ {

View File

@ -5,7 +5,7 @@ package sbt
import java.io.File import java.io.File
import java.util.concurrent.Callable import java.util.concurrent.Callable
import CommandSupport.FailureWall import CommandSupport.{FailureWall, logger}
final case class State( final case class State(
configuration: xsbti.AppConfiguration, configuration: xsbti.AppConfiguration,
@ -43,6 +43,7 @@ trait StateOps {
def update[T](key: AttributeKey[T])(f: Option[T] => T): State def update[T](key: AttributeKey[T])(f: Option[T] => T): State
def has(key: AttributeKey[_]): Boolean def has(key: AttributeKey[_]): Boolean
def baseDir: File def baseDir: File
def log: Logger
def locked[T](file: File)(t: => T): T def locked[T](file: File)(t: => T): T
def runExitHooks(): State def runExitHooks(): State
def addExitHook(f: => Unit): State def addExitHook(f: => Unit): State
@ -77,6 +78,7 @@ object State
def update[T](key: AttributeKey[T])(f: Option[T] => T): State = put(key, f(get(key))) def update[T](key: AttributeKey[T])(f: Option[T] => T): State = put(key, f(get(key)))
def has(key: AttributeKey[_]) = s.attributes contains key def has(key: AttributeKey[_]) = s.attributes contains key
def remove(key: AttributeKey[_]) = s.copy(attributes = s.attributes remove key) def remove(key: AttributeKey[_]) = s.copy(attributes = s.attributes remove key)
def log = CommandSupport.logger(s)
def fail = def fail =
{ {
val remaining = s.remainingCommands.dropWhile(_ != FailureWall) val remaining = s.remainingCommands.dropWhile(_ != FailureWall)

View File

@ -143,7 +143,7 @@ object Scoped
} }
final class RichInitialize[S](init: Initialize[S]) final class RichInitialize[S](init: Initialize[S])
{ {
@deprecated("A call to 'identity' is no longer necessary and can be removed.") @deprecated("A call to 'identity' is no longer necessary and can be removed.", "0.11.0")
final def identity: Initialize[S] = init final def identity: Initialize[S] = init
def map[T](f: S => T): Initialize[Task[T]] = init(s => mktask(f(s)) ) def map[T](f: S => T): Initialize[Task[T]] = init(s => mktask(f(s)) )
def flatMap[T](f: S => Task[T]): Initialize[Task[T]] = init(f) def flatMap[T](f: S => Task[T]): Initialize[Task[T]] = init(f)
@ -162,7 +162,7 @@ object Scoped
def task: SettingKey[Task[S]] = scopedSetting(scope, key) def task: SettingKey[Task[S]] = scopedSetting(scope, key)
def get(settings: Settings[Scope]): Option[Task[S]] = settings.get(scope, key) def get(settings: Settings[Scope]): Option[Task[S]] = settings.get(scope, key)
@deprecated("A call to 'identity' is no longer necessary and can be removed.") @deprecated("A call to 'identity' is no longer necessary and can be removed.", "0.11.0")
def identity: Initialize[Task[S]] = this def identity: Initialize[Task[S]] = this
def ? : Initialize[Task[Option[S]]] = Project.optional(scopedKey) { case None => mktask { None }; case Some(t) => t map some.fn } def ? : Initialize[Task[Option[S]]] = Project.optional(scopedKey) { case None => mktask { None }; case Some(t) => t map some.fn }

View File

@ -61,7 +61,7 @@ object Watched
(triggered, newWatchState, s) (triggered, newWatchState, s)
} }
catch { case e: Exception => catch { case e: Exception =>
val log = CommandSupport.logger(s) val log = s.log
log.error("Error occurred obtaining files to watch. Terminating continuous execution...") log.error("Error occurred obtaining files to watch. Terminating continuous execution...")
BuiltinCommands.handleException(e, s, log) BuiltinCommands.handleException(e, s, log)
(false, watchState, s.fail) (false, watchState, s.fail)