summaryrefslogtreecommitdiff
path: root/core/src/main/scala/mill/util/Ctx.scala
blob: 60e6bdbfc727ece13ee5a552b7dec1d9a978f0ea (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package mill.util

import ammonite.ops.Path
import mill.define.Applicative.ImplicitStub
import mill.util.Ctx.{ArgCtx, BaseCtx, DestCtx, LoaderCtx, LogCtx}

import scala.annotation.compileTimeOnly
import scala.language.implicitConversions

object Ctx{
  @compileTimeOnly("Target.ctx() can only be used with a T{...} block")
  @ImplicitStub
  implicit def taskCtx: Ctx = ???

  object DestCtx {
    implicit def pathToCtx(path: Path): DestCtx = new DestCtx { def dest = path }
  }
  trait DestCtx{
    def dest: Path
  }
  trait BaseCtx{
    def base: Path
  }
  object BaseCtx {
    implicit def pathToCtx(path: Path): BaseCtx = new BaseCtx { def base = path }
  }
  trait LogCtx{
    def log: Logger
  }
  object LogCtx{
    implicit def logToCtx(l: Logger): LogCtx = new LogCtx { def log = l }
  }
  trait ArgCtx{
    def args: IndexedSeq[_]
  }
  trait LoaderCtx{
    def load[T](x: Loader[T]): T
  }
  trait Loader[T]{
    def make(): T
  }
}
class Ctx(val args: IndexedSeq[_],
          val dest: Path,
          val base: Path,
          val log: Logger,
          workerCtx0: Ctx.LoaderCtx)
  extends DestCtx
  with LogCtx
  with ArgCtx
  with LoaderCtx
  with BaseCtx{

  def load[T](x: Ctx.Loader[T]): T = workerCtx0.load(x)
  def length = args.length
  def apply[T](index: Int): T = {
    if (index >= 0 && index < args.length) args(index).asInstanceOf[T]
    else throw new IndexOutOfBoundsException(s"Index $index outside of range 0 - ${args.length}")
  }
}