1/*  Title:      Pure/System/isabelle_system.scala
2    Author:     Makarius
3
4Fundamental Isabelle system environment: quasi-static module with
5optional init operation.
6*/
7
8package isabelle
9
10
11import java.io.{File => JFile, IOException}
12import java.nio.file.{Path => JPath, Files, SimpleFileVisitor, FileVisitResult}
13import java.nio.file.attribute.BasicFileAttributes
14
15import scala.collection.mutable
16
17
18object Isabelle_System
19{
20  /** bootstrap information **/
21
22  def jdk_home(): String =
23  {
24    val java_home = System.getProperty("java.home", "")
25    val home = new JFile(java_home)
26    val parent = home.getParent
27    if (home.getName == "jre" && parent != null &&
28        (new JFile(new JFile(parent, "bin"), "javac")).exists) parent
29    else java_home
30  }
31
32  def bootstrap_directory(
33    preference: String, envar: String, property: String, description: String): String =
34  {
35    val value =
36      proper_string(preference) orElse  // explicit argument
37      proper_string(System.getenv(envar)) orElse  // e.g. inherited from running isabelle tool
38      proper_string(System.getProperty(property)) getOrElse  // e.g. via JVM application boot process
39      error("Unknown " + description + " directory")
40
41    if ((new JFile(value)).isDirectory) value
42    else error("Bad " + description + " directory " + quote(value))
43  }
44
45
46
47  /** implicit settings environment **/
48
49  @volatile private var _settings: Option[Map[String, String]] = None
50
51  def settings(): Map[String, String] =
52  {
53    if (_settings.isEmpty) init()  // unsynchronized check
54    _settings.get
55  }
56
57  def init(isabelle_root: String = "", cygwin_root: String = ""): Unit = synchronized {
58    if (_settings.isEmpty) {
59      val isabelle_root1 =
60        bootstrap_directory(isabelle_root, "ISABELLE_ROOT", "isabelle.root", "Isabelle root")
61
62      val cygwin_root1 =
63        if (Platform.is_windows)
64          bootstrap_directory(cygwin_root, "CYGWIN_ROOT", "cygwin.root", "Cygwin root")
65        else ""
66
67      if (Platform.is_windows) Cygwin.init(isabelle_root1, cygwin_root1)
68
69      def set_cygwin_root()
70      {
71        if (Platform.is_windows)
72          _settings = Some(_settings.getOrElse(Map.empty) + ("CYGWIN_ROOT" -> cygwin_root1))
73      }
74
75      set_cygwin_root()
76
77      def default(env: Map[String, String], entry: (String, String)): Map[String, String] =
78        if (env.isDefinedAt(entry._1) || entry._2 == "") env
79        else env + entry
80
81      val env =
82      {
83        val temp_windows =
84        {
85          val temp = if (Platform.is_windows) System.getenv("TEMP") else null
86          if (temp != null && temp.contains('\\')) temp else ""
87        }
88        val user_home = System.getProperty("user.home", "")
89        val isabelle_app = System.getProperty("isabelle.app", "")
90
91        default(
92          default(
93            default(sys.env + ("ISABELLE_JDK_HOME" -> File.standard_path(jdk_home())),
94              "TEMP_WINDOWS" -> temp_windows),
95            "HOME" -> user_home),
96          "ISABELLE_APP" -> "true")
97      }
98
99      val settings =
100      {
101        val dump = JFile.createTempFile("settings", null)
102        dump.deleteOnExit
103        try {
104          val cmd1 =
105            if (Platform.is_windows)
106              List(cygwin_root1 + "\\bin\\bash", "-l",
107                File.standard_path(isabelle_root1 + "\\bin\\isabelle"))
108            else
109              List(isabelle_root1 + "/bin/isabelle")
110          val cmd = cmd1 ::: List("getenv", "-d", dump.toString)
111
112          val (output, rc) = process_output(process(cmd, env = env, redirect = true))
113          if (rc != 0) error(output)
114
115          val entries =
116            (for (entry <- File.read(dump).split("\u0000") if entry != "") yield {
117              val i = entry.indexOf('=')
118              if (i <= 0) entry -> ""
119              else entry.substring(0, i) -> entry.substring(i + 1)
120            }).toMap
121          entries + ("PATH" -> entries("PATH_JVM")) - "PATH_JVM"
122        }
123        finally { dump.delete }
124      }
125      _settings = Some(settings)
126      set_cygwin_root()
127    }
128  }
129
130
131  /* getenv */
132
133  def getenv(name: String, env: Map[String, String] = settings()): String =
134    env.getOrElse(name, "")
135
136  def getenv_strict(name: String, env: Map[String, String] = settings()): String =
137    proper_string(getenv(name, env)) getOrElse
138      error("Undefined Isabelle environment variable: " + quote(name))
139
140  def cygwin_root(): String = getenv_strict("CYGWIN_ROOT")
141
142  def isabelle_id(): String =
143    proper_string(getenv("ISABELLE_ID")) getOrElse
144      Mercurial.repository(Path.explode("~~")).parent()
145
146
147
148  /** file-system operations **/
149
150  /* permissions */
151
152  def chmod(arg: String, path: Path): Unit =
153    bash("chmod " + arg + " " + File.bash_path(path)).check
154
155  def chown(arg: String, path: Path): Unit =
156    bash("chown " + arg + " " + File.bash_path(path)).check
157
158
159  /* directories */
160
161  def mkdirs(path: Path): Unit =
162    if (!path.is_dir) {
163      bash("perl -e \"use File::Path make_path; make_path('" + File.standard_path(path) + "');\"")
164      if (!path.is_dir) error("Failed to create directory: " + quote(File.platform_path(path)))
165    }
166
167  def copy_dir(dir1: Path, dir2: Path): Unit =
168    bash("cp -a " + File.bash_path(dir1) + " " + File.bash_path(dir2)).check
169
170
171  /* tmp files */
172
173  def isabelle_tmp_prefix(): JFile =
174  {
175    val path = Path.explode("$ISABELLE_TMP_PREFIX")
176    path.file.mkdirs  // low-level mkdirs
177    File.platform_file(path)
178  }
179
180  def tmp_file(name: String, ext: String = "", base_dir: JFile = isabelle_tmp_prefix()): JFile =
181  {
182    val suffix = if (ext == "") "" else "." + ext
183    val file = Files.createTempFile(base_dir.toPath, name, suffix).toFile
184    file.deleteOnExit
185    file
186  }
187
188  def with_tmp_file[A](name: String, ext: String = "")(body: Path => A): A =
189  {
190    val file = tmp_file(name, ext)
191    try { body(File.path(file)) } finally { file.delete }
192  }
193
194
195  /* tmp dirs */
196
197  def rm_tree(root: Path): Unit = rm_tree(root.file)
198
199  def rm_tree(root: JFile)
200  {
201    root.delete
202    if (root.isDirectory) {
203      Files.walkFileTree(root.toPath,
204        new SimpleFileVisitor[JPath] {
205          override def visitFile(file: JPath, attrs: BasicFileAttributes): FileVisitResult =
206          {
207            try { Files.deleteIfExists(file) }
208            catch { case _: IOException => }
209            FileVisitResult.CONTINUE
210          }
211
212          override def postVisitDirectory(dir: JPath, e: IOException): FileVisitResult =
213          {
214            if (e == null) {
215              try { Files.deleteIfExists(dir) }
216              catch { case _: IOException => }
217              FileVisitResult.CONTINUE
218            }
219            else throw e
220          }
221        }
222      )
223    }
224  }
225
226  def tmp_dir(name: String, base_dir: JFile = isabelle_tmp_prefix()): JFile =
227  {
228    val dir = Files.createTempDirectory(base_dir.toPath, name).toFile
229    dir.deleteOnExit
230    dir
231  }
232
233  def with_tmp_dir[A](name: String)(body: Path => A): A =
234  {
235    val dir = tmp_dir(name)
236    try { body(File.path(dir)) } finally { rm_tree(dir) }
237  }
238
239
240  /* quasi-atomic update of directory */
241
242  def update_directory(dir: Path, f: Path => Unit)
243  {
244    val new_dir = dir.ext("new")
245    val old_dir = dir.ext("old")
246
247    rm_tree(new_dir)
248    rm_tree(old_dir)
249
250    f(new_dir)
251
252    if (dir.is_dir) File.move(dir, old_dir)
253    File.move(new_dir, dir)
254    rm_tree(old_dir)
255  }
256
257
258
259  /** external processes **/
260
261  /* raw process */
262
263  def process(command_line: List[String],
264    cwd: JFile = null,
265    env: Map[String, String] = settings(),
266    redirect: Boolean = false): Process =
267  {
268    val proc = new ProcessBuilder
269    proc.command(command_line:_*)  // fragile on Windows
270    if (cwd != null) proc.directory(cwd)
271    if (env != null) {
272      proc.environment.clear
273      for ((x, y) <- env) proc.environment.put(x, y)
274    }
275    proc.redirectErrorStream(redirect)
276    proc.start
277  }
278
279  def process_output(proc: Process): (String, Int) =
280  {
281    proc.getOutputStream.close
282
283    val output = File.read_stream(proc.getInputStream)
284    val rc =
285      try { proc.waitFor }
286      finally {
287        proc.getInputStream.close
288        proc.getErrorStream.close
289        proc.destroy
290        Thread.interrupted
291      }
292    (output, rc)
293  }
294
295  def kill(signal: String, group_pid: String): (String, Int) =
296  {
297    val bash =
298      if (Platform.is_windows) List(cygwin_root() + "\\bin\\bash.exe")
299      else List("/usr/bin/env", "bash")
300    process_output(process(bash ::: List("-c", "kill -" + signal + " -" + group_pid)))
301  }
302
303
304  /* GNU bash */
305
306  def bash(script: String,
307    cwd: JFile = null,
308    env: Map[String, String] = settings(),
309    redirect: Boolean = false,
310    progress_stdout: String => Unit = (_: String) => (),
311    progress_stderr: String => Unit = (_: String) => (),
312    progress_limit: Option[Long] = None,
313    strict: Boolean = true,
314    cleanup: () => Unit = () => ()): Process_Result =
315  {
316    Bash.process(script, cwd = cwd, env = env, redirect = redirect, cleanup = cleanup).
317      result(progress_stdout, progress_stderr, progress_limit, strict)
318  }
319
320  def jconsole(): Process_Result =
321    bash("isabelle_jdk jconsole " + java.lang.ProcessHandle.current().pid).check
322
323  private lazy val gnutar_check: Boolean =
324    try { bash("tar --version").check.out.containsSlice("GNU tar") || error("") }
325    catch { case ERROR(_) => false }
326
327  def gnutar(
328    args: String,
329    dir: Path = Path.current,
330    original_owner: Boolean = false,
331    redirect: Boolean = false): Process_Result =
332  {
333    val options =
334      (if (dir.is_current) "" else "-C " + File.bash_path(dir) + " ") +
335      (if (original_owner) "" else "--owner=root --group=staff ")
336
337    if (gnutar_check) bash("tar " + options + args, redirect = redirect)
338    else error("Expected to find GNU tar executable")
339  }
340
341  def hostname(): String = bash("hostname -s").check.out
342
343  def open(arg: String): Unit =
344    bash("exec \"$ISABELLE_OPEN\" " + Bash.string(arg) + " >/dev/null 2>/dev/null &")
345
346  def pdf_viewer(arg: Path): Unit =
347    bash("exec \"$PDF_VIEWER\" " + File.bash_path(arg) + " >/dev/null 2>/dev/null &")
348
349  def export_isabelle_identifier(isabelle_identifier: String): String =
350    if (isabelle_identifier == "") ""
351    else "export ISABELLE_IDENTIFIER=" + Bash.string(isabelle_identifier) + "\n"
352
353
354
355  /** Isabelle resources **/
356
357  /* repository clone with Admin */
358
359  def admin(): Boolean = Path.explode("~~/Admin").is_dir
360
361
362  /* components */
363
364  def components(): List[Path] =
365    Path.split(getenv_strict("ISABELLE_COMPONENTS"))
366
367
368  /* classes */
369
370  def init_classes[A](variable: String): List[A] =
371  {
372    for (name <- space_explode(':', Isabelle_System.getenv_strict(variable)))
373    yield {
374      def err(msg: String): Nothing =
375        error("Bad entry " + quote(name) + " in " + variable + "\n" + msg)
376
377      try { Class.forName(name).asInstanceOf[Class[A]].newInstance() }
378      catch {
379        case _: ClassNotFoundException => err("Class not found")
380        case exn: Throwable => err(Exn.message(exn))
381      }
382    }
383  }
384
385
386  /* default logic */
387
388  def default_logic(args: String*): String =
389  {
390    args.find(_ != "") match {
391      case Some(logic) => logic
392      case None => Isabelle_System.getenv_strict("ISABELLE_LOGIC")
393    }
394  }
395}
396