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