src/Pure/System/build.scala
author wenzelm
Mon Jul 30 11:03:44 2012 +0200 (2012-07-30)
changeset 48594 c24907e5081e
parent 48592 a125b8040ada
child 48595 231e6fa96dbb
permissions -rw-r--r--
removed build option -f (cf. a125b8040ada), due to slightly inconvenient behaviour on ancestors;
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@48579
   132
        (opt(keyword(IN) ~! path ^^ { 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@48583
   273
    def is_empty: Boolean = deps.isEmpty
wenzelm@48504
   274
    def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
wenzelm@48423
   275
  }
wenzelm@48423
   276
wenzelm@48478
   277
  def dependencies(verbose: Boolean, queue: Session.Queue): Deps =
wenzelm@48423
   278
    Deps((Map.empty[String, Node] /: queue.topological_order)(
wenzelm@48422
   279
      { case (deps, (name, info)) =>
wenzelm@48422
   280
          val preloaded =
wenzelm@48422
   281
            info.parent match {
wenzelm@48422
   282
              case None => Set.empty[String]
wenzelm@48422
   283
              case Some(parent) => deps(parent).loaded_theories
wenzelm@48422
   284
            }
wenzelm@48422
   285
          val thy_info = new Thy_Info(new Thy_Load(preloaded))
wenzelm@48422
   286
wenzelm@48583
   287
          if (verbose) {
wenzelm@48583
   288
            val groups =
wenzelm@48583
   289
              if (info.groups.isEmpty) ""
wenzelm@48583
   290
              else info.groups.mkString(" (", " ", ")")
wenzelm@48583
   291
            echo("Checking " + name + groups + " ...")
wenzelm@48583
   292
          }
wenzelm@48478
   293
wenzelm@48422
   294
          val thy_deps =
wenzelm@48422
   295
            thy_info.dependencies(
wenzelm@48422
   296
              info.theories.map(_._2).flatten.
wenzelm@48422
   297
                map(thy => Document.Node.Name(info.dir + Thy_Load.thy_path(thy))))
wenzelm@48422
   298
wenzelm@48422
   299
          val loaded_theories = preloaded ++ thy_deps.map(_._1.theory)
wenzelm@48423
   300
wenzelm@48423
   301
          val all_files =
wenzelm@48422
   302
            thy_deps.map({ case (n, h) =>
wenzelm@48422
   303
              val thy = Path.explode(n.node).expand
wenzelm@48422
   304
              val uses =
wenzelm@48422
   305
                h match {
wenzelm@48422
   306
                  case Exn.Res(d) =>
wenzelm@48422
   307
                    d.uses.map(p => (Path.explode(n.dir) + Path.explode(p._1)).expand)
wenzelm@48422
   308
                  case _ => Nil
wenzelm@48422
   309
                }
wenzelm@48422
   310
              thy :: uses
wenzelm@48422
   311
            }).flatten ::: info.files.map(file => info.dir + file)
wenzelm@48485
   312
          val sources =
wenzelm@48485
   313
            try { all_files.map(p => (p, SHA1.digest(p))) }
wenzelm@48485
   314
            catch {
wenzelm@48485
   315
              case ERROR(msg) =>
wenzelm@48485
   316
                error(msg + "\nThe error(s) above occurred in session " + quote(name))
wenzelm@48485
   317
            }
wenzelm@48422
   318
wenzelm@48422
   319
          deps + (name -> Node(loaded_theories, sources))
wenzelm@48423
   320
      }))
wenzelm@48422
   321
wenzelm@48422
   322
wenzelm@48424
   323
  /* jobs */
wenzelm@48341
   324
wenzelm@48548
   325
  private class Job(dir: Path, env: Map[String, String], script: String, args: String,
wenzelm@48511
   326
    output: Path, do_output: Boolean)
wenzelm@48364
   327
  {
wenzelm@48418
   328
    private val args_file = File.tmp_file("args")
wenzelm@48418
   329
    private val env1 = env + ("ARGS_FILE" -> Isabelle_System.posix_path(args_file.getPath))
wenzelm@48418
   330
    File.write(args_file, args)
wenzelm@48418
   331
wenzelm@48424
   332
    private val (thread, result) =
wenzelm@48548
   333
      Simple_Thread.future("build") { Isabelle_System.bash_env(dir.file, env1, script) }
wenzelm@48418
   334
wenzelm@48418
   335
    def terminate: Unit = thread.interrupt
wenzelm@48418
   336
    def is_finished: Boolean = result.is_finished
wenzelm@48425
   337
    def join: (String, String, Int) = { val res = result.join; args_file.delete; res }
wenzelm@48511
   338
    def output_path: Option[Path] = if (do_output) Some(output) else None
wenzelm@48418
   339
  }
wenzelm@48418
   340
wenzelm@48511
   341
  private def start_job(name: String, info: Session.Info, output: Path, do_output: Boolean,
wenzelm@48545
   342
    options: Options, verbose: Boolean, browser_info: Path): Job =
wenzelm@48418
   343
  {
wenzelm@48467
   344
    // global browser info dir
wenzelm@48548
   345
    if (options.bool("browser_info") && !(browser_info + Path.explode("index.html")).is_file)
wenzelm@48467
   346
    {
wenzelm@48467
   347
      browser_info.file.mkdirs()
wenzelm@48467
   348
      File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
wenzelm@48467
   349
        browser_info + Path.explode("isabelle.gif"))
wenzelm@48467
   350
      File.write(browser_info + Path.explode("index.html"),
wenzelm@48467
   351
        File.read(Path.explode("~~/lib/html/library_index_header.template")) +
wenzelm@48467
   352
        File.read(Path.explode("~~/lib/html/library_index_content.template")) +
wenzelm@48467
   353
        File.read(Path.explode("~~/lib/html/library_index_footer.template")))
wenzelm@48467
   354
    }
wenzelm@48467
   355
wenzelm@48418
   356
    val parent = info.parent.getOrElse("")
wenzelm@48418
   357
wenzelm@48511
   358
    val env =
wenzelm@48511
   359
      Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> Isabelle_System.standard_path(output))
wenzelm@48364
   360
    val script =
wenzelm@48511
   361
      if (is_pure(name)) {
wenzelm@48511
   362
        if (do_output) "./build " + name + " \"$OUTPUT\""
wenzelm@48511
   363
        else """ rm -f "$OUTPUT"; ./build """ + name
wenzelm@48511
   364
      }
wenzelm@48418
   365
      else {
wenzelm@48418
   366
        """
wenzelm@48418
   367
        . "$ISABELLE_HOME/lib/scripts/timestart.bash"
wenzelm@48418
   368
        """ +
wenzelm@48511
   369
          (if (do_output)
wenzelm@48511
   370
            """
wenzelm@48511
   371
            "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT"
wenzelm@48511
   372
            """
wenzelm@48418
   373
          else
wenzelm@48511
   374
            """
wenzelm@48511
   375
            rm -f "$OUTPUT"; "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT"
wenzelm@48511
   376
            """) +
wenzelm@48418
   377
        """
wenzelm@48418
   378
        RC="$?"
wenzelm@48418
   379
wenzelm@48418
   380
        . "$ISABELLE_HOME/lib/scripts/timestop.bash"
wenzelm@48418
   381
wenzelm@48418
   382
        if [ "$RC" -eq 0 ]; then
wenzelm@48418
   383
          echo "Finished $TARGET ($TIMES_REPORT)" >&2
wenzelm@48418
   384
        fi
wenzelm@48418
   385
wenzelm@48418
   386
        exit "$RC"
wenzelm@48418
   387
        """
wenzelm@48418
   388
      }
wenzelm@48418
   389
    val args_xml =
wenzelm@48418
   390
    {
wenzelm@48418
   391
      import XML.Encode._
wenzelm@48545
   392
          pair(bool, pair(Options.encode, pair(bool, pair(Path.encode, pair(string,
wenzelm@48545
   393
            pair(string, list(pair(Options.encode, list(Path.encode)))))))))(
wenzelm@48545
   394
          (do_output, (options, (verbose, (browser_info, (parent,
wenzelm@48545
   395
            (name, info.theories)))))))
wenzelm@48418
   396
    }
wenzelm@48548
   397
    new Job(info.dir, env, script, YXML.string_of_body(args_xml), output, do_output)
wenzelm@48364
   398
  }
wenzelm@48364
   399
wenzelm@48424
   400
wenzelm@48504
   401
  /* log files and corresponding heaps */
wenzelm@48504
   402
wenzelm@48505
   403
  private val LOG = Path.explode("log")
wenzelm@48505
   404
  private def log(name: String): Path = LOG + Path.basic(name)
wenzelm@48505
   405
  private def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@48504
   406
wenzelm@48505
   407
  private def sources_stamp(digests: List[SHA1.Digest]): String =
wenzelm@48504
   408
    digests.map(_.toString).sorted.mkString("sources: ", " ", "")
wenzelm@48504
   409
wenzelm@48505
   410
  private def heap_stamp(output: Option[Path]): String =
wenzelm@48504
   411
  {
wenzelm@48504
   412
    "heap: " +
wenzelm@48504
   413
      (output match {
wenzelm@48504
   414
        case Some(path) =>
wenzelm@48504
   415
          val file = path.file
wenzelm@48504
   416
          if (file.isFile) file.length.toString + " " + file.lastModified.toString
wenzelm@48504
   417
          else "-"
wenzelm@48504
   418
        case None => "-"
wenzelm@48504
   419
      })
wenzelm@48504
   420
  }
wenzelm@48504
   421
wenzelm@48505
   422
  private def check_stamps(dir: Path, name: String): Option[(String, Boolean)] =
wenzelm@48504
   423
  {
wenzelm@48504
   424
    val file = (dir + log_gz(name)).file
wenzelm@48504
   425
    if (file.isFile) {
wenzelm@48504
   426
      val stream = new GZIPInputStream (new BufferedInputStream(new FileInputStream(file)))
wenzelm@48504
   427
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@48504
   428
      val (s, h) = try { (reader.readLine, reader.readLine) } finally { reader.close }
wenzelm@48504
   429
      if (s != null && s.startsWith("sources: ") && h != null && h.startsWith("heap: ") &&
wenzelm@48504
   430
          h == heap_stamp(Some(dir + Path.basic(name)))) Some((s, h != "heap: -"))
wenzelm@48504
   431
      else None
wenzelm@48504
   432
    }
wenzelm@48504
   433
    else None
wenzelm@48504
   434
  }
wenzelm@48504
   435
wenzelm@48504
   436
wenzelm@48425
   437
  /* build */
wenzelm@48424
   438
wenzelm@48509
   439
  def build(
wenzelm@48509
   440
    all_sessions: Boolean = false,
wenzelm@48511
   441
    build_heap: Boolean = false,
wenzelm@48509
   442
    more_dirs: List[Path] = Nil,
wenzelm@48509
   443
    session_groups: List[String] = Nil,
wenzelm@48509
   444
    max_jobs: Int = 1,
wenzelm@48509
   445
    no_build: Boolean = false,
wenzelm@48509
   446
    build_options: List[String] = Nil,
wenzelm@48509
   447
    system_mode: Boolean = false,
wenzelm@48509
   448
    verbose: Boolean = false,
wenzelm@48509
   449
    sessions: List[String] = Nil): Int =
wenzelm@48341
   450
  {
wenzelm@48509
   451
    val options = (Options.init() /: build_options)(_.define_simple(_))
wenzelm@48509
   452
    val queue = find_sessions(options, more_dirs, all_sessions, session_groups, sessions)
wenzelm@48478
   453
    val deps = dependencies(verbose, queue)
wenzelm@48368
   454
wenzelm@48504
   455
    def make_stamp(name: String): String =
wenzelm@48544
   456
      sources_stamp(queue(name).entry_digest :: deps.sources(name))
wenzelm@48504
   457
wenzelm@48504
   458
    val (input_dirs, output_dir, browser_info) =
wenzelm@48504
   459
      if (system_mode) {
wenzelm@48504
   460
        val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@48504
   461
        (List(output_dir), output_dir, Path.explode("~~/browser_info"))
wenzelm@48504
   462
      }
wenzelm@48504
   463
      else {
wenzelm@48504
   464
        val output_dir = Path.explode("$ISABELLE_OUTPUT")
wenzelm@48504
   465
        (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
wenzelm@48504
   466
         Path.explode("$ISABELLE_BROWSER_INFO"))
wenzelm@48504
   467
      }
wenzelm@48363
   468
wenzelm@48373
   469
    // prepare log dir
wenzelm@48504
   470
    (output_dir + LOG).file.mkdirs()
wenzelm@48373
   471
wenzelm@48425
   472
    // scheduler loop
wenzelm@48425
   473
    @tailrec def loop(
wenzelm@48425
   474
      pending: Session.Queue,
wenzelm@48425
   475
      running: Map[String, Job],
wenzelm@48537
   476
      results: Map[String, (Boolean, Int)]): Map[String, (Boolean, Int)] =
wenzelm@48425
   477
    {
wenzelm@48425
   478
      if (pending.is_empty) results
wenzelm@48547
   479
      else
wenzelm@48547
   480
        running.find({ case (_, job) => job.is_finished }) match {
wenzelm@48547
   481
          case Some((name, job)) =>
wenzelm@48547
   482
            // finish job
wenzelm@48424
   483
wenzelm@48547
   484
            val (out, err, rc) = job.join
wenzelm@48547
   485
            echo(Library.trim_line(err))
wenzelm@48373
   486
wenzelm@48547
   487
            if (rc == 0) {
wenzelm@48547
   488
              val sources = make_stamp(name)
wenzelm@48547
   489
              val heap = heap_stamp(job.output_path)
wenzelm@48549
   490
              (output_dir + log(name)).file.delete
wenzelm@48547
   491
              File.write_gzip(output_dir + log_gz(name), sources + "\n" + heap + "\n" + out)
wenzelm@48547
   492
            }
wenzelm@48547
   493
            else {
wenzelm@48549
   494
              (output_dir + log_gz(name)).file.delete
wenzelm@48547
   495
              File.write(output_dir + log(name), out)
wenzelm@48547
   496
              echo(name + " FAILED")
wenzelm@48547
   497
              echo("(see also " + log(name).file.toString + ")")
wenzelm@48547
   498
              val lines = split_lines(out)
wenzelm@48547
   499
              val tail = lines.drop(lines.length - 20 max 0)
wenzelm@48547
   500
              echo("\n" + cat_lines(tail))
wenzelm@48547
   501
            }
wenzelm@48547
   502
            loop(pending - name, running - name, results + (name -> (false, rc)))
wenzelm@48528
   503
wenzelm@48547
   504
          case None if (running.size < (max_jobs max 1)) =>
wenzelm@48547
   505
            // check/start next job
wenzelm@48547
   506
            pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48547
   507
              case Some((name, info)) =>
wenzelm@48547
   508
                val parent_result = info.parent.map(results(_))
wenzelm@48547
   509
                val parent_current = parent_result.forall(_._1)
wenzelm@48547
   510
                val parent_ok = parent_result.forall(_._2 == 0)
wenzelm@48504
   511
wenzelm@48547
   512
                val output = output_dir + Path.basic(name)
wenzelm@48547
   513
                val do_output = build_heap || queue.is_inner(name)
wenzelm@48547
   514
wenzelm@48547
   515
                val current =
wenzelm@48547
   516
                {
wenzelm@48548
   517
                  input_dirs.find(dir => (dir + log_gz(name)).is_file) match {
wenzelm@48547
   518
                    case Some(dir) =>
wenzelm@48547
   519
                      check_stamps(dir, name) match {
wenzelm@48547
   520
                        case Some((s, h)) => s == make_stamp(name) && (h || !do_output)
wenzelm@48547
   521
                        case None => false
wenzelm@48547
   522
                      }
wenzelm@48504
   523
                    case None => false
wenzelm@48504
   524
                  }
wenzelm@48547
   525
                }
wenzelm@48594
   526
                val all_current = current && parent_current
wenzelm@48528
   527
wenzelm@48547
   528
                if (all_current)
wenzelm@48547
   529
                  loop(pending - name, running, results + (name -> (true, 0)))
wenzelm@48547
   530
                else if (no_build)
wenzelm@48547
   531
                  loop(pending - name, running, results + (name -> (false, 1)))
wenzelm@48547
   532
                else if (parent_ok) {
wenzelm@48547
   533
                  echo((if (do_output) "Building " else "Running ") + name + " ...")
wenzelm@48547
   534
                  val job =
wenzelm@48547
   535
                    start_job(name, info, output, do_output, info.options, verbose, browser_info)
wenzelm@48547
   536
                  loop(pending, running + (name -> job), results)
wenzelm@48547
   537
                }
wenzelm@48547
   538
                else {
wenzelm@48547
   539
                  echo(name + " CANCELLED")
wenzelm@48547
   540
                  loop(pending - name, running, results + (name -> (false, 1)))
wenzelm@48547
   541
                }
wenzelm@48547
   542
              case None => sleep(); loop(pending, running, results)
wenzelm@48425
   543
            }
wenzelm@48425
   544
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   545
        }
wenzelm@48425
   546
    }
wenzelm@48425
   547
wenzelm@48583
   548
    val results =
wenzelm@48583
   549
      if (deps.is_empty) {
wenzelm@48583
   550
        echo("### Nothing to build")
wenzelm@48583
   551
        Map.empty
wenzelm@48583
   552
      }
wenzelm@48583
   553
      else loop(queue, Map.empty, Map.empty)
wenzelm@48583
   554
wenzelm@48537
   555
    val rc = (0 /: results)({ case (rc1, (_, (_, rc2))) => rc1 max rc2 })
wenzelm@48504
   556
    if (rc != 0 && (verbose || !no_build)) {
wenzelm@48552
   557
      val unfinished =
wenzelm@48552
   558
        (for ((name, (_, r)) <- results.iterator if r != 0) yield name).toList.sorted
wenzelm@48473
   559
      echo("Unfinished session(s): " + commas(unfinished))
wenzelm@48473
   560
    }
wenzelm@48473
   561
    rc
wenzelm@48341
   562
  }
wenzelm@48341
   563
wenzelm@48341
   564
wenzelm@48346
   565
  /* command line entry point */
wenzelm@48341
   566
wenzelm@48341
   567
  def main(args: Array[String])
wenzelm@48341
   568
  {
wenzelm@48346
   569
    Command_Line.tool {
wenzelm@48346
   570
      args.toList match {
wenzelm@48346
   571
        case
wenzelm@48346
   572
          Properties.Value.Boolean(all_sessions) ::
wenzelm@48511
   573
          Properties.Value.Boolean(build_heap) ::
wenzelm@48425
   574
          Properties.Value.Int(max_jobs) ::
wenzelm@48469
   575
          Properties.Value.Boolean(no_build) ::
wenzelm@48447
   576
          Properties.Value.Boolean(system_mode) ::
wenzelm@48425
   577
          Properties.Value.Boolean(verbose) ::
wenzelm@48509
   578
          Command_Line.Chunks(more_dirs, session_groups, build_options, sessions) =>
wenzelm@48594
   579
            build(all_sessions, build_heap, more_dirs.map(Path.explode), session_groups,
wenzelm@48594
   580
              max_jobs, no_build, build_options, system_mode, verbose, sessions)
wenzelm@48346
   581
        case _ => error("Bad arguments:\n" + cat_lines(args))
wenzelm@48341
   582
      }
wenzelm@48346
   583
    }
wenzelm@48341
   584
  }
wenzelm@48276
   585
}
wenzelm@48276
   586