forked from scala-native/scala-native
/
File.scala
577 lines (486 loc) · 16.6 KB
/
File.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
package java.io
import java.nio.file.{FileSystems, Path}
import java.net.URI
import scala.annotation.tailrec
import scalanative.annotation.stub
import scalanative.posix.{fcntl, limits, unistd, utime}
import scalanative.posix.sys.stat
import scalanative.unsigned._
import scalanative.unsafe._
import scalanative.libc._, stdlib._, stdio._, string._
import scalanative.nio.fs.FileHelpers
import scalanative.runtime.{DeleteOnExit, Platform}
import unistd._
class File(_path: String) extends Serializable with Comparable[File] {
import File._
if (_path == null) throw new NullPointerException()
private val path: String = fixSlashes(_path)
private[io] val properPath: String = File.properPath(path)
private[io] val properPathBytes: Array[Byte] =
File.properPath(path).getBytes("UTF-8")
def this(parent: String, child: String) =
this(
Option(parent).map(p => p + File.separatorChar + child).getOrElse(child))
def this(parent: File, child: String) =
this(Option(parent).map(_.path).orNull, child)
def this(uri: URI) = {
this(uri.getPath())
checkURI(uri)
}
def compareTo(file: File): Int = {
if (caseSensitive) getPath().compareTo(file.getPath())
else getPath().compareToIgnoreCase(file.getPath())
}
def canExecute(): Boolean =
Zone { implicit z => access(toCString(path), unistd.X_OK) == 0 }
def canRead(): Boolean =
Zone { implicit z => access(toCString(path), unistd.R_OK) == 0 }
def canWrite(): Boolean =
Zone { implicit z => access(toCString(path), unistd.W_OK) == 0 }
def setExecutable(executable: Boolean): Boolean =
setExecutable(executable, ownerOnly = true)
def setExecutable(executable: Boolean, ownerOnly: Boolean): Boolean = {
import stat._
val mask = if (!ownerOnly) S_IXUSR | S_IXGRP | S_IXOTH else S_IXUSR
updatePermissions(mask, executable)
}
def setReadable(readable: Boolean): Boolean =
setReadable(readable, ownerOnly = true)
def setReadable(readable: Boolean, ownerOnly: Boolean): Boolean = {
import stat._
val mask = if (!ownerOnly) S_IRUSR | S_IRGRP | S_IROTH else S_IRUSR
updatePermissions(mask, readable)
}
def setWritable(writable: Boolean): Boolean =
setWritable(writable, ownerOnly = true)
def setWritable(writable: Boolean, ownerOnly: Boolean = true): Boolean = {
import stat._
val mask = if (!ownerOnly) S_IWUSR | S_IWGRP | S_IWOTH else S_IWUSR
updatePermissions(mask, writable)
}
private def updatePermissions(mask: stat.mode_t, grant: Boolean): Boolean =
Zone { implicit z =>
if (grant) {
stat.chmod(toCString(path), accessMode() | mask) == 0
} else {
stat.chmod(toCString(path), accessMode() & (~mask)) == 0
}
}
def exists(): Boolean =
Zone { implicit z => access(toCString(path), unistd.F_OK) == 0 }
def toPath(): Path =
FileSystems.getDefault().getPath(this.getPath(), Array.empty)
def getPath(): String = path
def delete(): Boolean =
if (path.nonEmpty && isDirectory()) {
deleteDirImpl()
} else {
deleteFileImpl()
}
private def deleteDirImpl(): Boolean =
Zone { implicit z => remove(toCString(path)) == 0 }
private def deleteFileImpl(): Boolean =
Zone { implicit z => unlink(toCString(path)) == 0 }
override def equals(that: Any): Boolean =
that match {
case that: File if caseSensitive =>
this.path == that.path
case that: File =>
this.path.toLowerCase == that.path.toLowerCase
case _ =>
false
}
def getAbsolutePath(): String = properPath
def getAbsoluteFile(): File = new File(this.getAbsolutePath())
def getCanonicalPath(): String =
Zone { implicit z =>
if (exists()) {
fromCString(simplifyExistingPath(toCString(properPath)))
} else {
simplifyNonExistingPath(fromCString(resolve(toCString(properPath))))
}
}
/**
* Finds the canonical path for `path`, using `realpath`.
* The file must exist, because the result of `realpath` doesn't
* match that of Java on non-existing file.
*/
private def simplifyExistingPath(path: CString)(implicit z: Zone): CString = {
val resolvedName = alloc[Byte](limits.PATH_MAX)
realpath(path, resolvedName)
resolvedName
}
/**
* Finds the canonical path for `path`.
*/
private def simplifyNonExistingPath(path: String): String =
path
.split(separatorChar)
.foldLeft(List.empty[String]) {
case (acc, "..") => if (acc.isEmpty) List("..") else acc.tail
case (acc, ".") => acc
case (acc, "") => acc
case (acc, seg) => seg :: acc
}
.reverse
.filterNot(_.isEmpty())
.mkString(separator, separator, "")
@throws(classOf[IOException])
def getCanonicalFile(): File = new File(getCanonicalPath())
def getName(): String = {
val separatorIndex: Int = path.lastIndexOf(separatorChar)
if (separatorIndex < 0) path
else path.substring(separatorIndex + 1, path.length())
}
def getParent(): String =
path.split(separatorChar).filterNot(_.isEmpty()) match {
case Array() if !isAbsolute() => null
case Array(_) if !isAbsolute() => null
case parts if !isAbsolute() => parts.init.mkString(separator)
case parts if isAbsolute() =>
parts.init.mkString(separator, separator, "")
}
def getParentFile(): File = {
val parent = getParent()
if (parent == null) null
else new File(parent)
}
override def hashCode(): Int =
if (caseSensitive) path.hashCode ^ 1234321
else path.toLowerCase.hashCode ^ 1234321
def isAbsolute(): Boolean =
File.isAbsolute(path)
def isDirectory(): Boolean =
Zone { implicit z => stat.S_ISDIR(accessMode()) != 0 }
def isFile(): Boolean =
Zone { implicit z => stat.S_ISREG(accessMode()) != 0 }
def isHidden(): Boolean =
getName().startsWith(".")
def lastModified(): Long =
Zone { implicit z =>
val buf = alloc[stat.stat]
if (stat.stat(toCString(path), buf) == 0) {
buf._8 * 1000L
} else {
0L
}
}
private def accessMode()(implicit z: Zone): stat.mode_t = {
val buf = alloc[stat.stat]
if (stat.stat(toCString(path), buf) == 0) {
buf._13
} else {
0.toUInt
}
}
def setLastModified(time: Long): Boolean =
if (time < 0) {
throw new IllegalArgumentException("Negative time")
} else
Zone { implicit z =>
val statbuf = alloc[stat.stat]
if (stat.stat(toCString(path), statbuf) == 0) {
val timebuf = alloc[utime.utimbuf]
timebuf._1 = statbuf._8
timebuf._2 = time / 1000L
utime.utime(toCString(path), timebuf) == 0
} else {
false
}
}
def setReadOnly(): Boolean =
Zone { implicit z =>
import stat._
val mask =
S_ISUID | S_ISGID | S_ISVTX | S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
val newMode = accessMode() & mask
chmod(toCString(path), newMode) == 0
}
def length(): Long =
Zone { implicit z =>
val buf = alloc[stat.stat]
if (stat.stat(toCString(path), buf) == 0) {
buf._6
} else {
0L
}
}
def list(): Array[String] =
list(FilenameFilter.allPassFilter)
def list(filter: FilenameFilter): Array[String] =
if (!isDirectory() || !canRead()) {
null
} else
Zone { implicit z =>
val elements =
FileHelpers.list(properPath, (n, _) => n, allowEmpty = true)
if (elements == null)
Array.empty[String]
else
elements.filter(filter.accept(this, _))
}
def listFiles(): Array[File] =
listFiles(FilenameFilter.allPassFilter)
def listFiles(filter: FilenameFilter): Array[File] =
list(filter).map(new File(this, _))
def listFiles(filter: FileFilter): Array[File] = {
val filenameFilter =
new FilenameFilter {
override def accept(dir: File, name: String): Boolean =
filter.accept(new File(dir, name))
}
listFiles(filenameFilter)
}
def mkdir(): Boolean =
Zone { implicit z =>
val mode = octal("0777")
stat.mkdir(toCString(path), mode) == 0
}
def mkdirs(): Boolean =
if (exists()) {
false
} else if (mkdir()) {
true
} else {
val parent = getParentFile()
if (parent == null) {
false
} else {
parent.mkdirs() && mkdir()
}
}
def createNewFile(): Boolean =
FileHelpers.createNewFile(path, throwOnError = true)
def renameTo(dest: File): Boolean =
Zone { implicit z =>
rename(toCString(properPath), toCString(dest.properPath)) == 0
}
override def toString(): String = path
def deleteOnExit(): Unit = DeleteOnExit.addFile(this.getAbsolutePath())
@stub
def toURL(): java.net.URL = ???
// Ported from Apache Harmony
def toURI(): URI = {
val path = getAbsolutePath()
if (!path.startsWith("/")) {
// start with sep.
new URI(
"file",
null,
new StringBuilder(path.length + 1).append('/').append(path).toString,
null,
null)
} else if (path.startsWith("//")) {
// UNC path
new URI("file", "", path, null)
} else {
new URI("file", null, path, null, null)
}
}
}
object File {
private val random = new java.util.Random()
private def octal(v: String): UInt =
Integer.parseInt(v, 8).toUInt
private def getUserDir(): String =
Zone { implicit z =>
var buff: CString = alloc[CChar](4096)
var res: CString = getcwd(buff, 4095)
fromCString(res)
}
/** The purpose of this method is to take a path and fix the slashes up. This
* includes changing them all to the current platforms fileSeparator and
* removing duplicates.
*/
// Ported from Apache Harmony
private def fixSlashes(path: String): String = {
val length = path.length
var newLength = 0
var uncIndex =
if (separatorChar == '/') 0 // UNIX world
else if (length > 2 && path.charAt(1) == ':')
2 // Windows, but starts with C:...
else 1 // Possible UNC path name
var foundSlash = false
val newPath = path.toCharArray()
var i = 0
while (i < length) {
val currentChar = newPath(i)
if ((separatorChar == '\\' && currentChar == '\\') || currentChar == '/') {
// UNC Name requires 2 leading slashes
if ((foundSlash && i == uncIndex) || !foundSlash) {
newPath(newLength) = separatorChar
newLength += 1
foundSlash = true
}
} else {
// check for leading slashes before a drive
if (currentChar == ':'
&& uncIndex > 0
&& (newLength == 2 || (newLength == 3 && newPath(1) == separatorChar))
&& newPath(0) == separatorChar) {
newPath(0) = newPath(newLength - 1)
newLength = 1
// allow trailing slash after drive letter
uncIndex = 2
}
newPath(newLength) = currentChar
newLength += 1
foundSlash = false
}
i += 1
}
if (foundSlash && (newLength > (uncIndex + 1) || (newLength == 2 && newPath(
0) != separatorChar))) {
newLength -= 1
}
new String(newPath, 0, newLength)
}
/**
* Returns a string representing the proper path of this file. If this file
* path is absolute, the user.dir property is not prepended, otherwise it
* is.
*/
// Ported from Apache Harmony
private def properPath(path: String): String = {
if (isAbsolute(path)) path
else {
val userdir =
Option(getUserDir())
.getOrElse(
throw new IOException(
"getcwd() error in trying to get user directory."))
if (path.isEmpty()) userdir
else if (userdir.endsWith(separator)) userdir + path
else userdir + separator + path
}
}
def isAbsolute(path: String): Boolean =
if (separatorChar == '\\') { // Windows. Must start with `\\` or `X:(\|/)`
(path.length > 1 && path.startsWith(separator + separator)) ||
(path.length > 2 && path(0).isLetter && path(1) == ':' && (path(2) == '/' || path(
2) == '\\'))
} else {
path.length > 0 && path.startsWith(separator)
}
/**
* Resolve a symbolic link. While the path resolves to an existing path,
* keep resolving. If an absolute link is found, resolve the parent
* directories if resolveAbsolute is true.
*/
// Ported from Apache Harmony
private def resolveLink(
path: CString,
resolveAbsolute: Boolean,
restart: Boolean = false)(implicit z: Zone): CString = {
val resolved =
readLink(path) match {
// path is not a symlink
case null =>
path
// found an absolute path. continue from there.
case link if link(0) == separatorChar =>
resolveLink(link, resolveAbsolute, restart = resolveAbsolute)
// found a relative path. append to the current path, and continue.
case link =>
val linkLength = strlen(link)
val pathLength = strlen(path)
var last = pathLength - 1
while (path(last) != separatorChar) last -= 1
last += 1
// previous path up to last /, plus result of resolving the link.
val newPathLength = last + linkLength + 1
val newPath = alloc[Byte](newPathLength)
strncpy(newPath, path, last)
strncat(newPath, link, linkLength)
resolveLink(newPath, resolveAbsolute, restart)
}
if (restart) resolve(resolved, start = 0)
else resolved
}
@tailrec private def resolve(path: CString, start: Int = 0)(
implicit z: Zone): CString = {
val part: CString = alloc[Byte](limits.PATH_MAX)
// Find the next separator
var i = start
while (i < strlen(path) && path(i) != separatorChar) i += 1
if (i == strlen(path)) resolveLink(path, resolveAbsolute = true)
else {
// copy path from start to next separator.
// and resolve that subpart.
strncpy(part, path, i + 1)
val resolved = resolveLink(part, resolveAbsolute = true)
strcpy(part, resolved)
strcat(part, path + i + 1)
if (strncmp(resolved, path, i + 1) == 0) {
// Nothing changed. Continue from the next segment.
resolve(part, i + 1)
} else {
// The path has changed. Start over.
resolve(part, 0)
}
}
}
/**
* If `link` is a symlink, follows it and returns the path pointed to.
* Otherwise, returns `None`.
*/
private def readLink(link: CString)(implicit z: Zone): CString = {
val buffer: CString = alloc[Byte](limits.PATH_MAX)
readlink(link, buffer, limits.PATH_MAX - 1) match {
case -1 =>
null
case read =>
// readlink doesn't null-terminate the result.
buffer(read) = 0
buffer
}
}
val pathSeparatorChar: Char = if (Platform.isWindows()) ';' else ':'
val pathSeparator: String = pathSeparatorChar.toString
val separatorChar: Char = if (Platform.isWindows()) '\\' else '/'
val separator: String = separatorChar.toString
private var counter: Int = 0
private var counterBase: Int = 0
private val caseSensitive: Boolean = !Platform.isWindows()
def listRoots(): Array[File] =
if (Platform.isWindows()) ???
else {
var array = new Array[File](1)
array(0) = new File("/")
return array
}
@throws(classOf[IOException])
def createTempFile(prefix: String, suffix: String): File =
createTempFile(prefix, suffix, null)
@throws(classOf[IOException])
def createTempFile(prefix: String, suffix: String, directory: File): File =
FileHelpers.createTempFile(prefix,
suffix,
directory,
minLength = true,
throwOnError = true)
// Ported from Apache Harmony
private def checkURI(uri: URI): Unit = {
def throwExc(msg: String): Unit =
throw new IllegalArgumentException(s"$msg: $uri")
def compMsg(comp: String): String =
s"Found $comp component in URI"
if (!uri.isAbsolute()) {
throwExc("URI is not absolute")
} else if (!uri.getRawSchemeSpecificPart().startsWith("/")) {
throwExc("URI is not hierarchical")
} else if (uri.getScheme() == null || !(uri.getScheme() == "file")) {
throwExc("Expected file scheme in URI")
} else if (uri.getRawPath() == null || uri.getRawPath().length() == 0) {
throwExc("Expected non-empty path in URI")
} else if (uri.getRawAuthority() != null) {
throwExc(compMsg("authority"))
} else if (uri.getRawQuery() != null) {
throwExc(compMsg("query"))
} else if (uri.getRawFragment() != null) {
throwExc(compMsg("fragment"))
}
// else URI is ok
}
}