src/Pure/System/standard_system.scala
author wenzelm
Thu Jun 23 14:52:32 2011 +0200 (2011-06-23)
changeset 43520 cec9b95fa35d
parent 43516 1c4736b9396a
child 43661 39fdbd814c7f
permissions -rw-r--r--
explicit import java.lang.System to prevent odd scope problems;
     1 /*  Title:      Pure/System/standard_system.scala
     2     Author:     Makarius
     3 
     4 Standard system operations, with basic Cygwin/Posix compatibility.
     5 */
     6 
     7 package isabelle
     8 
     9 import java.lang.System
    10 import java.util.zip.{ZipEntry, ZipInputStream}
    11 import java.util.regex.Pattern
    12 import java.util.Locale
    13 import java.net.URL
    14 import java.io.{BufferedWriter, OutputStreamWriter, FileOutputStream, BufferedOutputStream,
    15   BufferedInputStream, InputStream, FileInputStream, BufferedReader, InputStreamReader,
    16   File, FileFilter, IOException}
    17 import java.nio.charset.Charset
    18 
    19 import scala.io.{Source, Codec}
    20 import scala.util.matching.Regex
    21 import scala.collection.mutable
    22 
    23 
    24 object Standard_System
    25 {
    26   /* UTF-8 charset */
    27 
    28   val charset_name: String = "UTF-8"
    29   val charset: Charset = Charset.forName(charset_name)
    30   def codec(): Codec = Codec(charset)
    31 
    32   def string_bytes(s: String): Array[Byte] = s.getBytes(charset)
    33 
    34 
    35   /* permissive UTF-8 decoding */
    36 
    37   // see also http://en.wikipedia.org/wiki/UTF-8#Description
    38   // overlong encodings enable byte-stuffing
    39 
    40   def decode_permissive_utf8(text: CharSequence): String =
    41   {
    42     val buf = new java.lang.StringBuilder(text.length)
    43     var code = -1
    44     var rest = 0
    45     def flush()
    46     {
    47       if (code != -1) {
    48         if (rest == 0 && Character.isValidCodePoint(code))
    49           buf.appendCodePoint(code)
    50         else buf.append('\uFFFD')
    51         code = -1
    52         rest = 0
    53       }
    54     }
    55     def init(x: Int, n: Int)
    56     {
    57       flush()
    58       code = x
    59       rest = n
    60     }
    61     def push(x: Int)
    62     {
    63       if (rest <= 0) init(x, -1)
    64       else {
    65         code <<= 6
    66         code += x
    67         rest -= 1
    68       }
    69     }
    70     for (i <- 0 until text.length) {
    71       val c = text.charAt(i)
    72       if (c < 128) { flush(); buf.append(c) }
    73       else if ((c & 0xC0) == 0x80) push(c & 0x3F)
    74       else if ((c & 0xE0) == 0xC0) init(c & 0x1F, 1)
    75       else if ((c & 0xF0) == 0xE0) init(c & 0x0F, 2)
    76       else if ((c & 0xF8) == 0xF0) init(c & 0x07, 3)
    77     }
    78     flush()
    79     buf.toString
    80   }
    81 
    82 
    83   /* basic file operations */
    84 
    85   def slurp(reader: BufferedReader): String =
    86   {
    87     val output = new StringBuilder(100)
    88     var c = -1
    89     while ({ c = reader.read; c != -1 }) output += c.toChar
    90     reader.close
    91     output.toString
    92   }
    93 
    94   def slurp(stream: InputStream): String =
    95     slurp(new BufferedReader(new InputStreamReader(stream, charset)))
    96 
    97   def read_file(file: File): String = slurp(new FileInputStream(file))
    98 
    99   def write_file(file: File, text: CharSequence)
   100   {
   101     val writer =
   102       new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset))
   103     try { writer.append(text) }
   104     finally { writer.close }
   105   }
   106 
   107   def with_tmp_file[A](prefix: String)(body: File => A): A =
   108   {
   109     val file = File.createTempFile(prefix, null)
   110     file.deleteOnExit
   111     try { body(file) } finally { file.delete }
   112   }
   113 
   114   // FIXME handle (potentially cyclic) directory graph
   115   def find_files(start: File, ok: File => Boolean): List[File] =
   116   {
   117     val files = new mutable.ListBuffer[File]
   118     val filter = new FileFilter { def accept(entry: File) = entry.isDirectory || ok(entry) }
   119     def find_entry(entry: File)
   120     {
   121       if (ok(entry)) files += entry
   122       if (entry.isDirectory) entry.listFiles(filter).foreach(find_entry)
   123     }
   124     find_entry(start)
   125     files.toList
   126   }
   127 
   128 
   129   /* shell processes */
   130 
   131   def raw_execute(cwd: File, env: Map[String, String], redirect: Boolean, args: String*): Process =
   132   {
   133     val cmdline = new java.util.LinkedList[String]
   134     for (s <- args) cmdline.add(s)
   135 
   136     val proc = new ProcessBuilder(cmdline)
   137     if (cwd != null) proc.directory(cwd)
   138     if (env != null) {
   139       proc.environment.clear
   140       for ((x, y) <- env) proc.environment.put(x, y)
   141     }
   142     proc.redirectErrorStream(redirect)
   143     proc.start
   144   }
   145 
   146   def process_output(proc: Process): (String, Int) =
   147   {
   148     proc.getOutputStream.close
   149     val output = slurp(proc.getInputStream)
   150     val rc =
   151       try { proc.waitFor }
   152       finally {
   153         proc.getInputStream.close
   154         proc.getErrorStream.close
   155         proc.destroy
   156         Thread.interrupted
   157       }
   158     (output, rc)
   159   }
   160 
   161   def raw_exec(cwd: File, env: Map[String, String], redirect: Boolean, args: String*)
   162     : (String, Int) = process_output(raw_execute(cwd, env, redirect, args: _*))
   163 
   164 
   165   /* unpack zip archive -- platform file-system */
   166 
   167   def unzip(url: URL, root: File)
   168   {
   169     import scala.collection.JavaConversions._
   170 
   171     val buffer = new Array[Byte](4096)
   172 
   173     val zip_stream = new ZipInputStream(new BufferedInputStream(url.openStream))
   174     var entry: ZipEntry = null
   175     try {
   176       while ({ entry = zip_stream.getNextEntry; entry != null }) {
   177         val file = new File(root, entry.getName.replace('/', File.separatorChar))
   178         val dir = file.getParentFile
   179         if (dir != null && !dir.isDirectory && !dir.mkdirs)
   180           error("Failed to create directory: " + dir)
   181 
   182         var len = 0
   183         val out_stream = new BufferedOutputStream(new FileOutputStream(file))
   184         try {
   185           while ({ len = zip_stream.read(buffer); len != -1 })
   186             out_stream.write(buffer, 0, len)
   187         }
   188         finally { out_stream.close }
   189       }
   190     }
   191     finally { zip_stream.close }
   192   }
   193 
   194 
   195   /* unpack tar archive -- POSIX file-system */
   196 
   197   def posix_untar(url: URL, root: File, gunzip: Boolean = false,
   198     tar: String = "tar", gzip: String = "", progress: Int => Unit = _ => ()): String =
   199   {
   200     if (!root.isDirectory && !root.mkdirs)
   201       error("Failed to create root directory: " + root)
   202 
   203     val connection = url.openConnection
   204 
   205     val length = connection.getContentLength.toLong
   206     require(length >= 0L)
   207 
   208     val stream = new BufferedInputStream(connection.getInputStream)
   209     val progress_stream = new InputStream {
   210       private val total = length max 1L
   211       private var index = 0L
   212       private var percentage = 0L
   213       override def read(): Int =
   214       {
   215         val c = stream.read
   216         if (c != -1) {
   217           index += 100
   218           val p = index / total
   219           if (percentage != p) { percentage = p; progress(percentage.toInt) }
   220         }
   221         c
   222       }
   223       override def available(): Int = stream.available
   224       override def close() { stream.close }
   225     }
   226 
   227     val cmdline =
   228       List(tar, "-o", "-x", "-f-") :::
   229         (if (!gunzip) Nil else if (gzip == "") List("-z") else List("-I", gzip))
   230 
   231     val proc = raw_execute(root, null, false, cmdline:_*)
   232     val stdout = Simple_Thread.future("tar_stdout") { slurp(proc.getInputStream) }
   233     val stderr = Simple_Thread.future("tar_stderr") { slurp(proc.getErrorStream) }
   234     val stdin = new BufferedOutputStream(proc.getOutputStream)
   235 
   236     try {
   237       var c = -1
   238       val io_err =
   239         try { while ({ c = progress_stream.read; c != -1 }) stdin.write(c); false }
   240         catch { case e: IOException => true }
   241       stdin.close
   242 
   243       val rc = try { proc.waitFor } finally { Thread.interrupted }
   244       if (io_err || rc != 0) error(stderr.join.trim) else stdout.join
   245     }
   246     finally {
   247       progress_stream.close
   248       stdin.close
   249       proc.destroy
   250     }
   251   }
   252 }
   253 
   254 
   255 class Standard_System
   256 {
   257   val platform_root = if (Platform.is_windows) Cygwin.check_root() else "/"
   258   override def toString = platform_root
   259 
   260 
   261   /* jvm_path */
   262 
   263   private val Cygdrive = new Regex("/cygdrive/([a-zA-Z])($|/.*)")
   264   private val Named_Root = new Regex("//+([^/]*)(.*)")
   265 
   266   def jvm_path(posix_path: String): String =
   267     if (Platform.is_windows) {
   268       val result_path = new StringBuilder
   269       val rest =
   270         posix_path match {
   271           case Cygdrive(drive, rest) =>
   272             result_path ++= (drive + ":" + File.separator)
   273             rest
   274           case Named_Root(root, rest) =>
   275             result_path ++= File.separator
   276             result_path ++= File.separator
   277             result_path ++= root
   278             rest
   279           case path if path.startsWith("/") =>
   280             result_path ++= platform_root
   281             path
   282           case path => path
   283         }
   284       for (p <- rest.split("/") if p != "") {
   285         val len = result_path.length
   286         if (len > 0 && result_path(len - 1) != File.separatorChar)
   287           result_path += File.separatorChar
   288         result_path ++= p
   289       }
   290       result_path.toString
   291     }
   292     else posix_path
   293 
   294 
   295   /* posix_path */
   296 
   297   private val Platform_Root = new Regex("(?i)" +
   298     Pattern.quote(platform_root) + """(?:\\+|\z)(.*)""")
   299 
   300   private val Drive = new Regex("""([a-zA-Z]):\\*(.*)""")
   301 
   302   def posix_path(jvm_path: String): String =
   303     if (Platform.is_windows) {
   304       jvm_path.replace('/', '\\') match {
   305         case Platform_Root(rest) => "/" + rest.replace('\\', '/')
   306         case Drive(letter, rest) =>
   307           "/cygdrive/" + letter.toLowerCase(Locale.ENGLISH) +
   308             (if (rest == "") "" else "/" + rest.replace('\\', '/'))
   309         case path => path.replace('\\', '/')
   310       }
   311     }
   312     else jvm_path
   313 
   314 
   315   /* this_java executable */
   316 
   317   def this_java(): String =
   318   {
   319     val java_home = System.getProperty("java.home")
   320     val java_exe =
   321       if (Platform.is_windows) new File(java_home + "\\bin\\java.exe")
   322       else new File(java_home + "/bin/java")
   323     if (!java_exe.isFile) error("Expected this Java executable: " + java_exe.toString)
   324     posix_path(java_exe.getAbsolutePath)
   325   }
   326 }