src/Pure/System/build.scala
author wenzelm
Tue Jul 24 12:14:16 2012 +0200 (2012-07-24)
changeset 48467 a4318c36a829
parent 48462 424fd5364f15
child 48469 826a771cff33
permissions -rw-r--r--
more precise propagation of options: build, session, theories;
wenzelm@48276
     1
/*  Title:      Pure/System/build.scala
wenzelm@48276
     2
    Author:     Makarius
wenzelm@48276
     3
wenzelm@48276
     4
Build and manage Isabelle sessions.
wenzelm@48276
     5
*/
wenzelm@48276
     6
wenzelm@48276
     7
package isabelle
wenzelm@48276
     8
wenzelm@48276
     9
wenzelm@48409
    10
import java.io.{File => JFile}
wenzelm@48335
    11
wenzelm@48337
    12
import scala.collection.mutable
wenzelm@48340
    13
import scala.annotation.tailrec
wenzelm@48337
    14
wenzelm@48335
    15
wenzelm@48276
    16
object Build
wenzelm@48276
    17
{
wenzelm@48337
    18
  /** session information **/
wenzelm@48334
    19
wenzelm@48349
    20
  object Session
wenzelm@48349
    21
  {
wenzelm@48421
    22
    /* Key */
wenzelm@48421
    23
wenzelm@48349
    24
    object Key
wenzelm@48349
    25
    {
wenzelm@48349
    26
      object Ordering extends scala.math.Ordering[Key]
wenzelm@48349
    27
      {
wenzelm@48349
    28
        def compare(key1: Key, key2: Key): Int =
wenzelm@48350
    29
          key1.order compare key2.order match {
wenzelm@48349
    30
            case 0 => key1.name compare key2.name
wenzelm@48349
    31
            case ord => ord
wenzelm@48349
    32
          }
wenzelm@48349
    33
      }
wenzelm@48349
    34
    }
wenzelm@48349
    35
wenzelm@48349
    36
    sealed case class Key(name: String, order: Int)
wenzelm@48349
    37
    {
wenzelm@48349
    38
      override def toString: String = name
wenzelm@48349
    39
    }
wenzelm@48349
    40
wenzelm@48421
    41
wenzelm@48421
    42
    /* Info */
wenzelm@48421
    43
wenzelm@48349
    44
    sealed case class Info(
wenzelm@48457
    45
      base_name: String,
wenzelm@48349
    46
      dir: Path,
wenzelm@48418
    47
      parent: Option[String],
wenzelm@48349
    48
      description: String,
wenzelm@48349
    49
      options: Options,
wenzelm@48421
    50
      theories: List[(Options, List[Path])],
wenzelm@48421
    51
      files: List[Path],
wenzelm@48424
    52
      digest: SHA1.Digest)
wenzelm@48421
    53
wenzelm@48421
    54
wenzelm@48421
    55
    /* Queue */
wenzelm@48349
    56
wenzelm@48349
    57
    object Queue
wenzelm@48349
    58
    {
wenzelm@48349
    59
      val empty: Queue = new Queue()
wenzelm@48349
    60
    }
wenzelm@48349
    61
wenzelm@48349
    62
    final class Queue private(
wenzelm@48349
    63
      keys: Map[String, Key] = Map.empty,
wenzelm@48349
    64
      graph: Graph[Key, Info] = Graph.empty(Key.Ordering))
wenzelm@48349
    65
    {
wenzelm@48425
    66
      def is_empty: Boolean = graph.is_empty
wenzelm@48425
    67
wenzelm@48425
    68
      def apply(name: String): Info = graph.get_node(keys(name))
wenzelm@48351
    69
      def defined(name: String): Boolean = keys.isDefinedAt(name)
wenzelm@48419
    70
      def is_inner(name: String): Boolean = !graph.is_maximal(keys(name))
wenzelm@48419
    71
wenzelm@48418
    72
      def + (key: Key, info: Info): Queue =
wenzelm@48349
    73
      {
wenzelm@48349
    74
        val keys1 =
wenzelm@48351
    75
          if (defined(key.name)) error("Duplicate session: " + quote(key.name))
wenzelm@48351
    76
          else keys + (key.name -> key)
wenzelm@48349
    77
wenzelm@48349
    78
        val graph1 =
wenzelm@48349
    79
          try {
wenzelm@48418
    80
            graph.new_node(key, info).add_deps_acyclic(key, info.parent.toList.map(keys(_)))
wenzelm@48349
    81
          }
wenzelm@48349
    82
          catch {
wenzelm@48349
    83
            case exn: Graph.Cycles[_] =>
wenzelm@48349
    84
              error(cat_lines(exn.cycles.map(cycle =>
wenzelm@48349
    85
                "Cyclic session dependency of " +
wenzelm@48349
    86
                  cycle.map(key => quote(key.toString)).mkString(" via "))))
wenzelm@48349
    87
          }
wenzelm@48349
    88
        new Queue(keys1, graph1)
wenzelm@48349
    89
      }
wenzelm@48349
    90
wenzelm@48425
    91
      def - (name: String): Queue = new Queue(keys - name, graph.del_node(keys(name)))
wenzelm@48425
    92
wenzelm@48363
    93
      def required(names: List[String]): Queue =
wenzelm@48363
    94
      {
wenzelm@48363
    95
        val req = graph.all_preds(names.map(keys(_))).map(_.name).toSet
wenzelm@48363
    96
        val keys1 = keys -- keys.keySet.filter(name => !req(name))
wenzelm@48363
    97
        val graph1 = graph.restrict(key => keys1.isDefinedAt(key.name))
wenzelm@48363
    98
        new Queue(keys1, graph1)
wenzelm@48363
    99
      }
wenzelm@48363
   100
wenzelm@48425
   101
      def dequeue(skip: String => Boolean): Option[(String, Info)] =
wenzelm@48425
   102
      {
wenzelm@48425
   103
        val it = graph.entries.dropWhile(
wenzelm@48425
   104
          { case (key, (_, (deps, _))) => !deps.isEmpty || skip(key.name) })
wenzelm@48425
   105
        if (it.hasNext) { val (key, (info, _)) = it.next; Some((key.name, info)) }
wenzelm@48425
   106
        else None
wenzelm@48425
   107
      }
wenzelm@48425
   108
wenzelm@48422
   109
      def topological_order: List[(String, Info)] =
wenzelm@48422
   110
        graph.topological_order.map(key => (key.name, graph.get_node(key)))
wenzelm@48349
   111
    }
wenzelm@48349
   112
  }
wenzelm@48334
   113
wenzelm@48337
   114
wenzelm@48337
   115
  /* parsing */
wenzelm@48337
   116
wenzelm@48337
   117
  private case class Session_Entry(
wenzelm@48337
   118
    name: String,
wenzelm@48462
   119
    this_name: Boolean,
wenzelm@48349
   120
    order: Int,
wenzelm@48337
   121
    path: Option[String],
wenzelm@48347
   122
    parent: Option[String],
wenzelm@48337
   123
    description: String,
wenzelm@48421
   124
    options: List[Options.Spec],
wenzelm@48421
   125
    theories: List[(List[Options.Spec], List[String])],
wenzelm@48337
   126
    files: List[String])
wenzelm@48337
   127
wenzelm@48334
   128
  private object Parser extends Parse.Parser
wenzelm@48334
   129
  {
wenzelm@48334
   130
    val SESSION = "session"
wenzelm@48334
   131
    val IN = "in"
wenzelm@48334
   132
    val DESCRIPTION = "description"
wenzelm@48334
   133
    val OPTIONS = "options"
wenzelm@48334
   134
    val THEORIES = "theories"
wenzelm@48334
   135
    val FILES = "files"
wenzelm@48334
   136
wenzelm@48334
   137
    val syntax =
wenzelm@48336
   138
      Outer_Syntax.empty + "!" + "(" + ")" + "+" + "," + "=" + "[" + "]" +
wenzelm@48336
   139
        SESSION + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
wenzelm@48334
   140
wenzelm@48337
   141
    val session_entry: Parser[Session_Entry] =
wenzelm@48334
   142
    {
wenzelm@48334
   143
      val session_name = atom("session name", _.is_name)
wenzelm@48334
   144
      val theory_name = atom("theory name", _.is_name)
wenzelm@48280
   145
wenzelm@48334
   146
      val option =
wenzelm@48334
   147
        name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@48337
   148
      val options = keyword("[") ~> repsep(option, keyword(",")) <~ keyword("]")
wenzelm@48334
   149
wenzelm@48334
   150
      val theories =
wenzelm@48334
   151
        keyword(THEORIES) ~! ((options | success(Nil)) ~ rep1(theory_name)) ^^
wenzelm@48334
   152
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@48334
   153
wenzelm@48334
   154
      ((keyword(SESSION) ~! session_name) ^^ { case _ ~ x => x }) ~
wenzelm@48336
   155
        (keyword("!") ^^^ true | success(false)) ~
wenzelm@48349
   156
        (keyword("(") ~! (nat <~ keyword(")")) ^^ { case _ ~ x => x } | success(Integer.MAX_VALUE)) ~
wenzelm@48337
   157
        (opt(keyword(IN) ~! string ^^ { case _ ~ x => x })) ~
wenzelm@48347
   158
        (keyword("=") ~> opt(session_name <~ keyword("+"))) ~
wenzelm@48334
   159
        (keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x } | success("")) ~
wenzelm@48334
   160
        (keyword(OPTIONS) ~! options ^^ { case _ ~ x => x } | success(Nil)) ~
wenzelm@48347
   161
        rep(theories) ~
wenzelm@48336
   162
        (keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x } | success(Nil)) ^^
wenzelm@48349
   163
          { case a ~ b ~ c ~ d ~ e ~ f ~ g ~ h ~ i => Session_Entry(a, b, c, d, e, f, g, h, i) }
wenzelm@48334
   164
    }
wenzelm@48334
   165
wenzelm@48409
   166
    def parse_entries(root: JFile): List[Session_Entry] =
wenzelm@48334
   167
    {
wenzelm@48411
   168
      val toks = syntax.scan(File.read(root))
wenzelm@48337
   169
      parse_all(rep(session_entry), Token.reader(toks, root.toString)) match {
wenzelm@48334
   170
        case Success(result, _) => result
wenzelm@48334
   171
        case bad => error(bad.toString)
wenzelm@48334
   172
      }
wenzelm@48334
   173
    }
wenzelm@48334
   174
  }
wenzelm@48280
   175
wenzelm@48337
   176
wenzelm@48341
   177
  /* find sessions */
wenzelm@48337
   178
wenzelm@48361
   179
  private val ROOT = Path.explode("ROOT")
wenzelm@48361
   180
  private val SESSIONS = Path.explode("etc/sessions")
wenzelm@48361
   181
wenzelm@48364
   182
  private def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
wenzelm@48364
   183
wenzelm@48421
   184
  private def sessions_root(options: Options, dir: Path, root: JFile, queue: Session.Queue)
wenzelm@48421
   185
    : Session.Queue =
wenzelm@48280
   186
  {
wenzelm@48361
   187
    (queue /: Parser.parse_entries(root))((queue1, entry) =>
wenzelm@48337
   188
      try {
wenzelm@48347
   189
        if (entry.name == "") error("Bad session name")
wenzelm@48347
   190
wenzelm@48337
   191
        val full_name =
wenzelm@48364
   192
          if (is_pure(entry.name)) {
wenzelm@48347
   193
            if (entry.parent.isDefined) error("Illegal parent session")
wenzelm@48347
   194
            else entry.name
wenzelm@48347
   195
          }
wenzelm@48347
   196
          else
wenzelm@48347
   197
            entry.parent match {
wenzelm@48361
   198
              case Some(parent_name) if queue1.defined(parent_name) =>
wenzelm@48462
   199
                if (entry.this_name) entry.name
wenzelm@48351
   200
                else parent_name + "-" + entry.name
wenzelm@48351
   201
              case _ => error("Bad parent session")
wenzelm@48347
   202
            }
wenzelm@48339
   203
wenzelm@48337
   204
        val path =
wenzelm@48337
   205
          entry.path match {
wenzelm@48337
   206
            case Some(p) => Path.explode(p)
wenzelm@48337
   207
            case None => Path.basic(entry.name)
wenzelm@48337
   208
          }
wenzelm@48339
   209
wenzelm@48351
   210
        val key = Session.Key(full_name, entry.order)
wenzelm@48421
   211
wenzelm@48467
   212
        val session_options = options ++ entry.options
wenzelm@48467
   213
wenzelm@48421
   214
        val theories =
wenzelm@48467
   215
          entry.theories.map({ case (opts, thys) =>
wenzelm@48467
   216
            (session_options ++ opts, thys.map(Path.explode(_))) })
wenzelm@48421
   217
        val files = entry.files.map(Path.explode(_))
wenzelm@48423
   218
        val digest = SHA1.digest((full_name, entry.parent, entry.options, entry.theories).toString)
wenzelm@48423
   219
wenzelm@48418
   220
        val info =
wenzelm@48457
   221
          Session.Info(entry.name, dir + path, entry.parent,
wenzelm@48467
   222
            entry.description, session_options, theories, files, digest)
wenzelm@48351
   223
wenzelm@48418
   224
        queue1 + (key, info)
wenzelm@48337
   225
      }
wenzelm@48337
   226
      catch {
wenzelm@48337
   227
        case ERROR(msg) =>
wenzelm@48337
   228
          error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@48370
   229
            quote(entry.name) + Position.str_of(Position.file(root)))
wenzelm@48352
   230
      })
wenzelm@48352
   231
  }
wenzelm@48352
   232
wenzelm@48421
   233
  private def sessions_dir(options: Options, strict: Boolean, dir: Path, queue: Session.Queue)
wenzelm@48421
   234
    : Session.Queue =
wenzelm@48352
   235
  {
wenzelm@48373
   236
    val root = (dir + ROOT).file
wenzelm@48421
   237
    if (root.isFile) sessions_root(options, dir, root, queue)
wenzelm@48352
   238
    else if (strict) error("Bad session root file: " + quote(root.toString))
wenzelm@48361
   239
    else queue
wenzelm@48352
   240
  }
wenzelm@48352
   241
wenzelm@48421
   242
  private def sessions_catalog(options: Options, dir: Path, catalog: JFile, queue: Session.Queue)
wenzelm@48421
   243
    : Session.Queue =
wenzelm@48352
   244
  {
wenzelm@48354
   245
    val dirs =
wenzelm@48411
   246
      split_lines(File.read(catalog)).filterNot(line => line == "" || line.startsWith("#"))
wenzelm@48361
   247
    (queue /: dirs)((queue1, dir1) =>
wenzelm@48352
   248
      try {
wenzelm@48352
   249
        val dir2 = dir + Path.explode(dir1)
wenzelm@48421
   250
        if (dir2.file.isDirectory) sessions_dir(options, true, dir2, queue1)
wenzelm@48352
   251
        else error("Bad session directory: " + dir2.toString)
wenzelm@48337
   252
      }
wenzelm@48352
   253
      catch {
wenzelm@48352
   254
        case ERROR(msg) =>
wenzelm@48352
   255
          error(msg + "\nThe error(s) above occurred in session catalog " + quote(catalog.toString))
wenzelm@48352
   256
      })
wenzelm@48352
   257
  }
wenzelm@48352
   258
wenzelm@48421
   259
  def find_sessions(options: Options, all_sessions: Boolean, sessions: List[String],
wenzelm@48419
   260
    more_dirs: List[Path]): Session.Queue =
wenzelm@48352
   261
  {
wenzelm@48361
   262
    var queue = Session.Queue.empty
wenzelm@48352
   263
wenzelm@48352
   264
    for (dir <- Isabelle_System.components()) {
wenzelm@48421
   265
      queue = sessions_dir(options, false, dir, queue)
wenzelm@48352
   266
wenzelm@48373
   267
      val catalog = (dir + SESSIONS).file
wenzelm@48352
   268
      if (catalog.isFile)
wenzelm@48421
   269
        queue = sessions_catalog(options, dir, catalog, queue)
wenzelm@48337
   270
    }
wenzelm@48352
   271
wenzelm@48421
   272
    for (dir <- more_dirs) queue = sessions_dir(options, true, dir, queue)
wenzelm@48352
   273
wenzelm@48419
   274
    sessions.filter(name => !queue.defined(name)) match {
wenzelm@48419
   275
      case Nil =>
wenzelm@48419
   276
      case bad => error("Undefined session(s): " + commas_quote(bad))
wenzelm@48419
   277
    }
wenzelm@48419
   278
wenzelm@48419
   279
    if (all_sessions) queue else queue.required(sessions)
wenzelm@48280
   280
  }
wenzelm@48341
   281
wenzelm@48341
   282
wenzelm@48424
   283
wenzelm@48424
   284
  /** build **/
wenzelm@48424
   285
wenzelm@48422
   286
  /* dependencies */
wenzelm@48422
   287
wenzelm@48422
   288
  sealed case class Node(
wenzelm@48422
   289
    loaded_theories: Set[String],
wenzelm@48423
   290
    sources: List[(Path, SHA1.Digest)])
wenzelm@48422
   291
wenzelm@48423
   292
  sealed case class Deps(deps: Map[String, Node])
wenzelm@48423
   293
  {
wenzelm@48423
   294
    def sources(name: String): List[(Path, SHA1.Digest)] = deps(name).sources
wenzelm@48423
   295
  }
wenzelm@48423
   296
wenzelm@48423
   297
  def dependencies(queue: Session.Queue): Deps =
wenzelm@48423
   298
    Deps((Map.empty[String, Node] /: queue.topological_order)(
wenzelm@48422
   299
      { case (deps, (name, info)) =>
wenzelm@48422
   300
          val preloaded =
wenzelm@48422
   301
            info.parent match {
wenzelm@48422
   302
              case None => Set.empty[String]
wenzelm@48422
   303
              case Some(parent) => deps(parent).loaded_theories
wenzelm@48422
   304
            }
wenzelm@48422
   305
          val thy_info = new Thy_Info(new Thy_Load(preloaded))
wenzelm@48422
   306
wenzelm@48422
   307
          val thy_deps =
wenzelm@48422
   308
            thy_info.dependencies(
wenzelm@48422
   309
              info.theories.map(_._2).flatten.
wenzelm@48422
   310
                map(thy => Document.Node.Name(info.dir + Thy_Load.thy_path(thy))))
wenzelm@48422
   311
wenzelm@48422
   312
          val loaded_theories = preloaded ++ thy_deps.map(_._1.theory)
wenzelm@48423
   313
wenzelm@48423
   314
          val all_files =
wenzelm@48422
   315
            thy_deps.map({ case (n, h) =>
wenzelm@48422
   316
              val thy = Path.explode(n.node).expand
wenzelm@48422
   317
              val uses =
wenzelm@48422
   318
                h match {
wenzelm@48422
   319
                  case Exn.Res(d) =>
wenzelm@48422
   320
                    d.uses.map(p => (Path.explode(n.dir) + Path.explode(p._1)).expand)
wenzelm@48422
   321
                  case _ => Nil
wenzelm@48422
   322
                }
wenzelm@48422
   323
              thy :: uses
wenzelm@48422
   324
            }).flatten ::: info.files.map(file => info.dir + file)
wenzelm@48423
   325
          val sources = all_files.par.map(p => (p, SHA1.digest(p))).toList
wenzelm@48422
   326
wenzelm@48422
   327
          deps + (name -> Node(loaded_theories, sources))
wenzelm@48423
   328
      }))
wenzelm@48422
   329
wenzelm@48422
   330
wenzelm@48424
   331
  /* jobs */
wenzelm@48341
   332
wenzelm@48424
   333
  private class Job(cwd: JFile, env: Map[String, String], script: String, args: String)
wenzelm@48364
   334
  {
wenzelm@48418
   335
    private val args_file = File.tmp_file("args")
wenzelm@48418
   336
    private val env1 = env + ("ARGS_FILE" -> Isabelle_System.posix_path(args_file.getPath))
wenzelm@48418
   337
    File.write(args_file, args)
wenzelm@48418
   338
wenzelm@48424
   339
    private val (thread, result) =
wenzelm@48424
   340
      Simple_Thread.future("build") { Isabelle_System.bash_env(cwd, env1, script) }
wenzelm@48418
   341
wenzelm@48418
   342
    def terminate: Unit = thread.interrupt
wenzelm@48418
   343
    def is_finished: Boolean = result.is_finished
wenzelm@48425
   344
    def join: (String, String, Int) = { val res = result.join; args_file.delete; res }
wenzelm@48418
   345
  }
wenzelm@48418
   346
wenzelm@48457
   347
  private def start_job(name: String, info: Session.Info, output: Option[String],
wenzelm@48459
   348
    options: Options, timing: Boolean, verbose: Boolean, browser_info: Path): Job =
wenzelm@48418
   349
  {
wenzelm@48467
   350
    // global browser info dir
wenzelm@48467
   351
    if (options.bool("browser_info") && !(browser_info + Path.explode("index.html")).file.isFile)
wenzelm@48467
   352
    {
wenzelm@48467
   353
      browser_info.file.mkdirs()
wenzelm@48467
   354
      File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
wenzelm@48467
   355
        browser_info + Path.explode("isabelle.gif"))
wenzelm@48467
   356
      File.write(browser_info + Path.explode("index.html"),
wenzelm@48467
   357
        File.read(Path.explode("~~/lib/html/library_index_header.template")) +
wenzelm@48467
   358
        File.read(Path.explode("~~/lib/html/library_index_content.template")) +
wenzelm@48467
   359
        File.read(Path.explode("~~/lib/html/library_index_footer.template")))
wenzelm@48467
   360
    }
wenzelm@48467
   361
wenzelm@48418
   362
    val parent = info.parent.getOrElse("")
wenzelm@48418
   363
wenzelm@48373
   364
    val cwd = info.dir.file
wenzelm@48447
   365
    val env = Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> output.getOrElse(""))
wenzelm@48364
   366
    val script =
wenzelm@48447
   367
      if (is_pure(name)) "./build " + name + " \"$OUTPUT\""
wenzelm@48418
   368
      else {
wenzelm@48418
   369
        """
wenzelm@48418
   370
        . "$ISABELLE_HOME/lib/scripts/timestart.bash"
wenzelm@48418
   371
        """ +
wenzelm@48447
   372
          (if (output.isDefined)
wenzelm@48447
   373
            """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT" """
wenzelm@48418
   374
          else
wenzelm@48418
   375
            """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT" """) +
wenzelm@48418
   376
        """
wenzelm@48418
   377
        RC="$?"
wenzelm@48418
   378
wenzelm@48418
   379
        . "$ISABELLE_HOME/lib/scripts/timestop.bash"
wenzelm@48418
   380
wenzelm@48418
   381
        if [ "$RC" -eq 0 ]; then
wenzelm@48418
   382
          echo "Finished $TARGET ($TIMES_REPORT)" >&2
wenzelm@48418
   383
        fi
wenzelm@48418
   384
wenzelm@48418
   385
        exit "$RC"
wenzelm@48418
   386
        """
wenzelm@48418
   387
      }
wenzelm@48418
   388
    val args_xml =
wenzelm@48418
   389
    {
wenzelm@48418
   390
      import XML.Encode._
wenzelm@48459
   391
          pair(bool, pair(Options.encode, pair(bool, pair(bool, pair(Path.encode, pair(string,
wenzelm@48459
   392
            pair(string, pair(string, list(pair(Options.encode, list(Path.encode)))))))))))(
wenzelm@48459
   393
          (output.isDefined, (options, (timing, (verbose, (browser_info, (parent,
wenzelm@48459
   394
            (name, (info.base_name, info.theories)))))))))
wenzelm@48418
   395
    }
wenzelm@48424
   396
    new Job(cwd, env, script, YXML.string_of_body(args_xml))
wenzelm@48364
   397
  }
wenzelm@48364
   398
wenzelm@48424
   399
wenzelm@48425
   400
  /* build */
wenzelm@48424
   401
wenzelm@48424
   402
  private def echo(msg: String) { java.lang.System.out.println(msg) }
wenzelm@48425
   403
  private def sleep(): Unit = Thread.sleep(500)
wenzelm@48424
   404
wenzelm@48425
   405
  def build(all_sessions: Boolean, build_images: Boolean, max_jobs: Int,
wenzelm@48459
   406
    list_only: Boolean, system_mode: Boolean, timing: Boolean, verbose: Boolean,
wenzelm@48419
   407
    more_dirs: List[Path], more_options: List[String], sessions: List[String]): Int =
wenzelm@48341
   408
  {
wenzelm@48419
   409
    val options = (Options.init() /: more_options)(_.define_simple(_))
wenzelm@48421
   410
    val queue = find_sessions(options, all_sessions, sessions, more_dirs)
wenzelm@48423
   411
    val deps = dependencies(queue)
wenzelm@48368
   412
wenzelm@48447
   413
    val (output_dir, browser_info) =
wenzelm@48447
   414
      if (system_mode) (Path.explode("~~/heaps/$ML_IDENTIFIER"), Path.explode("~~/browser_info"))
wenzelm@48447
   415
      else (Path.explode("$ISABELLE_OUTPUT"), Path.explode("$ISABELLE_BROWSER_INFO"))
wenzelm@48363
   416
wenzelm@48373
   417
    // prepare log dir
wenzelm@48447
   418
    val log_dir = output_dir + Path.explode("log")
wenzelm@48373
   419
    log_dir.file.mkdirs()
wenzelm@48373
   420
wenzelm@48425
   421
    // scheduler loop
wenzelm@48425
   422
    @tailrec def loop(
wenzelm@48425
   423
      pending: Session.Queue,
wenzelm@48425
   424
      running: Map[String, Job],
wenzelm@48425
   425
      results: Map[String, Int]): Map[String, Int] =
wenzelm@48425
   426
    {
wenzelm@48425
   427
      if (pending.is_empty) results
wenzelm@48425
   428
      else if (running.exists({ case (_, job) => job.is_finished })) {
wenzelm@48425
   429
        val (name, job) = running.find({ case (_, job) => job.is_finished }).get
wenzelm@48424
   430
wenzelm@48425
   431
        val (out, err, rc) = job.join
wenzelm@48425
   432
        echo(Library.trim_line(err))
wenzelm@48373
   433
wenzelm@48425
   434
        val log = log_dir + Path.basic(name)
wenzelm@48425
   435
        if (rc == 0) {
wenzelm@48425
   436
          val sources =
wenzelm@48425
   437
            (queue(name).digest :: deps.sources(name).map(_._2)).map(_.toString).sorted
wenzelm@48425
   438
              .mkString("sources: ", " ", "\n")
wenzelm@48425
   439
          File.write_zip(log.ext("gz"), sources + out)
wenzelm@48425
   440
        }
wenzelm@48425
   441
        else {
wenzelm@48425
   442
          File.write(log, out)
wenzelm@48425
   443
          echo(name + " FAILED")
wenzelm@48425
   444
          echo("(see also " + log.file + ")")
wenzelm@48425
   445
          val lines = split_lines(out)
wenzelm@48425
   446
          val tail = lines.drop(lines.length - 20 max 0)
wenzelm@48425
   447
          echo("\n" + cat_lines(tail))
wenzelm@48425
   448
        }
wenzelm@48425
   449
        loop(pending - name, running - name, results + (name -> rc))
wenzelm@48425
   450
      }
wenzelm@48425
   451
      else if (running.size < (max_jobs max 1)) {
wenzelm@48425
   452
        pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48425
   453
          case Some((name, info)) =>
wenzelm@48425
   454
            if (list_only) {
wenzelm@48425
   455
              echo(name + " in " + info.dir)
wenzelm@48425
   456
              loop(pending - name, running, results + (name -> 0))
wenzelm@48425
   457
            }
wenzelm@48425
   458
            else if (info.parent.map(results(_)).forall(_ == 0)) {
wenzelm@48447
   459
              val output =
wenzelm@48447
   460
                if (build_images || queue.is_inner(name))
wenzelm@48447
   461
                  Some(Isabelle_System.standard_path(output_dir + Path.basic(name)))
wenzelm@48447
   462
                else None
wenzelm@48447
   463
              echo((if (output.isDefined) "Building " else "Running ") + name + " ...")
wenzelm@48467
   464
              val job = start_job(name, info, output, info.options, timing, verbose, browser_info)
wenzelm@48425
   465
              loop(pending, running + (name -> job), results)
wenzelm@48425
   466
            }
wenzelm@48425
   467
            else {
wenzelm@48425
   468
              echo(name + " CANCELLED")
wenzelm@48425
   469
              loop(pending - name, running, results + (name -> 1))
wenzelm@48425
   470
            }
wenzelm@48425
   471
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   472
        }
wenzelm@48373
   473
      }
wenzelm@48425
   474
      else { sleep(); loop(pending, running, results) }
wenzelm@48425
   475
    }
wenzelm@48425
   476
wenzelm@48425
   477
    (0 /: loop(queue, Map.empty, Map.empty))({ case (rc1, (_, rc2)) => rc1 max rc2 })
wenzelm@48341
   478
  }
wenzelm@48341
   479
wenzelm@48341
   480
wenzelm@48346
   481
  /* command line entry point */
wenzelm@48341
   482
wenzelm@48341
   483
  def main(args: Array[String])
wenzelm@48341
   484
  {
wenzelm@48346
   485
    Command_Line.tool {
wenzelm@48346
   486
      args.toList match {
wenzelm@48346
   487
        case
wenzelm@48346
   488
          Properties.Value.Boolean(all_sessions) ::
wenzelm@48346
   489
          Properties.Value.Boolean(build_images) ::
wenzelm@48425
   490
          Properties.Value.Int(max_jobs) ::
wenzelm@48346
   491
          Properties.Value.Boolean(list_only) ::
wenzelm@48447
   492
          Properties.Value.Boolean(system_mode) ::
wenzelm@48459
   493
          Properties.Value.Boolean(timing) ::
wenzelm@48425
   494
          Properties.Value.Boolean(verbose) ::
wenzelm@48346
   495
          Command_Line.Chunks(more_dirs, options, sessions) =>
wenzelm@48459
   496
            build(all_sessions, build_images, max_jobs, list_only, system_mode, timing,
wenzelm@48447
   497
              verbose, more_dirs.map(Path.explode), options, sessions)
wenzelm@48346
   498
        case _ => error("Bad arguments:\n" + cat_lines(args))
wenzelm@48341
   499
      }
wenzelm@48346
   500
    }
wenzelm@48341
   501
  }
wenzelm@48276
   502
}
wenzelm@48276
   503