mirror of
https://github.com/apple/swift-nio
synced 2026-11-28 05:14:23 +00:00
Add API for setting last accessed and last modified file times (#2735)
This PR adds API to set a file's last accessed and last modified times, as well as a `touch()` shorthand that updates both to the current time. Motivation: Feature request: https://github.com/apple/swift-nio/issues/2712 Modifications: This PR adds API to set a file's last accessed and last modified times, as well as a `touch()` shorthand that updates both to the current time. Result: Files' last accessed and last modified times can be updated.
This commit is contained in:
1 parent
9428f62793
commit
bc161803bb
12 files changed
+432
-3
No files matched your search
@@ -83,6 +83,16 @@ extension _HasFileHandle {
|
||||
public func close() async throws {
|
||||
try await self.fileHandle.close()
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.fileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``FileHandleProtocol`` by making system calls to interact with the local file system.
|
||||
@@ -148,6 +158,16 @@ public struct FileHandle: FileHandleProtocol {
|
||||
public func close() async throws {
|
||||
try await self.systemFileHandle.close()
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.systemFileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``ReadableFileHandleProtocol`` by making system calls to interact with the local
|
||||
@@ -173,6 +193,16 @@ public struct ReadFileHandle: ReadableFileHandleProtocol, _HasFileHandle {
|
||||
public func readChunks(in range: Range<Int64>, chunkLength: ByteCount) -> FileChunks {
|
||||
self.fileHandle.systemFileHandle.readChunks(in: range, chunkLength: chunkLength)
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.fileHandle.systemFileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``WritableFileHandleProtocol`` by making system calls to interact with the local
|
||||
@@ -203,6 +233,16 @@ public struct WriteFileHandle: WritableFileHandleProtocol, _HasFileHandle {
|
||||
public func close(makeChangesVisible: Bool) async throws {
|
||||
try await self.fileHandle.systemFileHandle.close(makeChangesVisible: makeChangesVisible)
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.fileHandle.systemFileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``ReadableAndWritableFileHandleProtocol`` by making system calls to interact with the
|
||||
@@ -247,6 +287,16 @@ public struct ReadWriteFileHandle: ReadableAndWritableFileHandleProtocol, _HasFi
|
||||
public func close(makeChangesVisible: Bool) async throws {
|
||||
try await self.fileHandle.systemFileHandle.close(makeChangesVisible: makeChangesVisible)
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.fileHandle.systemFileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``DirectoryFileHandleProtocol`` by making system calls to interact with the local
|
||||
|
||||
@@ -143,6 +143,27 @@ public protocol FileHandleProtocol {
|
||||
///
|
||||
/// After closing the handle calls to other functions will throw an appropriate error.
|
||||
func close() async throws
|
||||
|
||||
/// Sets the file's last access and last data modification times to the given values.
|
||||
///
|
||||
/// If **either** time is `nil`, the current value will not be changed.
|
||||
/// If **both** times are `nil`, then both times will be set to the current time.
|
||||
///
|
||||
/// > Important: Times are only considered valid if their nanoseconds components are one of the following:
|
||||
/// > - `UTIME_NOW` (you can use ``FileInfo/Timespec/now`` to get a Timespec set to this value),
|
||||
/// > - `UTIME_OMIT` (you can use ``FileInfo/Timespec/omit`` to get a Timespec set to this value),
|
||||
/// > - Greater than zero and no larger than 1000 million: if outside of this range, the value will be clamped to the closest valid value.
|
||||
/// > The seconds component must also be positive: if it's not, zero will be used as the value instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lastAccessTime: The new value of the file's last access time, as time elapsed since the Epoch.
|
||||
/// - lastDataModificationTime: The new value of the file's last data modification time, as time elapsed since the Epoch.
|
||||
///
|
||||
/// - Throws: If there's an error updating the times. If this happens, the original values won't be modified.
|
||||
func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws
|
||||
}
|
||||
|
||||
// MARK: - Readable
|
||||
@@ -488,6 +509,36 @@ extension WritableFileHandleProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - File times modifiers
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension FileHandleProtocol {
|
||||
/// Sets the file's last access time to the given time.
|
||||
///
|
||||
/// - Parameter time: The time to which the file's last access time should be set.
|
||||
///
|
||||
/// - Throws: If there's an error updating the time. If this happens, the original value won't be modified.
|
||||
public func setLastAccessTime(to time: FileInfo.Timespec) async throws {
|
||||
try await self.setTimes(lastAccess: time, lastDataModification: nil)
|
||||
}
|
||||
|
||||
/// Sets the file's last data modification time to the given time.
|
||||
///
|
||||
/// - Parameter time: The time to which the file's last data modification time should be set.
|
||||
///
|
||||
/// - Throws: If there's an error updating the time. If this happens, the original value won't be modified.
|
||||
public func setLastDataModificationTime(to time: FileInfo.Timespec) async throws {
|
||||
try await self.setTimes(lastAccess: nil, lastDataModification: time)
|
||||
}
|
||||
|
||||
/// Sets the file's last access and last data modification times to the current time.
|
||||
///
|
||||
/// - Throws: If there's an error updating the times. If this happens, the original values won't be modified.
|
||||
public func touch() async throws {
|
||||
try await self.setTimes(lastAccess: nil, lastDataModification: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// A file handle which is suitable for reading and writing.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public typealias ReadableAndWritableFileHandleProtocol = ReadableFileHandleProtocol
|
||||
|
||||
@@ -19,8 +19,10 @@ import SystemPackage
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
import CNIOLinux
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
import CNIOLinux
|
||||
#endif
|
||||
|
||||
/// Information about a file system object.
|
||||
@@ -145,6 +147,29 @@ extension FileInfo {
|
||||
|
||||
/// A time interval consisting of whole seconds and nanoseconds.
|
||||
public struct Timespec: Hashable, Sendable {
|
||||
#if canImport(Darwin)
|
||||
private static let utimeOmit = Int(UTIME_OMIT)
|
||||
private static let utimeNow = Int(UTIME_NOW)
|
||||
#elseif canImport(Glibc) || canImport(Musl)
|
||||
private static let utimeOmit = Int(CNIOLinux_UTIME_OMIT)
|
||||
private static let utimeNow = Int(CNIOLinux_UTIME_NOW)
|
||||
#endif
|
||||
|
||||
/// A timespec where the seconds are set to zero and the nanoseconds set to `UTIME_OMIT`.
|
||||
/// In syscalls such as `futimens`, this means the time component set to this value will be ignored.
|
||||
public static let omit = Self(
|
||||
seconds: 0,
|
||||
nanoseconds: Self.utimeOmit
|
||||
)
|
||||
|
||||
/// A timespec where the seconds are set to zero and the nanoseconds set to `UTIME_NOW`.
|
||||
/// In syscalls such as `futimens`, this means the time component set to this value will be
|
||||
/// be set to the current time or the largest value supported by the platform, whichever is smaller.
|
||||
public static let now = Self(
|
||||
seconds: 0,
|
||||
nanoseconds: Self.utimeNow
|
||||
)
|
||||
|
||||
/// The number of seconds.
|
||||
public var seconds: Int
|
||||
|
||||
|
||||
@@ -1066,6 +1066,44 @@ extension FileSystemError {
|
||||
location: location
|
||||
)
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static func futimens(
|
||||
errno: Errno,
|
||||
path: FilePath,
|
||||
lastAccessTime: FileInfo.Timespec?,
|
||||
lastDataModificationTime: FileInfo.Timespec?,
|
||||
location: SourceLocation
|
||||
) -> FileSystemError {
|
||||
let code: FileSystemError.Code
|
||||
let message: String
|
||||
|
||||
switch errno {
|
||||
case .permissionDenied, .notPermitted:
|
||||
code = .permissionDenied
|
||||
message = "Not permitted to change last access or last data modification times for \(path)."
|
||||
|
||||
case .readOnlyFileSystem:
|
||||
code = .unsupported
|
||||
message = "Not permitted to change last access or last data modification times for \(path): this is a read-only file system."
|
||||
|
||||
case .badFileDescriptor:
|
||||
code = .closed
|
||||
message = "Could not change last access or last data modification dates for \(path): file is closed."
|
||||
|
||||
default:
|
||||
code = .unknown
|
||||
message = "Could not change last access or last data modification dates for \(path)."
|
||||
}
|
||||
|
||||
return FileSystemError(
|
||||
code: code,
|
||||
message: message,
|
||||
systemCall: "futimens",
|
||||
errno: errno,
|
||||
location: location
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -266,6 +266,16 @@ public enum Syscall {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@_spi(Testing)
|
||||
public static func futimens(
|
||||
fileDescriptor fd: FileDescriptor,
|
||||
times: UnsafePointer<timespec>?
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_futimens(fd.rawValue, times)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
|
||||
@@ -349,6 +349,18 @@ internal func system_sendfile(
|
||||
}
|
||||
#endif
|
||||
|
||||
internal func system_futimens(
|
||||
_ fd: CInt,
|
||||
_ times: UnsafePointer<timespec>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(fd, times)
|
||||
}
|
||||
#endif
|
||||
return futimens(fd, times)
|
||||
}
|
||||
|
||||
// MARK: - libc
|
||||
|
||||
/// fdopendir(3): Opens a directory stream for the file descriptor
|
||||
|
||||
@@ -22,8 +22,10 @@ import NIOPosix
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc
|
||||
import CNIOLinux
|
||||
#elseif canImport(Musl)
|
||||
import Musl
|
||||
import CNIOLinux
|
||||
#endif
|
||||
|
||||
/// An implementation of ``FileHandleProtocol`` which is backed by system calls and a file
|
||||
@@ -153,7 +155,7 @@ extension SystemFileHandle.SendableView {
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes a closure with the file descriptor it it's available otherwise throws the result
|
||||
/// Executes a closure with the file descriptor if it's available otherwise throws the result
|
||||
/// of `onUnavailable`.
|
||||
internal func _withUnsafeDescriptor<R>(
|
||||
_ execute: (FileDescriptor) throws -> R,
|
||||
@@ -166,8 +168,8 @@ extension SystemFileHandle.SendableView {
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes a closure with the file descriptor it it's available otherwise throws the result
|
||||
/// of `onUnavailable`.
|
||||
/// Executes a closure with the file descriptor if it's available otherwise returns the result
|
||||
/// of `onUnavailable` as a `Result` Error.
|
||||
internal func _withUnsafeDescriptorResult<R>(
|
||||
_ execute: (FileDescriptor) -> Result<R, FileSystemError>,
|
||||
onUnavailable: () -> FileSystemError
|
||||
@@ -355,6 +357,18 @@ extension SystemFileHandle: FileHandleProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.threadPool.runIfActive { [sendableView] in
|
||||
try sendableView._setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public enum UpdatePermissionsOperation { case set, add, remove }
|
||||
}
|
||||
@@ -909,6 +923,84 @@ extension SystemFileHandle.SendableView {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func _setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) throws {
|
||||
try self._withUnsafeDescriptor { descriptor in
|
||||
let syscallResult: Result<Void, Errno>
|
||||
switch (lastAccess, lastDataModification) {
|
||||
case (.none, .none):
|
||||
// If the timespec array is nil, as per the `futimens` docs,
|
||||
// both the last accessed and last modification times
|
||||
// will be set to now.
|
||||
syscallResult = Syscall.futimens(
|
||||
fileDescriptor: descriptor,
|
||||
times: nil
|
||||
)
|
||||
|
||||
case (.some(let lastAccess), .none):
|
||||
// Don't modify the last modification time.
|
||||
syscallResult = Syscall.futimens(
|
||||
fileDescriptor: descriptor,
|
||||
times: [timespec(lastAccess), timespec(.omit)]
|
||||
)
|
||||
|
||||
case (.none, .some(let lastDataModification)):
|
||||
// Don't modify the last access time.
|
||||
syscallResult = Syscall.futimens(
|
||||
fileDescriptor: descriptor,
|
||||
times: [timespec(.omit), timespec(lastDataModification)]
|
||||
)
|
||||
|
||||
case (.some(let lastAccess), .some(let lastDataModification)):
|
||||
syscallResult = Syscall.futimens(
|
||||
fileDescriptor: descriptor,
|
||||
times: [timespec(lastAccess), timespec(lastDataModification)]
|
||||
)
|
||||
}
|
||||
|
||||
try syscallResult.mapError { errno in
|
||||
FileSystemError.futimens(
|
||||
errno: errno,
|
||||
path: self.path,
|
||||
lastAccessTime: lastAccess,
|
||||
lastDataModificationTime: lastDataModification,
|
||||
location: .here()
|
||||
)
|
||||
}.get()
|
||||
} onUnavailable: {
|
||||
FileSystemError(
|
||||
code: .closed,
|
||||
message: "Couldn't modify file dates, the file '\(self.path)' is closed.",
|
||||
cause: nil,
|
||||
location: .here()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension timespec {
|
||||
fileprivate init(_ fileinfoTimespec: FileInfo.Timespec) {
|
||||
// Clamp seconds to be positive
|
||||
let seconds = max(0, fileinfoTimespec.seconds)
|
||||
|
||||
// If nanoseconds are not UTIME_NOW or UTIME_OMIT, clamp to be between
|
||||
// 0 and 1,000 million.
|
||||
let nanoseconds: Int
|
||||
switch fileinfoTimespec {
|
||||
case .now, .omit:
|
||||
nanoseconds = fileinfoTimespec.nanoseconds
|
||||
default:
|
||||
nanoseconds = min(1_000_000_000, max(0, fileinfoTimespec.nanoseconds))
|
||||
}
|
||||
|
||||
self.init(
|
||||
tv_sec: seconds,
|
||||
tv_nsec: nanoseconds
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Readable File Handle
|
||||
|
||||
Reference in new issue
Block a user