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