src/Pure/Tools/build.scala
author wenzelm
Mon Oct 02 11:43:17 2017 +0200 (19 months ago)
changeset 66745 e7ac579b883c
parent 66744 fec1504e5f03
child 66746 888a51e77c6e
permissions -rw-r--r--
option -S for "isabelle build";
     1 /*  Title:      Pure/Tools/build.scala
     2     Author:     Makarius
     3     Options:    :folding=explicit:
     4 
     5 Build and manage Isabelle sessions.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import java.io.{BufferedInputStream, FileInputStream,
    12   BufferedReader, InputStreamReader, IOException}
    13 import java.util.zip.GZIPInputStream
    14 
    15 import scala.collection.SortedSet
    16 import scala.collection.mutable
    17 import scala.annotation.tailrec
    18 
    19 
    20 object Build
    21 {
    22   /** auxiliary **/
    23 
    24   /* persistent build info */
    25 
    26   sealed case class Session_Info(
    27     imported_sources: List[String],
    28     sources: List[String],
    29     input_heaps: List[String],
    30     output_heap: Option[String],
    31     return_code: Int)
    32 
    33 
    34   /* queue with scheduling information */
    35 
    36   private object Queue
    37   {
    38     def load_timings(progress: Progress, store: Sessions.Store, name: String)
    39       : (List[Properties.T], Double) =
    40     {
    41       val no_timings: (List[Properties.T], Double) = (Nil, 0.0)
    42 
    43       store.find_database(name) match {
    44         case None => no_timings
    45         case Some(database) =>
    46           def ignore_error(msg: String) =
    47           {
    48             progress.echo_warning("Ignoring bad database: " +
    49               database.expand + (if (msg == "") "" else "\n" + msg))
    50             no_timings
    51           }
    52           try {
    53             using(SQLite.open_database(database))(db =>
    54             {
    55               val command_timings = store.read_command_timings(db, name)
    56               val session_timing =
    57                 store.read_session_timing(db, name) match {
    58                   case Markup.Elapsed(t) => t
    59                   case _ => 0.0
    60                 }
    61               (command_timings, session_timing)
    62             })
    63           }
    64           catch {
    65             case ERROR(msg) => ignore_error(msg)
    66             case exn: java.lang.Error => ignore_error(Exn.message(exn))
    67             case _: XML.Error => ignore_error("")
    68           }
    69       }
    70     }
    71 
    72     def apply(progress: Progress, sessions: Sessions.T, store: Sessions.Store): Queue =
    73     {
    74       val graph = sessions.build_graph
    75       val names = graph.keys
    76 
    77       val timings = names.map(name => (name, load_timings(progress, store, name)))
    78       val command_timings =
    79         Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
    80       val session_timing =
    81         Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
    82 
    83       def outdegree(name: String): Int = graph.imm_succs(name).size
    84 
    85       object Ordering extends scala.math.Ordering[String]
    86       {
    87         def compare_timing(name1: String, name2: String): Int =
    88         {
    89           val t1 = session_timing(name1)
    90           val t2 = session_timing(name2)
    91           if (t1 == 0.0 || t2 == 0.0) 0
    92           else t1 compare t2
    93         }
    94 
    95         def compare(name1: String, name2: String): Int =
    96           outdegree(name2) compare outdegree(name1) match {
    97             case 0 =>
    98               compare_timing(name2, name1) match {
    99                 case 0 =>
   100                   sessions(name2).timeout compare sessions(name1).timeout match {
   101                     case 0 => name1 compare name2
   102                     case ord => ord
   103                   }
   104                 case ord => ord
   105               }
   106             case ord => ord
   107           }
   108       }
   109 
   110       new Queue(graph, SortedSet(names: _*)(Ordering), command_timings)
   111     }
   112   }
   113 
   114   private class Queue(
   115     graph: Graph[String, Sessions.Info],
   116     order: SortedSet[String],
   117     val command_timings: String => List[Properties.T])
   118   {
   119     def is_inner(name: String): Boolean = !graph.is_maximal(name)
   120 
   121     def is_empty: Boolean = graph.is_empty
   122 
   123     def - (name: String): Queue =
   124       new Queue(graph.del_node(name),
   125         order - name,  // FIXME scala-2.10.0 TreeSet problem!?
   126         command_timings)
   127 
   128     def dequeue(skip: String => Boolean): Option[(String, Sessions.Info)] =
   129     {
   130       val it = order.iterator.dropWhile(name =>
   131         skip(name)
   132           || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
   133           || !graph.is_minimal(name))
   134       if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
   135       else None
   136     }
   137   }
   138 
   139 
   140   /* PIDE protocol handler */
   141 
   142   class Handler(progress: Progress, session: Session, session_name: String)
   143     extends Session.Protocol_Handler
   144   {
   145     val result_error: Promise[String] = Future.promise
   146 
   147     override def exit() { result_error.cancel }
   148 
   149     private def build_session_finished(msg: Prover.Protocol_Output): Boolean =
   150     {
   151       val error_message =
   152         try { Pretty.string_of(Symbol.decode_yxml(msg.text)) }
   153         catch { case ERROR(msg) => msg }
   154       result_error.fulfill(error_message)
   155       session.send_stop()
   156       true
   157     }
   158 
   159     private def loading_theory(msg: Prover.Protocol_Output): Boolean =
   160       msg.properties match {
   161         case Markup.Loading_Theory(name) =>
   162           progress.theory(session_name, name)
   163           true
   164         case _ => false
   165       }
   166 
   167     val functions =
   168       List(
   169         Markup.BUILD_SESSION_FINISHED -> build_session_finished _,
   170         Markup.LOADING_THEORY -> loading_theory _)
   171   }
   172 
   173 
   174   /* job: running prover process */
   175 
   176   private class Job(progress: Progress,
   177     name: String,
   178     val info: Sessions.Info,
   179     sessions: Sessions.T,
   180     deps: Sessions.Deps,
   181     store: Sessions.Store,
   182     do_output: Boolean,
   183     verbose: Boolean,
   184     pide: Boolean,
   185     val numa_node: Option[Int],
   186     command_timings: List[Properties.T])
   187   {
   188     val output = store.output_dir + Path.basic(name)
   189     def output_path: Option[Path] = if (do_output) Some(output) else None
   190     output.file.delete
   191 
   192     val options =
   193       numa_node match {
   194         case None => info.options
   195         case Some(n) => info.options.string("ML_process_policy") = NUMA.policy(n)
   196       }
   197 
   198     private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
   199     isabelle.graphview.Graph_File.write(options, graph_file, deps(name).session_graph)
   200 
   201     private val future_result: Future[Process_Result] =
   202       Future.thread("build") {
   203         val parent = info.parent.getOrElse("")
   204         val base = deps(name)
   205         val args_yxml =
   206           YXML.string_of_body(
   207             {
   208               import XML.Encode._
   209               pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
   210                 pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
   211                 pair(string, pair(string, pair(string, pair(Path.encode,
   212                 pair(list(pair(Options.encode, list(pair(string, properties)))),
   213                 pair(list(pair(string, string)), pair(list(string),
   214                 list(pair(string, string))))))))))))))))(
   215               (Symbol.codes, (command_timings, (do_output, (verbose,
   216                 (store.browser_info, (info.document_files, (File.standard_path(graph_file),
   217                 (parent, (info.chapter, (name, (Path.current,
   218                 (info.theories,
   219                 (base.global_theories.toList, (base.loaded_theories.keys,
   220                 base.dest_known_theories)))))))))))))))
   221             })
   222 
   223         val env =
   224           Isabelle_System.settings() +
   225             ("ISABELLE_ML_DEBUGGER" -> options.bool("ML_debugger").toString)
   226 
   227         def save_heap: String =
   228           "ML_Heap.share_common_data (); ML_Heap.save_child " +
   229             ML_Syntax.print_string0(File.platform_path(output))
   230 
   231         if (pide && !Sessions.is_pure(name)) {
   232           val resources = new Resources(deps(parent))
   233           val session = new Session(options, resources)
   234           val handler = new Handler(progress, session, name)
   235           session.init_protocol_handler(handler)
   236 
   237           val session_result = Future.promise[Process_Result]
   238 
   239           Isabelle_Process.start(session, options, logic = parent,
   240             cwd = info.dir.file, env = env, sessions = Some(sessions), store = store,
   241             phase_changed =
   242             {
   243               case Session.Ready => session.protocol_command("build_session", args_yxml)
   244               case Session.Terminated(result) => session_result.fulfill(result)
   245               case _ =>
   246             })
   247 
   248           val result = session_result.join
   249           handler.result_error.join match {
   250             case "" => result
   251             case msg =>
   252               result.copy(
   253                 rc = result.rc max 1,
   254                 out_lines = result.out_lines ::: split_lines(Output.error_message_text(msg)))
   255           }
   256         }
   257         else {
   258           val args_file = Isabelle_System.tmp_file("build")
   259           File.write(args_file, args_yxml)
   260 
   261           val eval =
   262             "Command_Line.tool0 (fn () => (" +
   263             "Build.build " + ML_Syntax.print_string0(File.standard_path(args_file)) +
   264             (if (do_output) "; " + save_heap else "") + "));"
   265 
   266           val process =
   267             if (Sessions.is_pure(name)) {
   268               ML_Process(options, raw_ml_system = true, cwd = info.dir.file,
   269                 args =
   270                   (for ((root, _) <- Thy_Header.ml_roots) yield List("--use", root)).flatten :::
   271                   List("--eval", eval),
   272                 env = env, sessions = Some(sessions), store = store,
   273                 cleanup = () => args_file.delete)
   274             }
   275             else {
   276               ML_Process(options, parent, List("--eval", eval), cwd = info.dir.file,
   277                 env = env, sessions = Some(sessions), store = store,
   278                 cleanup = () => args_file.delete)
   279             }
   280 
   281           process.result(
   282             progress_stdout = (line: String) =>
   283               Library.try_unprefix("\floading_theory = ", line) match {
   284                 case Some(theory) => progress.theory(name, theory)
   285                 case None =>
   286               },
   287             progress_limit =
   288               options.int("process_output_limit") match {
   289                 case 0 => None
   290                 case m => Some(m * 1000000L)
   291               },
   292             strict = false)
   293         }
   294       }
   295 
   296     def terminate: Unit = future_result.cancel
   297     def is_finished: Boolean = future_result.is_finished
   298 
   299     @volatile private var was_timeout = false
   300     private val timeout_request: Option[Event_Timer.Request] =
   301     {
   302       if (info.timeout > Time.zero)
   303         Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
   304       else None
   305     }
   306 
   307     def join: Process_Result =
   308     {
   309       val result = future_result.join
   310 
   311       if (result.ok)
   312         Present.finish(progress, store.browser_info, graph_file, info, name)
   313 
   314       graph_file.delete
   315       timeout_request.foreach(_.cancel)
   316 
   317       if (result.interrupted) {
   318         if (was_timeout) result.error(Output.error_message_text("Timeout")).was_timeout
   319         else result.error(Output.error_message_text("Interrupt"))
   320       }
   321       else result
   322     }
   323   }
   324 
   325 
   326 
   327   /** build with results **/
   328 
   329   class Results private[Build](results: Map[String, (Option[Process_Result], Sessions.Info)])
   330   {
   331     def sessions: Set[String] = results.keySet
   332     def cancelled(name: String): Boolean = results(name)._1.isEmpty
   333     def apply(name: String): Process_Result = results(name)._1.getOrElse(Process_Result(1))
   334     def info(name: String): Sessions.Info = results(name)._2
   335     val rc =
   336       (0 /: results.iterator.map(
   337         { case (_, (Some(r), _)) => r.rc case (_, (None, _)) => 1 }))(_ max _)
   338     def ok: Boolean = rc == 0
   339 
   340     override def toString: String = rc.toString
   341   }
   342 
   343   def build(
   344     options: Options,
   345     progress: Progress = No_Progress,
   346     check_unknown_files: Boolean = false,
   347     build_heap: Boolean = false,
   348     clean_build: Boolean = false,
   349     dirs: List[Path] = Nil,
   350     select_dirs: List[Path] = Nil,
   351     numa_shuffling: Boolean = false,
   352     max_jobs: Int = 1,
   353     list_files: Boolean = false,
   354     check_keywords: Set[String] = Set.empty,
   355     no_build: Boolean = false,
   356     soft_build: Boolean = false,
   357     system_mode: Boolean = false,
   358     verbose: Boolean = false,
   359     pide: Boolean = false,
   360     requirements: Boolean = false,
   361     all_sessions: Boolean = false,
   362     base_sessions: List[String] = Nil,
   363     exclude_session_groups: List[String] = Nil,
   364     exclude_sessions: List[String] = Nil,
   365     session_groups: List[String] = Nil,
   366     sessions: List[String] = Nil,
   367     selection: Sessions.Selection = Sessions.Selection.empty): Results =
   368   {
   369     val build_options = options.int.update("completion_limit", 0).bool.update("ML_statistics", true)
   370 
   371     val store = Sessions.store(system_mode)
   372 
   373 
   374     /* session selection and dependencies */
   375 
   376     val full_sessions = Sessions.load(build_options, dirs, select_dirs)
   377 
   378     def imported_sources_stamp(deps: Sessions.Deps, name: String): List[String] =
   379       deps.imported_sources(name).map(_.toString).sorted
   380 
   381     def sources_stamp(deps: Sessions.Deps, name: String): List[String] =
   382       (full_sessions(name).meta_digest :: deps.sources(name)).map(_.toString).sorted
   383 
   384     val (selected, selected_sessions, deps) =
   385     {
   386       val (selected0, selected_sessions0) =
   387         full_sessions.selection(
   388             Sessions.Selection(requirements, all_sessions, base_sessions, exclude_session_groups,
   389               exclude_sessions, session_groups, sessions) ++ selection)
   390 
   391       val deps0 =
   392         Sessions.deps(selected_sessions0, progress = progress, inlined_files = true,
   393           verbose = verbose, list_files = list_files, check_keywords = check_keywords,
   394           global_theories = full_sessions.global_theories).check_errors
   395 
   396       if (soft_build) {
   397         val outdated =
   398           selected0.flatMap(name =>
   399             store.find_database(name) match {
   400               case Some(database) =>
   401                 using(SQLite.open_database(database))(store.read_build(_, name)) match {
   402                   case Some(build)
   403                   if build.return_code == 0 &&
   404                     build.imported_sources == imported_sources_stamp(deps0, name) &&
   405                     build.sources == sources_stamp(deps0, name) => None
   406                   case _ => Some(name)
   407                 }
   408               case None => Some(name)
   409             })
   410         val (selected, selected_sessions) =
   411           full_sessions.selection(Sessions.Selection(sessions = outdated))
   412         val deps =
   413           Sessions.deps(selected_sessions, inlined_files = true,
   414             global_theories = full_sessions.global_theories).check_errors
   415         (selected, selected_sessions, deps)
   416       }
   417       else (selected0, selected_sessions0, deps0)
   418     }
   419 
   420 
   421     /* check unknown files */
   422 
   423     if (check_unknown_files) {
   424       val source_files =
   425         (for {
   426           (_, base) <- deps.session_bases.iterator
   427           (path, _) <- base.sources.iterator
   428         } yield path).toList
   429       val unknown_files = Mercurial.unknown_files(source_files)
   430       if (unknown_files.nonEmpty) {
   431         progress.echo_warning("Unknown files (not part of a Mercurial repository):" +
   432           unknown_files.map(path => path.expand.implode).sorted.mkString("\n  ", "\n  ", ""))
   433       }
   434     }
   435 
   436 
   437     /* main build process */
   438 
   439     val queue = Queue(progress, selected_sessions, store)
   440 
   441     store.prepare_output()
   442 
   443     // optional cleanup
   444     if (clean_build) {
   445       for (name <- full_sessions.build_descendants(selected)) {
   446         val files =
   447           List(Path.basic(name), store.database(name), store.log(name), store.log_gz(name)).
   448             map(store.output_dir + _).filter(_.is_file)
   449         if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
   450         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   451       }
   452     }
   453 
   454     // scheduler loop
   455     case class Result(
   456       current: Boolean,
   457       heap_stamp: Option[String],
   458       process: Option[Process_Result],
   459       info: Sessions.Info)
   460     {
   461       def ok: Boolean =
   462         process match {
   463           case None => false
   464           case Some(res) => res.rc == 0
   465         }
   466     }
   467 
   468     def sleep()
   469     {
   470       try { Thread.sleep(500) }
   471       catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
   472     }
   473 
   474     val numa_nodes = new NUMA.Nodes(numa_shuffling)
   475 
   476     @tailrec def loop(
   477       pending: Queue,
   478       running: Map[String, (List[String], Job)],
   479       results: Map[String, Result]): Map[String, Result] =
   480     {
   481       def used_node(i: Int): Boolean =
   482         running.iterator.exists(
   483           { case (_, (_, job)) => job.numa_node.isDefined && job.numa_node.get == i })
   484 
   485       if (pending.is_empty) results
   486       else {
   487         if (progress.stopped)
   488           for ((_, (_, job)) <- running) job.terminate
   489 
   490         running.find({ case (_, (_, job)) => job.is_finished }) match {
   491           case Some((name, (input_heaps, job))) =>
   492             //{{{ finish job
   493 
   494             val process_result = job.join
   495 
   496             val log_lines = process_result.out_lines.filterNot(_.startsWith("\f"))
   497             val process_result_tail =
   498             {
   499               val tail = job.info.options.int("process_output_tail")
   500               process_result.copy(
   501                 out_lines =
   502                   "(see also " + (store.output_dir + store.log(name)).file.toString + ")" ::
   503                   (if (tail == 0) log_lines else log_lines.drop(log_lines.length - tail max 0)))
   504             }
   505 
   506 
   507             // write log file
   508             val heap_stamp =
   509               if (process_result.ok) {
   510                 (store.output_dir + store.log(name)).file.delete
   511                 val heap_stamp =
   512                   for (path <- job.output_path if path.is_file)
   513                     yield Sessions.write_heap_digest(path)
   514 
   515                 File.write_gzip(store.output_dir + store.log_gz(name), terminate_lines(log_lines))
   516 
   517                 heap_stamp
   518               }
   519               else {
   520                 (store.output_dir + Path.basic(name)).file.delete
   521                 (store.output_dir + store.log_gz(name)).file.delete
   522 
   523                 File.write(store.output_dir + store.log(name), terminate_lines(log_lines))
   524 
   525                 None
   526               }
   527 
   528             // write database
   529             {
   530               val database = store.output_dir + store.database(name)
   531               database.file.delete
   532 
   533               using(SQLite.open_database(database))(db =>
   534                 store.write_session_info(db, name,
   535                   build_log =
   536                     Build_Log.Log_File(name, process_result.out_lines).
   537                       parse_session_info(
   538                         command_timings = true, ml_statistics = true, task_statistics = true),
   539                   build =
   540                     Session_Info(
   541                       imported_sources_stamp(deps, name),
   542                       sources_stamp(deps, name),
   543                       input_heaps,
   544                       heap_stamp,
   545                       process_result.rc)))
   546             }
   547 
   548             // messages
   549             process_result.err_lines.foreach(progress.echo(_))
   550 
   551             if (process_result.ok)
   552               progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
   553             else {
   554               progress.echo(name + " FAILED")
   555               if (!process_result.interrupted) progress.echo(process_result_tail.out)
   556             }
   557 
   558             loop(pending - name, running - name,
   559               results + (name -> Result(false, heap_stamp, Some(process_result_tail), job.info)))
   560             //}}}
   561           case None if running.size < (max_jobs max 1) =>
   562             //{{{ check/start next job
   563             pending.dequeue(running.isDefinedAt(_)) match {
   564               case Some((name, info)) =>
   565                 val ancestor_results = selected_sessions.build_ancestors(name).map(results(_))
   566                 val ancestor_heaps = ancestor_results.flatMap(_.heap_stamp)
   567 
   568                 val do_output = build_heap || Sessions.is_pure(name) || queue.is_inner(name)
   569 
   570                 val (current, heap_stamp) =
   571                 {
   572                   store.find_database_heap(name) match {
   573                     case Some((database, heap_stamp)) =>
   574                       using(SQLite.open_database(database))(store.read_build(_, name)) match {
   575                         case Some(build) =>
   576                           val current =
   577                             build.return_code == 0 &&
   578                             build.sources == sources_stamp(deps, name) &&
   579                             build.input_heaps == ancestor_heaps &&
   580                             build.output_heap == heap_stamp &&
   581                             !(do_output && heap_stamp.isEmpty)
   582                           (current, heap_stamp)
   583                         case None => (false, None)
   584                       }
   585                     case None => (false, None)
   586                   }
   587                 }
   588                 val all_current = current && ancestor_results.forall(_.current)
   589 
   590                 if (all_current)
   591                   loop(pending - name, running,
   592                     results + (name -> Result(true, heap_stamp, Some(Process_Result(0)), info)))
   593                 else if (no_build) {
   594                   if (verbose) progress.echo("Skipping " + name + " ...")
   595                   loop(pending - name, running,
   596                     results + (name -> Result(false, heap_stamp, Some(Process_Result(1)), info)))
   597                 }
   598                 else if (ancestor_results.forall(_.ok) && !progress.stopped) {
   599                   val numa_node = numa_nodes.next(used_node(_))
   600                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   601                   val job =
   602                     new Job(progress, name, info, selected_sessions, deps, store, do_output,
   603                       verbose, pide, numa_node, queue.command_timings(name))
   604                   loop(pending, running + (name -> (ancestor_heaps, job)), results)
   605                 }
   606                 else {
   607                   progress.echo(name + " CANCELLED")
   608                   loop(pending - name, running,
   609                     results + (name -> Result(false, heap_stamp, None, info)))
   610                 }
   611               case None => sleep(); loop(pending, running, results)
   612             }
   613             ///}}}
   614           case None => sleep(); loop(pending, running, results)
   615         }
   616       }
   617     }
   618 
   619 
   620     /* build results */
   621 
   622     val results0 =
   623       if (deps.is_empty) {
   624         progress.echo_warning("Nothing to build")
   625         Map.empty[String, Result]
   626       }
   627       else loop(queue, Map.empty, Map.empty)
   628 
   629     val results =
   630       new Results(
   631         (for ((name, result) <- results0.iterator)
   632           yield (name, (result.process, result.info))).toMap)
   633 
   634     if (results.rc != 0 && (verbose || !no_build)) {
   635       val unfinished =
   636         (for {
   637           name <- results.sessions.iterator
   638           if !results(name).ok
   639          } yield name).toList.sorted
   640       progress.echo("Unfinished session(s): " + commas(unfinished))
   641     }
   642 
   643 
   644     /* global browser info */
   645 
   646     if (!no_build) {
   647       val browser_chapters =
   648         (for {
   649           (name, result) <- results0.iterator
   650           if result.ok
   651           info = full_sessions(name)
   652           if info.options.bool("browser_info")
   653         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   654             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   655 
   656       for ((chapter, entries) <- browser_chapters)
   657         Present.update_chapter_index(store.browser_info, chapter, entries)
   658 
   659       if (browser_chapters.nonEmpty) Present.make_global_index(store.browser_info)
   660     }
   661 
   662     results
   663   }
   664 
   665 
   666   /* Isabelle tool wrapper */
   667 
   668   val isabelle_tool = Isabelle_Tool("build", "build and manage Isabelle sessions", args =>
   669   {
   670     val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
   671 
   672     var base_sessions: List[String] = Nil
   673     var select_dirs: List[Path] = Nil
   674     var numa_shuffling = false
   675     var pide = false
   676     var requirements = false
   677     var soft_build = false
   678     var exclude_session_groups: List[String] = Nil
   679     var all_sessions = false
   680     var build_heap = false
   681     var clean_build = false
   682     var dirs: List[Path] = Nil
   683     var session_groups: List[String] = Nil
   684     var max_jobs = 1
   685     var check_keywords: Set[String] = Set.empty
   686     var list_files = false
   687     var no_build = false
   688     var options = (Options.init() /: build_options)(_ + _)
   689     var system_mode = false
   690     var verbose = false
   691     var exclude_sessions: List[String] = Nil
   692 
   693     val getopts = Getopts("""
   694 Usage: isabelle build [OPTIONS] [SESSIONS ...]
   695 
   696   Options are:
   697     -B NAME      include session NAME and all descendants
   698     -D DIR       include session directory and select its sessions
   699     -N           cyclic shuffling of NUMA CPU nodes (performance tuning)
   700     -P           build via PIDE protocol
   701     -R           operate on requirements of selected sessions
   702     -S           soft build: only observe changes of sources, not heap images
   703     -X NAME      exclude sessions from group NAME and all descendants
   704     -a           select all sessions
   705     -b           build heap images
   706     -c           clean build
   707     -d DIR       include session directory
   708     -g NAME      select session group NAME
   709     -j INT       maximum number of parallel jobs (default 1)
   710     -k KEYWORD   check theory sources for conflicts with proposed keywords
   711     -l           list session source files
   712     -n           no build -- test dependencies only
   713     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   714     -s           system build mode: produce output in ISABELLE_HOME
   715     -v           verbose
   716     -x NAME      exclude session NAME and all descendants
   717 
   718   Build and manage Isabelle sessions, depending on implicit settings:
   719 
   720 """ + Library.prefix_lines("  ", Build_Log.Settings.show()) + "\n",
   721       "B:" -> (arg => base_sessions = base_sessions ::: List(arg)),
   722       "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   723       "N" -> (_ => numa_shuffling = true),
   724       "P" -> (_ => pide = true),
   725       "R" -> (_ => requirements = true),
   726       "S" -> (_ => soft_build = true),
   727       "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   728       "a" -> (_ => all_sessions = true),
   729       "b" -> (_ => build_heap = true),
   730       "c" -> (_ => clean_build = true),
   731       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   732       "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   733       "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
   734       "k:" -> (arg => check_keywords = check_keywords + arg),
   735       "l" -> (_ => list_files = true),
   736       "n" -> (_ => no_build = true),
   737       "o:" -> (arg => options = options + arg),
   738       "s" -> (_ => system_mode = true),
   739       "v" -> (_ => verbose = true),
   740       "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   741 
   742     val sessions = getopts(args)
   743 
   744     val progress = new Console_Progress(verbose = verbose)
   745 
   746     val start_date = Date.now()
   747 
   748     if (verbose) {
   749       progress.echo(
   750         "Started at " + Build_Log.print_date(start_date) +
   751           " (" + Isabelle_System.getenv("ML_IDENTIFIER") + " on " + Isabelle_System.hostname() +")")
   752       progress.echo(Build_Log.Settings.show() + "\n")
   753     }
   754 
   755     val results =
   756       progress.interrupt_handler {
   757         build(options, progress,
   758           check_unknown_files = Mercurial.is_repository(Path.explode("~~")),
   759           build_heap = build_heap,
   760           clean_build = clean_build,
   761           dirs = dirs,
   762           select_dirs = select_dirs,
   763           numa_shuffling = NUMA.enabled_warning(progress, numa_shuffling),
   764           max_jobs = max_jobs,
   765           list_files = list_files,
   766           check_keywords = check_keywords,
   767           no_build = no_build,
   768           soft_build = soft_build,
   769           system_mode = system_mode,
   770           verbose = verbose,
   771           pide = pide,
   772           requirements = requirements,
   773           all_sessions = all_sessions,
   774           base_sessions = base_sessions,
   775           exclude_session_groups = exclude_session_groups,
   776           exclude_sessions = exclude_sessions,
   777           session_groups = session_groups,
   778           sessions = sessions)
   779       }
   780     val end_date = Date.now()
   781     val elapsed_time = end_date.time - start_date.time
   782 
   783     if (verbose) {
   784       progress.echo("\nFinished at " + Build_Log.print_date(end_date))
   785     }
   786 
   787     val total_timing =
   788       (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
   789         copy(elapsed = elapsed_time)
   790     progress.echo(total_timing.message_resources)
   791 
   792     sys.exit(results.rc)
   793   })
   794 }