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