1 /* Title: Pure/System/standard_system.scala
4 Standard system operations, with basic Cygwin/Posix compatibility.
9 import java.util.regex.Pattern
10 import java.util.Locale
12 import java.io.{BufferedWriter, OutputStreamWriter, FileOutputStream, BufferedOutputStream,
13 BufferedInputStream, InputStream, FileInputStream, BufferedReader, InputStreamReader,
14 File, FileFilter, IOException}
16 import scala.io.{Source, Codec}
17 import scala.util.matching.Regex
18 import scala.collection.mutable
21 object Standard_System
26 def codec(): Codec = Codec(charset)
28 def string_bytes(s: String): Array[Byte] = s.getBytes(charset)
31 /* permissive UTF-8 decoding */
33 // see also http://en.wikipedia.org/wiki/UTF-8#Description
34 // overlong encodings enable byte-stuffing
36 def decode_permissive_utf8(text: CharSequence): String =
38 val buf = new java.lang.StringBuilder(text.length)
44 if (rest == 0 && Character.isValidCodePoint(code))
45 buf.appendCodePoint(code)
46 else buf.append('\uFFFD')
51 def init(x: Int, n: Int)
59 if (rest <= 0) init(x, -1)
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)
79 /* basic file operations */
81 def slurp(reader: BufferedReader): String =
83 val output = new StringBuilder(100)
85 while ({ c = reader.read; c != -1 }) output += c.toChar
90 def slurp(stream: InputStream): String =
91 slurp(new BufferedReader(new InputStreamReader(stream, charset)))
93 def read_file(file: File): String = slurp(new FileInputStream(file))
95 def write_file(file: File, text: CharSequence)
97 val writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset))
98 try { writer.append(text) }
99 finally { writer.close }
102 def with_tmp_file[A](prefix: String)(body: File => A): A =
104 val file = File.createTempFile(prefix, null)
106 try { body(file) } finally { file.delete }
109 // FIXME handle (potentially cyclic) directory graph
110 def find_files(start: File, ok: File => Boolean): List[File] =
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)
116 if (ok(entry)) files += entry
117 if (entry.isDirectory) entry.listFiles(filter).foreach(find_entry)
124 /* shell processes */
126 def raw_execute(cwd: File, env: Map[String, String], redirect: Boolean, args: String*): Process =
128 val cmdline = new java.util.LinkedList[String]
129 for (s <- args) cmdline.add(s)
131 val proc = new ProcessBuilder(cmdline)
132 if (cwd != null) proc.directory(cwd)
134 proc.environment.clear
135 for ((x, y) <- env) proc.environment.put(x, y)
137 proc.redirectErrorStream(redirect)
141 def process_output(proc: Process): (String, Int) =
143 proc.getOutputStream.close
144 val output = slurp(proc.getInputStream)
148 proc.getInputStream.close
149 proc.getErrorStream.close
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: _*))
160 /* unpack tar archive */
162 def posix_untar(url: URL, root: File, gunzip: Boolean = false,
163 tar: String = "tar", gzip: String = "", progress: Int => Unit = _ => ()): String =
165 if (!root.isDirectory && !root.mkdirs)
166 error("Failed to create root directory: " + root)
168 val connection = url.openConnection
170 val length = connection.getContentLength.toLong
171 require(length >= 0L)
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 =
183 val p = index / total
184 if (percentage != p) { percentage = p; progress(percentage.toInt) }
188 override def available(): Int = stream.available
189 override def close() { stream.close }
193 List(tar, "-o", "-x", "-f-") :::
194 (if (!gunzip) Nil else if (gzip == "") List("-z") else List("-I", gzip))
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)
204 try { while ({ c = progress_stream.read; c != -1 }) stdin.write(c); false }
205 catch { case e: IOException => true }
208 val rc = try { proc.waitFor } finally { Thread.interrupted }
209 if (io_err || rc != 0) error(stderr.join.trim) else stdout.join
212 progress_stream.close
220 class Standard_System
222 val platform_root = if (Platform.is_windows) Cygwin.check_root() else "/"
223 override def toString = platform_root
228 private val Cygdrive = new Regex("/cygdrive/([a-zA-Z])($|/.*)")
229 private val Named_Root = new Regex("//+([^/]*)(.*)")
231 def jvm_path(posix_path: String): String =
232 if (Platform.is_windows) {
233 val result_path = new StringBuilder
236 case Cygdrive(drive, rest) =>
237 result_path ++= (drive + ":" + File.separator)
239 case Named_Root(root, rest) =>
240 result_path ++= File.separator
241 result_path ++= File.separator
244 case path if path.startsWith("/") =>
245 result_path ++= platform_root
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
262 private val Platform_Root = new Regex("(?i)" +
263 Pattern.quote(platform_root) + """(?:\\+|\z)(.*)""")
265 private val Drive = new Regex("""([a-zA-Z]):\\*(.*)""")
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('\\', '/')
280 /* this_java executable */
282 def this_java(): String =
284 val java_home = System.getProperty("java.home")
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)