File: FileSystemError.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (336 lines) | stat: -rw-r--r-- 11,155 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android)
import SystemPackage

/// An error thrown as a result of interaction with the file system.
///
/// All errors have a high-level ``FileSystemError/Code-swift.struct`` which identifies the domain
/// of the error. For example an operation performed on a ``FileHandleProtocol`` which has already been
/// closed will result in a ``FileSystemError/Code-swift.struct/closed`` error code. Errors also
/// include a message describing what went wrong and how to remedy it (if applicable). The
/// ``FileSystemError/message`` is not static and may include dynamic information such as the path
/// of the file for which the operation failed, for example.
///
/// Errors may have a ``FileSystemError/cause``, an underlying error which caused the operation to
/// fail which may be platform specific.
public struct FileSystemError: Error, @unchecked Sendable {
    // Note: @unchecked because we use a backing class for storage.

    private var storage: Storage
    private mutating func ensureStorageIsUnique() {
        if !isKnownUniquelyReferenced(&self.storage) {
            self.storage = self.storage.copy()
        }
    }

    private final class Storage {
        var code: Code
        var message: String
        var cause: Error?
        var location: SourceLocation

        init(code: Code, message: String, cause: Error?, location: SourceLocation) {
            self.code = code
            self.message = message
            self.cause = cause
            self.location = location
        }

        func copy() -> Self {
            return Self(
                code: self.code,
                message: self.message,
                cause: self.cause,
                location: self.location
            )
        }
    }

    /// A high-level error code to provide broad a classification.
    public var code: Code {
        get { self.storage.code }
        set {
            self.ensureStorageIsUnique()
            self.storage.code = newValue
        }
    }

    /// A message describing what went wrong and how it may be remedied.
    public var message: String {
        get { self.storage.message }
        set {
            self.ensureStorageIsUnique()
            self.storage.message = newValue
        }
    }

    /// An underlying error which caused the operation to fail. This may include additional details
    /// about the root cause of the failure.
    public var cause: Error? {
        get { self.storage.cause }
        set {
            self.ensureStorageIsUnique()
            self.storage.cause = newValue
        }
    }

    /// The location from which this error was thrown.
    public var location: SourceLocation {
        get { self.storage.location }
        set {
            self.ensureStorageIsUnique()
            self.storage.location = newValue
        }
    }

    public init(
        code: Code,
        message: String,
        cause: Error?,
        location: SourceLocation
    ) {
        self.storage = Storage(code: code, message: message, cause: cause, location: location)
    }

    /// Creates a ``FileSystemError`` by wrapping the given `cause` and its location and code.
    internal init(message: String, wrapping cause: FileSystemError) {
        self.init(code: cause.code, message: message, cause: cause, location: cause.location)
    }
}

extension FileSystemError: CustomStringConvertible {
    public var description: String {
        if let cause = self.cause {
            return "\(self.code): \(self.message) (\(cause))"
        } else {
            return "\(self.code): \(self.message)"
        }
    }
}

extension FileSystemError: CustomDebugStringConvertible {
    public var debugDescription: String {
        if let cause = self.cause {
            return """
                \(String(reflecting: self.code)): \(String(reflecting: self.message)) \
                (\(String(reflecting: cause)))
                """
        } else {
            return "\(String(reflecting: self.code)): \(String(reflecting: self.message))"
        }
    }
}

extension FileSystemError {
    private func detailedDescriptionLines() -> [String] {
        // Build up a tree-like description of the error. This allows nested causes to be formatted
        // correctly, especially when they are also FileSystemErrors.
        //
        // An example is:
        //
        //  FileSystemError: Closed
        //  ├─ Reason: Unable to open file at path 'foo.swift', the descriptor is closed.
        //  ├─ Cause: 'openat' system call failed with '(9) Bad file descriptor'.
        //  └─ Source location: openFile(forReadingAt:_:) (FileSystem.swift:314)
        var lines = [
            "FileSystemError: \(self.code)",
            "├─ Reason: \(self.message)",
        ]

        if let error = self.cause as? FileSystemError {
            lines.append("├─ Cause:")
            let causeLines = error.detailedDescriptionLines()
            // We know this will never be empty.
            lines.append("│  └─ \(causeLines.first!)")
            lines.append(contentsOf: causeLines.dropFirst().map { "│     \($0)" })
        } else if let error = self.cause {
            lines.append("├─ Cause: \(String(reflecting: error))")
        }

        lines.append(
            "└─ Source location: \(self.location.function) (\(self.location.file):\(self.location.line))"
        )

        return lines
    }

    /// A detailed multi-line description of the error.
    ///
    /// - Returns: A multi-line description of the error.
    public func detailedDescription() -> String {
        return self.detailedDescriptionLines().joined(separator: "\n")
    }
}

extension FileSystemError {
    /// A high level indication of the kind of error being thrown.
    public struct Code: Hashable, Sendable, CustomStringConvertible {
        private enum Wrapped: Hashable, Sendable, CustomStringConvertible {
            case closed
            case invalidArgument
            case io
            case permissionDenied
            case notEmpty
            case notFound
            case resourceExhausted
            case unavailable
            case unknown
            case unsupported
            case fileAlreadyExists

            var description: String {
                switch self {
                case .closed:
                    return "Closed"
                case .invalidArgument:
                    return "Invalid argument"
                case .io:
                    return "I/O error"
                case .permissionDenied:
                    return "Permission denied"
                case .resourceExhausted:
                    return "Resource exhausted"
                case .notEmpty:
                    return "Not empty"
                case .notFound:
                    return "Not found"
                case .unavailable:
                    return "Unavailable"
                case .unknown:
                    return "Unknown"
                case .unsupported:
                    return "Unsupported"
                case .fileAlreadyExists:
                    return "File already exists"
                }
            }
        }

        public var description: String {
            String(describing: self.code)
        }

        private var code: Wrapped
        private init(_ code: Wrapped) {
            self.code = code
        }

        /// An operation on the file could not be performed because the file is closed
        /// (or detached).
        public static var closed: Self {
            Self(.closed)
        }

        /// A provided argument was not valid for the operation.
        public static var invalidArgument: Self {
            Self(.invalidArgument)
        }

        /// An I/O error occurred.
        public static var io: Self {
            Self(.io)
        }

        /// The caller did not have sufficient permission to perform the operation.
        public static var permissionDenied: Self {
            Self(.permissionDenied)
        }

        /// A required resource was exhausted.
        public static var resourceExhausted: Self {
            Self(.resourceExhausted)
        }

        /// The directory wasn't empty.
        public static var notEmpty: Self {
            Self(.notEmpty)
        }

        /// The file could not be found.
        public static var notFound: Self {
            Self(.notFound)
        }

        /// The file system is not currently available, for example if the underlying executor
        /// is not running.
        public static var unavailable: Self {
            Self(.unavailable)
        }

        /// The error is not known or may not have an appropriate classification. See
        /// ``FileSystemError/cause`` for more information about the error.
        public static var unknown: Self {
            Self(.unknown)
        }

        /// The operation is not supported or is not enabled.
        public static var unsupported: Self {
            Self(.unsupported)
        }

        /// The file already exists.
        public static var fileAlreadyExists: Self {
            Self(.fileAlreadyExists)
        }
    }

    /// A location within source code.
    public struct SourceLocation: Sendable, Hashable {
        /// The function in which the error was thrown.
        public var function: String

        /// The file in which the error was thrown.
        public var file: String

        /// The line on which the error was thrown.
        public var line: Int

        public init(function: String, file: String, line: Int) {
            self.function = function
            self.file = file
            self.line = line
        }

        internal static func here(
            function: String = #function,
            file: String = #fileID,
            line: Int = #line
        ) -> Self {
            return SourceLocation(function: function, file: file, line: line)
        }
    }
}

extension FileSystemError {
    /// An error resulting from a system call.
    public struct SystemCallError: Error, Hashable, CustomStringConvertible {
        /// The name of the system call which produced the error.
        public var systemCall: String
        /// The errno set by the system call.
        public var errno: Errno

        public init(systemCall: String, errno: Errno) {
            self.systemCall = systemCall
            self.errno = errno
        }

        public var description: String {
            "'\(self.systemCall)' system call failed with '(\(self.errno.rawValue)) \(self.errno)'."
        }
    }
}

#endif