forked from PerfectlySoft/Perfect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFile.swift
575 lines (498 loc) · 16.4 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
//
// File.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/7/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
#if os(Linux)
import SwiftGlibc
import LinuxBridge
// !FIX! these are obviously sketchy
// I hope SwiftGlibc to eventually include these
// Otherwise, export them from LinuxBridge
let S_IRGRP = (S_IRUSR >> 3)
let S_IWGRP = (S_IWUSR >> 3)
let S_IRWXU = (__S_IREAD|__S_IWRITE|__S_IEXEC)
let S_IRWXG = (S_IRWXU >> 3)
let S_IRWXO = (S_IRWXG >> 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 : Closeable {
var openMode = Int(O_RDONLY)
var fd = -1
var internalPath = ""
/// Create a file object given a path and open mode
/// - parameter path: Path to the file which will be accessed
/// - parameter openMode: Default mode with which the file will be opened. Defaults to read-only. The file can be opened in any other mode by calling the accosiated openXXX function.
public init(_ path: String, openMode: Int = Int(O_RDONLY)) {
self.internalPath = path
self.openMode = openMode
}
/// Create a file object given an already opened file descriptor
/// - parameter fd: The file descriptor
/// - parameter path: The path to the file which has been previously opened. Defaults to no path.
public init(fd: Int32, path: String = "") {
self.fd = Int(fd)
self.internalPath = path
}
/// Create a temporary file, usually in the system's /tmp/ directory
/// - parameter tempFilePrefix: The prefix for the temporary file's name. Random characters will be appended to the file's eventual name.
public convenience init(tempFilePrefix: String) {
let template = tempFilePrefix + "XXXXXX"
let utf8 = template.utf8
let name = UnsafeMutablePointer<Int8>.alloc(utf8.count + 1)
var i = utf8.startIndex
for index in 0..<utf8.count {
name[index] = Int8(utf8[i])
i = i.successor()
}
name[utf8.count] = 0
let fd = mkstemp(name)
let tmpFileName = String.fromCString(name)!
name.dealloc(utf8.count + 1)
name.destroy()
self.init(fd: fd, path: tmpFileName)
}
/// Returns the file's path
public func path() -> String { return internalPath }
/// Returns the file path. If the file is a symbolic link, the link will be resolved.
public func realPath() -> String {
if isLink() {
let buffer = UnsafeMutablePointer<Int8>.alloc(2048)
defer { buffer.destroy() ; buffer.dealloc(2048) }
let res = readlink(internalPath, buffer, 2048)
if res != -1 {
let ary = completeArray(buffer, count: res)
let trailPath = UTF8Encoding.encode(ary)
if trailPath[trailPath.startIndex] != "/" && trailPath[trailPath.startIndex] != "." {
return internalPath.stringByDeletingLastPathComponent + "/" + trailPath
}
return trailPath
}
}
return internalPath
}
/// Closes and deletes the file
public func delete() {
if isOpen() {
close()
}
unlink(path())
}
/// 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
}
/// Opens the file using the default open mode.
/// - throws: `PerfectError.FileError`
public func open() throws {
#if os(Linux)
let openFd = linux_open(internalPath, CInt(openMode), mode_t(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP))
#else
let openFd = Darwin.open(internalPath, CInt(openMode), mode_t(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP))
#endif
guard openFd != -1 else {
try ThrowFileError()
}
fd = Int(openFd)
}
/// Opens the file for read-only access.
/// - throws: `PerfectError.FileError`
public func openRead() throws {
openMode = Int(O_RDONLY)
try open()
}
/// Opens the file for read-write access, creating the file if it did not exist.
/// - throws: `PerfectError.FileError`
public func openWrite() throws {
openMode = Int(O_RDWR|O_CREAT)
try open()
}
/// Opens the file for write-only access, creating the file if it did not exist.
/// - throws: `PerfectError.FileError`
public func openWriteOnly() throws {
openMode = Int(O_WRONLY|O_CREAT)
try open()
}
/// Opens the file for read-write access, creating the file if it did not exist and moving the file marker to the end.
/// - throws: `PerfectError.FileError`
public func openAppend() throws {
openMode = Int(O_RDWR|O_APPEND|O_CREAT)
try open()
}
/// Opens the file for read-write access, creating the file if it did not exist and setting the file's size to zero.
/// - throws: `PerfectError.FileError`
public func openTruncate() throws {
openMode = Int(O_RDWR|O_TRUNC|O_CREAT)
try open()
}
/// Opens the file for read-only access.
/// - parameter path: The path
/// - throws: `PerfectError.FileError`
public func openRead(path: String) throws {
internalPath = path
openMode = Int(O_RDONLY)
try open()
}
/// Opens the file for read-write access, creating the file if it did not exist.
/// - parameter path: The path
/// - throws: `PerfectError.FileError`
public func openWrite(path: String) throws {
internalPath = path
openMode = Int(O_RDWR|O_CREAT)
try open()
}
/// Opens the file for write-only access, creating the file if it did not exist.
/// - parameter path: The path
/// - throws: `PerfectError.FileError`
public func openWriteOnly(path: String) throws {
internalPath = path
openMode = Int(O_WRONLY|O_CREAT)
try open()
}
/// Opens the file for read-write access, creating the file if it did not exist and moving the file marker to the end.
/// - parameter path: The path
/// - throws: `PerfectError.FileError`
public func openAppend(path: String) throws {
internalPath = path
openMode = Int(O_RDWR|O_APPEND|O_CREAT)
try open()
}
/// Opens the file for read-write access, creating the file if it did not exist and setting the file's size to zero.
/// - parameter path: The path
/// - throws: `PerfectError.FileError`
public func openTruncate(path: String) throws {
internalPath = path
openMode = Int(O_RDWR|O_TRUNC|O_CREAT)
try open()
}
/// Returns the value of the file's current position marker
/// - returns: The file marker value
public func marker() -> Int {
if isOpen() {
return Int(lseek(Int32(self.fd), 0, SEEK_CUR))
}
return 0
}
/// Sets the file's position marker given the `to` and `whence` parameters.
/// - parameter to: The new position
/// - parameter whence: Whence to set it from. Once of `SEEK_SET`, `SEEK_CUR`, `SEEK_END`.
/// - returns: The new position marker value
public func setMarker(to: Int, whence: Int32 = SEEK_CUR) -> Int {
if isOpen() {
return Int(lseek(Int32(self.fd), off_t(to), whence))
}
return 0
}
/// 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 func 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
}
/// 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`
public func moveTo(path: String, overWrite: Bool = false) throws -> File {
let destFile = File(path)
if destFile.exists() {
if overWrite {
destFile.delete()
} else {
throw PerfectError.FileError(-1, "Can not overwrite existing file")
}
}
close()
let res = rename(self.path(), path)
if res == 0 {
return destFile
}
if errno == EXDEV {
try self.copyTo(path, overWrite: overWrite)
self.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`
public func copyTo(path: String, overWrite: Bool = false) throws -> File {
let destFile = File(path)
if destFile.exists() {
if overWrite {
destFile.delete()
} else {
throw PerfectError.FileError(-1, "Can not overwrite existing file")
}
}
let wasOpen = self.isOpen()
let oldMarker = self.marker()
if !wasOpen {
try openRead()
} else {
setMarker(0)
}
defer {
if !wasOpen {
close()
} else {
setMarker(oldMarker)
}
}
try destFile.openTruncate()
var bytes = try self.readSomeBytes(fileCopyBufferSize)
while bytes.count > 0 {
try destFile.writeBytes(bytes)
bytes = try self.readSomeBytes(fileCopyBufferSize)
}
destFile.close()
return destFile
}
/// Checks that the file exists on the file system
/// - returns: True if the file exists or false otherwise
public func exists() -> Bool {
return access(internalPath, F_OK) != -1
}
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
}
/// Returns the size of the file in bytes
public func 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 has been opened
public func isOpen() -> Bool {
return fd != -1
}
/// Returns true if the file is a symbolic link
public func 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)
}
/// Returns true if the file is actually a directory
public func 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
public func perms() -> Int {
var st = stat()
let statRes = isOpen() ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard statRes != -1 else {
return 0
}
let mode = st.st_mode
return Int(Int32(mode) ^ Int32(S_IFMT))
}
/// 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`
public func readSomeBytes(count: Int) throws -> [UInt8] {
if !isOpen() {
try openRead()
}
let bSize = min(count, self.sizeOr(count))
let ptr = UnsafeMutablePointer<UInt8>.alloc(bSize)
defer {
ptr.destroy()
ptr.dealloc(bSize)
}
let readCount = read(CInt(fd), ptr, bSize)
guard readCount >= 0 else {
try ThrowFileError()
}
return completeArray(ptr, count: readCount)
}
/// Reads the entire file as a string
public func readString() throws -> String {
let bytes = try self.readSomeBytes(self.size())
return UTF8Encoding.encode(bytes)
}
/// 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`
public func writeString(s: String) throws -> Int {
return try writeBytes(Array(s.utf8))
}
/// Writes the array of bytes to the file
/// - parameter bytes: The bytes to write
/// - returns: The number of bytes which were written
/// - throws: `PerfectError.FileError`
public func writeBytes(bytes: [UInt8]) throws -> Int {
return try writeBytes(bytes, dataPosition: 0, length: bytes.count)
}
/// 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`
public func writeBytes(bytes: [UInt8], dataPosition: Int, length: Int) throws -> Int {
let ptr = UnsafeMutablePointer<UInt8>(bytes).advancedBy(dataPosition)
let wrote = write(CInt(fd), ptr, length)
guard wrote == length else {
try ThrowFileError()
}
return wrote
}
/// 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`
public func lock(byteCount: Int) throws {
if !isOpen() {
try openWrite()
}
let res = lockf(Int32(self.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`
public func unlock(byteCount: Int) throws {
if !isOpen() {
try openWrite()
}
let res = lockf(Int32(self.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`
public func tryLock(byteCount: Int) throws {
if !isOpen() {
try openWrite()
}
let res = lockf(Int32(self.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`
public func testLock(byteCount: Int) throws -> Bool {
if !isOpen() {
try openWrite()
}
let res = Int(lockf(Int32(self.fd), F_TEST, off_t(byteCount)))
guard res == 0 || res == Int(EACCES) || res == Int(EAGAIN) else {
try ThrowFileError()
}
return res != 0
}
private func completeArray(from: UnsafeMutablePointer<UInt8>, count: Int) -> [UInt8] {
defer { from.destroy() }
var ary = [UInt8](count: count, repeatedValue: 0)
for index in 0..<count {
ary[index] = from[index]
}
return ary
}
private func completeArray(from: UnsafeMutablePointer<Int8>, count: Int) -> [UInt8] {
defer { from.destroy() }
var ary = [UInt8](count: count, repeatedValue: 0)
for index in 0..<count {
ary[index] = UInt8(from[index])
}
return ary
}
}
class UnclosableFile : File {
init(fd: Int32) {
super.init(fd: fd, path: "")
}
override func close() {
// nothing
}
}
/// This file can be used to write to standard in
public func FileStdin() -> File {
return UnclosableFile(fd: STDIN_FILENO)
}
/// This file can be used to write to standard out
public func FileStdout() -> File {
return UnclosableFile(fd: STDOUT_FILENO)
}
/// This file can be used to write to standard error
public func FileStderr() -> File {
return UnclosableFile(fd: STDERR_FILENO)
}