src/Pure/System/standard_system.scala
author wenzelm
Tue Jul 05 10:54:05 2011 +0200 (2011-07-05)
changeset 43664 47af50b0c8c5
parent 43661 39fdbd814c7f
child 43670 7f933761764b
permissions -rw-r--r--
tuned;
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@34201
    82
wenzelm@34201
    83
  /* basic file operations */
wenzelm@34201
    84
wenzelm@39578
    85
  def slurp(reader: BufferedReader): String =
wenzelm@34201
    86
  {
wenzelm@39578
    87
    val output = new StringBuilder(100)
wenzelm@39578
    88
    var c = -1
wenzelm@39578
    89
    while ({ c = reader.read; c != -1 }) output += c.toChar
wenzelm@39578
    90
    reader.close
wenzelm@39578
    91
    output.toString
wenzelm@34201
    92
  }
wenzelm@34201
    93
wenzelm@39578
    94
  def slurp(stream: InputStream): String =
wenzelm@39578
    95
    slurp(new BufferedReader(new InputStreamReader(stream, charset)))
wenzelm@39578
    96
wenzelm@39578
    97
  def read_file(file: File): String = slurp(new FileInputStream(file))
wenzelm@34201
    98
wenzelm@43661
    99
  def try_read(files: Seq[File]): String =
wenzelm@43661
   100
  {
wenzelm@43661
   101
    val buf = new StringBuilder
wenzelm@43661
   102
    for {
wenzelm@43661
   103
      file <- files if file.isFile
wenzelm@43661
   104
      c <- (Source.fromFile(file) ++ Iterator.single('\n'))
wenzelm@43661
   105
    } buf.append(c)
wenzelm@43661
   106
    buf.toString
wenzelm@43661
   107
  }
wenzelm@43661
   108
wenzelm@34201
   109
  def write_file(file: File, text: CharSequence)
wenzelm@34201
   110
  {
wenzelm@43516
   111
    val writer =
wenzelm@43516
   112
      new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset))
wenzelm@34201
   113
    try { writer.append(text) }
wenzelm@34201
   114
    finally { writer.close }
wenzelm@34201
   115
  }
wenzelm@34201
   116
wenzelm@39578
   117
  def with_tmp_file[A](prefix: String)(body: File => A): A =
wenzelm@39578
   118
  {
wenzelm@39578
   119
    val file = File.createTempFile(prefix, null)
wenzelm@39582
   120
    file.deleteOnExit
wenzelm@39578
   121
    try { body(file) } finally { file.delete }
wenzelm@39578
   122
  }
wenzelm@39578
   123
wenzelm@34300
   124
  // FIXME handle (potentially cyclic) directory graph
wenzelm@34298
   125
  def find_files(start: File, ok: File => Boolean): List[File] =
wenzelm@34298
   126
  {
wenzelm@34298
   127
    val files = new mutable.ListBuffer[File]
wenzelm@34298
   128
    val filter = new FileFilter { def accept(entry: File) = entry.isDirectory || ok(entry) }
wenzelm@34298
   129
    def find_entry(entry: File)
wenzelm@34298
   130
    {
wenzelm@34298
   131
      if (ok(entry)) files += entry
wenzelm@34298
   132
      if (entry.isDirectory) entry.listFiles(filter).foreach(find_entry)
wenzelm@34298
   133
    }
wenzelm@34298
   134
    find_entry(start)
wenzelm@34298
   135
    files.toList
wenzelm@34298
   136
  }
wenzelm@34298
   137
wenzelm@34201
   138
wenzelm@34201
   139
  /* shell processes */
wenzelm@34201
   140
wenzelm@34219
   141
  def raw_execute(cwd: File, env: Map[String, String], redirect: Boolean, args: String*): Process =
wenzelm@34201
   142
  {
wenzelm@34201
   143
    val cmdline = new java.util.LinkedList[String]
wenzelm@34201
   144
    for (s <- args) cmdline.add(s)
wenzelm@34201
   145
wenzelm@34201
   146
    val proc = new ProcessBuilder(cmdline)
wenzelm@34219
   147
    if (cwd != null) proc.directory(cwd)
wenzelm@34202
   148
    if (env != null) {
wenzelm@34202
   149
      proc.environment.clear
wenzelm@34202
   150
      for ((x, y) <- env) proc.environment.put(x, y)
wenzelm@34202
   151
    }
wenzelm@34201
   152
    proc.redirectErrorStream(redirect)
wenzelm@39522
   153
    proc.start
wenzelm@34201
   154
  }
wenzelm@34201
   155
wenzelm@34201
   156
  def process_output(proc: Process): (String, Int) =
wenzelm@34201
   157
  {
wenzelm@34201
   158
    proc.getOutputStream.close
wenzelm@39578
   159
    val output = slurp(proc.getInputStream)
wenzelm@34201
   160
    val rc =
wenzelm@34201
   161
      try { proc.waitFor }
wenzelm@34201
   162
      finally {
wenzelm@34201
   163
        proc.getInputStream.close
wenzelm@34201
   164
        proc.getErrorStream.close
wenzelm@34201
   165
        proc.destroy
wenzelm@34201
   166
        Thread.interrupted
wenzelm@34201
   167
      }
wenzelm@34201
   168
    (output, rc)
wenzelm@34201
   169
  }
wenzelm@34258
   170
wenzelm@39522
   171
  def raw_exec(cwd: File, env: Map[String, String], redirect: Boolean, args: String*)
wenzelm@39522
   172
    : (String, Int) = process_output(raw_execute(cwd, env, redirect, args: _*))
wenzelm@39705
   173
wenzelm@39705
   174
wenzelm@39732
   175
  /* unpack zip archive -- platform file-system */
wenzelm@39732
   176
wenzelm@39732
   177
  def unzip(url: URL, root: File)
wenzelm@39732
   178
  {
wenzelm@39732
   179
    import scala.collection.JavaConversions._
wenzelm@39732
   180
wenzelm@39732
   181
    val buffer = new Array[Byte](4096)
wenzelm@39732
   182
wenzelm@39732
   183
    val zip_stream = new ZipInputStream(new BufferedInputStream(url.openStream))
wenzelm@39732
   184
    var entry: ZipEntry = null
wenzelm@39732
   185
    try {
wenzelm@39732
   186
      while ({ entry = zip_stream.getNextEntry; entry != null }) {
wenzelm@39732
   187
        val file = new File(root, entry.getName.replace('/', File.separatorChar))
wenzelm@39732
   188
        val dir = file.getParentFile
wenzelm@39732
   189
        if (dir != null && !dir.isDirectory && !dir.mkdirs)
wenzelm@39732
   190
          error("Failed to create directory: " + dir)
wenzelm@39732
   191
wenzelm@39732
   192
        var len = 0
wenzelm@39732
   193
        val out_stream = new BufferedOutputStream(new FileOutputStream(file))
wenzelm@39732
   194
        try {
wenzelm@39732
   195
          while ({ len = zip_stream.read(buffer); len != -1 })
wenzelm@39732
   196
            out_stream.write(buffer, 0, len)
wenzelm@39732
   197
        }
wenzelm@39732
   198
        finally { out_stream.close }
wenzelm@39732
   199
      }
wenzelm@39732
   200
    }
wenzelm@39732
   201
    finally { zip_stream.close }
wenzelm@39732
   202
  }
wenzelm@39732
   203
wenzelm@39732
   204
wenzelm@39732
   205
  /* unpack tar archive -- POSIX file-system */
wenzelm@39705
   206
wenzelm@39708
   207
  def posix_untar(url: URL, root: File, gunzip: Boolean = false,
wenzelm@39709
   208
    tar: String = "tar", gzip: String = "", progress: Int => Unit = _ => ()): String =
wenzelm@39705
   209
  {
wenzelm@39708
   210
    if (!root.isDirectory && !root.mkdirs)
wenzelm@39708
   211
      error("Failed to create root directory: " + root)
wenzelm@39705
   212
wenzelm@39705
   213
    val connection = url.openConnection
wenzelm@39705
   214
wenzelm@39705
   215
    val length = connection.getContentLength.toLong
wenzelm@39705
   216
    require(length >= 0L)
wenzelm@39705
   217
wenzelm@39708
   218
    val stream = new BufferedInputStream(connection.getInputStream)
wenzelm@39705
   219
    val progress_stream = new InputStream {
wenzelm@39705
   220
      private val total = length max 1L
wenzelm@39705
   221
      private var index = 0L
wenzelm@39705
   222
      private var percentage = 0L
wenzelm@39705
   223
      override def read(): Int =
wenzelm@39705
   224
      {
wenzelm@39708
   225
        val c = stream.read
wenzelm@39705
   226
        if (c != -1) {
wenzelm@39705
   227
          index += 100
wenzelm@39705
   228
          val p = index / total
wenzelm@39705
   229
          if (percentage != p) { percentage = p; progress(percentage.toInt) }
wenzelm@39705
   230
        }
wenzelm@39705
   231
        c
wenzelm@39705
   232
      }
wenzelm@39708
   233
      override def available(): Int = stream.available
wenzelm@39708
   234
      override def close() { stream.close }
wenzelm@39705
   235
    }
wenzelm@39705
   236
wenzelm@39709
   237
    val cmdline =
wenzelm@39709
   238
      List(tar, "-o", "-x", "-f-") :::
wenzelm@39709
   239
        (if (!gunzip) Nil else if (gzip == "") List("-z") else List("-I", gzip))
wenzelm@39709
   240
wenzelm@39709
   241
    val proc = raw_execute(root, null, false, cmdline:_*)
wenzelm@39705
   242
    val stdout = Simple_Thread.future("tar_stdout") { slurp(proc.getInputStream) }
wenzelm@39705
   243
    val stderr = Simple_Thread.future("tar_stderr") { slurp(proc.getErrorStream) }
wenzelm@39705
   244
    val stdin = new BufferedOutputStream(proc.getOutputStream)
wenzelm@39705
   245
wenzelm@39705
   246
    try {
wenzelm@39705
   247
      var c = -1
wenzelm@39706
   248
      val io_err =
wenzelm@39708
   249
        try { while ({ c = progress_stream.read; c != -1 }) stdin.write(c); false }
wenzelm@39706
   250
        catch { case e: IOException => true }
wenzelm@39705
   251
      stdin.close
wenzelm@39705
   252
wenzelm@39705
   253
      val rc = try { proc.waitFor } finally { Thread.interrupted }
wenzelm@39706
   254
      if (io_err || rc != 0) error(stderr.join.trim) else stdout.join
wenzelm@39705
   255
    }
wenzelm@39705
   256
    finally {
wenzelm@39708
   257
      progress_stream.close
wenzelm@39705
   258
      stdin.close
wenzelm@39705
   259
      proc.destroy
wenzelm@39705
   260
    }
wenzelm@39705
   261
  }
wenzelm@34201
   262
}
wenzelm@34201
   263
wenzelm@34201
   264
wenzelm@34201
   265
class Standard_System
wenzelm@34201
   266
{
wenzelm@43664
   267
  /* platform_root */
wenzelm@43664
   268
wenzelm@34201
   269
  val platform_root = if (Platform.is_windows) Cygwin.check_root() else "/"
wenzelm@34201
   270
wenzelm@34201
   271
wenzelm@34201
   272
  /* jvm_path */
wenzelm@34201
   273
wenzelm@34201
   274
  private val Cygdrive = new Regex("/cygdrive/([a-zA-Z])($|/.*)")
wenzelm@36136
   275
  private val Named_Root = new Regex("//+([^/]*)(.*)")
wenzelm@34201
   276
wenzelm@34201
   277
  def jvm_path(posix_path: String): String =
wenzelm@34201
   278
    if (Platform.is_windows) {
wenzelm@34201
   279
      val result_path = new StringBuilder
wenzelm@34201
   280
      val rest =
wenzelm@34201
   281
        posix_path match {
wenzelm@34201
   282
          case Cygdrive(drive, rest) =>
wenzelm@34201
   283
            result_path ++= (drive + ":" + File.separator)
wenzelm@34201
   284
            rest
wenzelm@36136
   285
          case Named_Root(root, rest) =>
wenzelm@36136
   286
            result_path ++= File.separator
wenzelm@36136
   287
            result_path ++= File.separator
wenzelm@36136
   288
            result_path ++= root
wenzelm@36136
   289
            rest
wenzelm@34201
   290
          case path if path.startsWith("/") =>
wenzelm@34201
   291
            result_path ++= platform_root
wenzelm@34201
   292
            path
wenzelm@34201
   293
          case path => path
wenzelm@34201
   294
        }
wenzelm@34201
   295
      for (p <- rest.split("/") if p != "") {
wenzelm@34201
   296
        val len = result_path.length
wenzelm@34201
   297
        if (len > 0 && result_path(len - 1) != File.separatorChar)
wenzelm@34201
   298
          result_path += File.separatorChar
wenzelm@34201
   299
        result_path ++= p
wenzelm@34201
   300
      }
wenzelm@34201
   301
      result_path.toString
wenzelm@34201
   302
    }
wenzelm@34201
   303
    else posix_path
wenzelm@34201
   304
wenzelm@34201
   305
wenzelm@34201
   306
  /* posix_path */
wenzelm@34201
   307
wenzelm@34201
   308
  private val Platform_Root = new Regex("(?i)" +
wenzelm@34201
   309
    Pattern.quote(platform_root) + """(?:\\+|\z)(.*)""")
wenzelm@34201
   310
wenzelm@34201
   311
  private val Drive = new Regex("""([a-zA-Z]):\\*(.*)""")
wenzelm@34201
   312
wenzelm@34201
   313
  def posix_path(jvm_path: String): String =
wenzelm@34201
   314
    if (Platform.is_windows) {
wenzelm@34201
   315
      jvm_path.replace('/', '\\') match {
wenzelm@34201
   316
        case Platform_Root(rest) => "/" + rest.replace('\\', '/')
wenzelm@34201
   317
        case Drive(letter, rest) =>
wenzelm@34201
   318
          "/cygdrive/" + letter.toLowerCase(Locale.ENGLISH) +
wenzelm@34201
   319
            (if (rest == "") "" else "/" + rest.replace('\\', '/'))
wenzelm@34201
   320
        case path => path.replace('\\', '/')
wenzelm@34201
   321
      }
wenzelm@34201
   322
    }
wenzelm@34201
   323
    else jvm_path
wenzelm@36193
   324
wenzelm@36193
   325
wenzelm@36193
   326
  /* this_java executable */
wenzelm@36193
   327
wenzelm@36193
   328
  def this_java(): String =
wenzelm@36193
   329
  {
wenzelm@36193
   330
    val java_home = System.getProperty("java.home")
wenzelm@36193
   331
    val java_exe =
wenzelm@36193
   332
      if (Platform.is_windows) new File(java_home + "\\bin\\java.exe")
wenzelm@36193
   333
      else new File(java_home + "/bin/java")
wenzelm@36193
   334
    if (!java_exe.isFile) error("Expected this Java executable: " + java_exe.toString)
wenzelm@36193
   335
    posix_path(java_exe.getAbsolutePath)
wenzelm@36193
   336
  }
wenzelm@34201
   337
}