-
Notifications
You must be signed in to change notification settings - Fork 943
/
File.swift
602 lines (540 loc) · 17.6 KB
/
File.swift
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//
// File.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/7/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
#if os(Linux)
import LinuxBridge
// !FIX! these are obviously sketchy
// I hope SwiftGlibc to eventually include these
// Otherwise, export them from LinuxBridge
import var Glibc.S_IRUSR
import var Glibc.S_IWUSR
import var Glibc.S_IXUSR
import var Glibc.S_IFMT
import var Glibc.S_IFREG
import var Glibc.S_IFDIR
import var Glibc.S_IFLNK
let S_IRGRP = (S_IRUSR >> 3)
let S_IWGRP = (S_IWUSR >> 3)
let S_IXGRP = (S_IXUSR >> 3)
let S_IRWXU = (__S_IREAD|__S_IWRITE|__S_IEXEC)
let S_IRWXG = (S_IRWXU >> 3)
let S_IRWXO = (S_IRWXG >> 3)
let S_IROTH = (S_IRGRP >> 3)
let S_IWOTH = (S_IWGRP >> 3)
let S_IXOTH = (S_IXGRP >> 3)
let SEEK_CUR: Int32 = 1
let EXDEV = Int32(18)
let EACCES = Int32(13)
let EAGAIN = Int32(11)
let F_OK: Int32 = 0
#else
import Darwin
#endif
let fileCopyBufferSize = 16384
/// Provides access to a file on the local file system
public class File {
/// The underlying file system descriptor.
public var fd = -1
var internalPath = ""
/// Checks that the file exists on the file system
/// - returns: True if the file exists or false otherwise
public var exists: Bool {
return access(internalPath, F_OK) != -1
}
/// Returns true if the file has been opened
public var isOpen: Bool {
return fd != -1
}
/// Returns the file's path
public var path: String { return internalPath }
/// Returns the file path. If the file is a symbolic link, the link will be resolved.
public var realPath: String {
let maxPath = 2048
guard isLink else {
return internalPath
}
var ary = [UInt8](repeating: 0, count: maxPath)
let res: Int = ary.withUnsafeMutableBytes {
guard let p = $0.bindMemory(to: Int8.self).baseAddress else {
return -1
}
return readlink(internalPath, p, maxPath)
}
guard res != -1 else {
return internalPath
}
let trailPath = String(cString: ary)
let lastChar = trailPath[trailPath.startIndex]
guard lastChar != "/" && lastChar != "." else {
return trailPath
}
return internalPath.deletingLastFilePathComponent + "/" + trailPath
}
/// Returns the modification date for the file in the standard UNIX format of seconds since 1970/01/01 00:00:00 GMT
/// - returns: The date as Int
public var modificationTime: Int {
var st = stat()
let res = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard res == 0 else {
return Int.max
}
#if os(Linux)
return Int(st.st_mtim.tv_sec)
#else
return Int(st.st_mtimespec.tv_sec)
#endif
}
static func resolveTilde(inPath: String) -> String {
#if !os(iOS) && !os(tvOS)
if !inPath.isEmpty && inPath[inPath.startIndex] == "~" {
var wexp = wordexp_t()
guard 0 == wordexp(inPath, &wexp, 0),
let we_wordv = wexp.we_wordv else {
return inPath
}
defer {
wordfree(&wexp)
}
if let resolved = we_wordv[0], let pth = String(validatingUTF8: resolved) {
return pth
}
}
#endif
return inPath
}
/// Create a file object given a path and open mode
/// - parameter path: Path to the file which will be accessed
/// - parameter fd: The file descriptor, if any, for an already opened file
public init(_ path: String, fd: Int32 = -1) {
internalPath = File.resolveTilde(inPath: path)
self.fd = Int(fd)
}
deinit {
close()
}
/// Closes the file if it had been opened
public func close() {
if fd != -1 {
#if os(Linux)
_ = SwiftGlibc.close(CInt(fd))
#else
_ = Darwin.close(CInt(fd))
#endif
fd = -1
}
}
/// Resets the internal file descriptor, leaving the file opened if it had been.
public func abandon() {
fd = -1
}
}
public extension File {
/// The open mode for the file.
enum OpenMode {
/// Opens the file for read-only access.
case read
/// Opens the file for write-only access, creating the file if it did not exist.
case write
/// Opens the file for read-write access, creating the file if it did not exist.
case readWrite
/// Opens the file for read-write access, creating the file if it did not exist and moving the file marker to the end.
case append
/// Opens the file for read-write access, creating the file if it did not exist and setting the file's size to zero.
case truncate
var toMode: Int {
switch self {
case .read: return Int(O_RDONLY)
case .write: return Int(O_WRONLY|O_CREAT)
case .readWrite: return Int(O_RDWR|O_CREAT)
case .append: return Int(O_RDWR|O_APPEND|O_CREAT)
case .truncate: return Int(O_RDWR|O_TRUNC|O_CREAT)
}
}
}
/// A file or directory access permission value.
struct PermissionMode: OptionSet {
/// File system mode type.
public typealias Mode = mode_t
/// The raw mode.
public let rawValue: Mode
/// Create a permission mode with a raw value.
public init(rawValue: Mode) {
self.rawValue = rawValue
}
#if os(Linux)
init(rawValue: Int32) {
self.init(rawValue: UInt32(rawValue))
}
#endif
/// Readable by user.
public static let readUser = PermissionMode(rawValue: S_IRUSR)
/// Writable by user.
public static let writeUser = PermissionMode(rawValue: S_IWUSR)
/// Executable by user.
public static let executeUser = PermissionMode(rawValue: S_IXUSR)
/// Readable by group.
public static let readGroup = PermissionMode(rawValue: S_IRGRP)
/// Writable by group.
public static let writeGroup = PermissionMode(rawValue: S_IWGRP)
/// Executable by group.
public static let executeGroup = PermissionMode(rawValue: S_IXGRP)
/// Readable by others.
public static let readOther = PermissionMode(rawValue: S_IROTH)
/// Writable by others.
public static let writeOther = PermissionMode(rawValue: S_IWOTH)
/// Executable by others.
public static let executeOther = PermissionMode(rawValue: S_IXOTH)
/// Read, write, execute by user.
public static let rwxUser: PermissionMode = [.readUser, .writeUser, .executeUser]
/// Read, write by user and group.
public static let rwUserGroup: PermissionMode = [.readUser, .writeUser, .readGroup, .writeGroup]
/// Read, execute by group.
public static let rxGroup: PermissionMode = [.readGroup, .executeGroup]
/// Read, execute by other.
public static let rxOther: PermissionMode = [.readOther, .executeOther]
}
/// Opens the file using the given mode.
/// - throws: `PerfectError.FileError`
func open(_ mode: OpenMode = .read, permissions: PermissionMode = .rwUserGroup) throws {
if fd != -1 {
close()
}
#if os(Linux)
let openFd = linux_open(internalPath, CInt(mode.toMode), permissions.rawValue)
#else
let openFd = Darwin.open(internalPath, CInt(mode.toMode), permissions.rawValue)
#endif
guard openFd != -1 else {
try ThrowFileError()
}
fd = Int(openFd)
}
}
public extension File {
/// The current file read/write position.
var marker: Int {
/// Returns the value of the file's current position marker
get {
if isOpen {
return Int(lseek(Int32(fd), 0, SEEK_CUR))
}
return 0
}
/// Sets the file's position marker given the value as measured from the begining of the file.
set {
lseek(Int32(fd), off_t(newValue), SEEK_SET)
}
}
}
public extension File {
/// Closes and deletes the file
func delete() {
close()
unlink(path)
}
/// Moves the file to the new location, optionally overwriting any existing file
/// - parameter path: The path to move the file to
/// - parameter overWrite: Indicates that any existing file at the destination path should first be deleted
/// - returns: Returns a new file object representing the new location
/// - throws: `PerfectError.FileError`
func moveTo(path: String, overWrite: Bool = false) throws -> File {
let destFile = File(path)
if destFile.exists {
guard overWrite else {
throw PerfectError.fileError(-1, "Can not overwrite existing file")
}
destFile.delete()
}
close()
let res = rename(self.path, path)
if res == 0 {
return destFile
}
if errno == EXDEV {
_ = try copyTo(path: path, overWrite: overWrite)
delete()
return destFile
}
try ThrowFileError()
}
/// Copies the file to the new location, optionally overwriting any existing file
/// - parameter path: The path to copy the file to
/// - parameter overWrite: Indicates that any existing file at the destination path should first be deleted
/// - returns: Returns a new file object representing the new location
/// - throws: `PerfectError.FileError`
@discardableResult
func copyTo(path pth: String, overWrite: Bool = false) throws -> File {
let destFile = File(pth)
if destFile.exists {
guard overWrite else {
throw PerfectError.fileError(-1, "Can not overwrite existing file")
}
destFile.delete()
}
let wasOpen = isOpen
let oldMarker = marker
if !wasOpen {
try open()
} else {
_ = marker = 0
}
defer {
if !wasOpen {
close()
} else {
_ = marker = oldMarker
}
}
try destFile.open(.truncate)
var bytes = try readSomeBytes(count: fileCopyBufferSize)
while bytes.count > 0 {
try destFile.write(bytes: bytes)
bytes = try readSomeBytes(count: fileCopyBufferSize)
}
destFile.close()
return destFile
}
}
public extension File {
/// Returns the size of the file in bytes
var size: Int {
var st = stat()
let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard statRes != -1 else {
return 0
}
return Int(st.st_size)
}
/// Returns true if the file is actually a directory
var isDir: Bool {
var st = stat()
let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard statRes != -1 else {
return false
}
let mode = st.st_mode
return (Int32(mode) & Int32(S_IFMT)) == Int32(S_IFDIR)
}
/// Returns the UNIX style permissions for the file
var perms: PermissionMode {
get {
var st = stat()
let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard statRes != -1 else {
return PermissionMode(rawValue: PermissionMode.Mode(0))
}
let mode = st.st_mode
return PermissionMode(rawValue: mode_t(Int32(mode) ^ Int32(S_IFMT)))
}
set {
_ = chmod(internalPath, newValue.rawValue)
}
}
}
public extension File {
/// Returns true if the file is a symbolic link
var isLink: Bool {
var st = stat()
let statRes = lstat(internalPath, &st)
guard statRes != -1 else {
return false
}
let mode = st.st_mode
return (Int32(mode) & Int32(S_IFMT)) == Int32(S_IFLNK)
}
/// Create a symlink from the target to the destination.
@discardableResult
func linkTo(path: String, overWrite: Bool = false) throws -> File {
let destFile = File(path)
if destFile.exists {
guard overWrite else {
throw PerfectError.fileError(-1, "Can not overwrite existing file")
}
destFile.delete()
}
let res = symlink(self.path, path)
if res == 0 {
return File(path)
}
try ThrowFileError()
}
}
public extension File {
/// Reads up to the indicated number of bytes from the file
/// - parameter count: The maximum number of bytes to read
/// - returns: The bytes read as an array of UInt8. May have a count of zero.
/// - throws: `PerfectError.FileError`
func readSomeBytes(count: Int) throws -> [UInt8] {
if !isOpen {
try open()
}
func sizeOr(_ value: Int) -> Int {
var st = stat()
let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard statRes != -1 else {
return 0
}
if (Int32(st.st_mode) & Int32(S_IFMT)) == Int32(S_IFREG) {
return Int(st.st_size)
}
return value
}
let bSize = min(count, sizeOr(count))
var ary = [UInt8](repeating: 0, count: bSize)
let readCount = ary.withUnsafeMutableBytes {
read(CInt(fd), $0.bindMemory(to: Int8.self).baseAddress, bSize)
}
guard readCount >= 0 else {
try ThrowFileError()
}
if readCount < bSize {
ary.removeLast(bSize - readCount)
}
return ary
}
/// Reads the entire file as a string
func readString() throws -> String {
let bytes = try readSomeBytes(count: size)
return UTF8Encoding.encode(bytes: bytes)
}
}
public extension File {
/// Writes the string to the file using UTF-8 encoding
/// - parameter s: The string to write
/// - returns: Returns the number of bytes which were written
/// - throws: `PerfectError.FileError`
@discardableResult
func write(string: String) throws -> Int {
return try write(bytes: Array(string.utf8))
}
/// Write the indicated bytes to the file
/// - parameter bytes: The array of UInt8 to write.
/// - parameter dataPosition: The offset within `bytes` at which to begin writing.
/// - parameter length: The number of bytes to write.
/// - throws: `PerfectError.FileError`
@discardableResult
func write(bytes: [UInt8], dataPosition: Int = 0, length: Int = Int.max) throws -> Int {
let len = min(bytes.count - dataPosition, length)
#if os(Linux)
let wrote = bytes.withUnsafeBytes {
SwiftGlibc.write(Int32(fd), $0.bindMemory(to: Int8.self).baseAddress?.advanced(by: dataPosition), len)
}
#else
let wrote = bytes.withUnsafeBytes {
Darwin.write(Int32(fd), $0.bindMemory(to: Int8.self).baseAddress?.advanced(by: dataPosition), len)
}
#endif
guard wrote == len else {
try ThrowFileError()
}
return wrote
}
}
public extension File {
/// Attempts to place an advisory lock starting from the current position marker up to the indicated byte count. This function will block the current thread until the lock can be performed.
/// - parameter byteCount: The number of bytes to lock
/// - throws: `PerfectError.FileError`
func lock(byteCount: Int) throws {
if !isOpen {
try open(.write)
}
let res = lockf(Int32(fd), F_LOCK, off_t(byteCount))
guard res == 0 else {
try ThrowFileError()
}
}
/// Unlocks the number of bytes starting from the current position marker up to the indicated byte count.
/// - parameter byteCount: The number of bytes to unlock
/// - throws: `PerfectError.FileError`
func unlock(byteCount: Int) throws {
if !isOpen {
try open(.write)
}
let res = lockf(Int32(fd), F_ULOCK, off_t(byteCount))
guard res == 0 else {
try ThrowFileError()
}
}
/// Attempts to place an advisory lock starting from the current position marker up to the indicated byte count. This function will throw an exception if the file is already locked, but will not block the current thread.
/// - parameter byteCount: The number of bytes to lock
/// - throws: `PerfectError.FileError`
func tryLock(byteCount: Int) throws {
if !isOpen {
try open(.write)
}
let res = lockf(Int32(fd), F_TLOCK, off_t(byteCount))
guard res == 0 else {
try ThrowFileError()
}
}
/// Tests if the indicated bytes are locked
/// - parameter byteCount: The number of bytes to test
/// - returns: True if the file is locked
/// - throws: `PerfectError.FileError`
func testLock(byteCount: Int) throws -> Bool {
if !isOpen {
try open(.write)
}
let res = Int(lockf(Int32(fd), F_TEST, off_t(byteCount)))
guard res == 0 || res == Int(EACCES) || res == Int(EAGAIN) else {
try ThrowFileError()
}
return res != 0
}
}
// Subclass to represent a file which can not be closed
private final class UnclosableFile : File {
override init(_ path: String, fd: Int32) {
super.init(path, fd: fd)
}
override func close() {
// nothing
}
}
/// A temporary, randomly named file.
public final class TemporaryFile: File {
/// Create a temporary file, usually in the system's /tmp/ directory
/// - parameter withPrefix: The prefix for the temporary file's name. Random characters will be appended to the file's eventual name.
public convenience init(withPrefix: String) {
let template = withPrefix + "XXXXXX"
let utf8 = template.utf8
let name = UnsafeMutablePointer<Int8>.allocate(capacity: utf8.count + 1)
var i = utf8.startIndex
for index in 0..<utf8.count {
name[index] = Int8(utf8[i])
i = utf8.index(after: i)
}
name[utf8.count] = 0
let fd = mkstemp(name)
let tmpFileName = String(validatingUTF8: name)!
name.deallocate()
self.init(tmpFileName, fd: fd)
}
}
/// This file can be used to write to standard in
public var fileStdin: File {
return UnclosableFile("/dev/stdin", fd: STDIN_FILENO)
}
/// This file can be used to write to standard out
public var fileStdout: File {
return UnclosableFile("/dev/stdout", fd: STDOUT_FILENO)
}
/// This file can be used to write to standard error
public var fileStderr: File {
return UnclosableFile("/dev/stderr", fd: STDERR_FILENO)
}