summaryrefslogtreecommitdiff
path: root/main/api/src/mill/api/Ctx.scala
blob: 4ccf5a7d143e6edacb9a19d1ea4b24b5e87a98fb (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package mill.api

import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.implicitConversions

import os.Path

/**
 * Provides access to various resources in the context of a currently execution Target.
 */
object Ctx {
  @compileTimeOnly("Target.ctx() / T.ctx() can only be used with a T{...} block")
  @ImplicitStub
  implicit def taskCtx: Ctx = ???

  /** Access to the targets destination path. */
  trait Dest {
    def dest: os.Path
  }
  object Dest {
    implicit def pathToCtx(path: os.Path): Dest = new Dest { def dest = path }
  }

  /** Access to the targets [[Logger]] instance. */
  trait Log {
    def log: Logger
  }
  object Log {
    implicit def logToCtx(l: Logger): Log = new Log { def log = l }
  }

  /** Access to the projects home path. */
  trait Home {
    def home: os.Path
  }

  /** Access to the current system environment settings. */
  trait Env {
    def env: Map[String, String]
  }

  trait Args {
    def args: IndexedSeq[_]
  }

  def defaultHome = os.home / ".mill" / "ammonite"

  /**
    * Marker annotation.
    */
  class ImplicitStub extends StaticAnnotation
}


class Ctx(
  val args: IndexedSeq[_],
  dest0: () => os.Path,
  val log: Logger,
  val home: os.Path,
  val env: Map[String, String]
)
  extends Ctx.Dest
  with Ctx.Log
  with Ctx.Args
  with Ctx.Home
  with Ctx.Env {

  def dest: Path = dest0()
  def length: Int = 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}")
  }
}