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