### Go os.Stat() Example Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Shows Go's os.Stat() function and its return type, fs.FileInfo. ```go os.Stat() -> fs.FileInfo ``` -------------------------------- ### Python os.stat() Example Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Demonstrates Python's os.stat() function and its result type, os.stat_result. ```python os.stat() -> os.stat_result ``` -------------------------------- ### Rust fs::metadata() Example Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Illustrates Rust's approach to file metadata retrieval, mapping to fs::Metadata. ```rust fs::metadata() -> fs::Metadata ``` -------------------------------- ### Create stat() overloads on FilePath Source: https://github.com/apple/swift-system/blob/main/Proposals/0008-backdeploy-cinterop-stat.md Provides a deprecated extension on FilePath to guide developers toward the new System.Stat API while maintaining backward compatibility. ```swift extension FilePath { @available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.") public func stat() -> CInterop.Stat { CInterop.Stat() } @available(*, deprecated, message: "Use 'try stat()' in your FilePath extension to get a System.Stat instead. Then, use '.rawValue' to get the underlying C type if desired.") public func stat( _ path: UnsafePointer, _ s: inout CInterop.Stat ) -> Int32 { system_stat(path, &s) } } ``` -------------------------------- ### Unqualified stat call causing compatibility issues Source: https://github.com/apple/swift-system/blob/main/Proposals/0008-backdeploy-cinterop-stat.md Example of an extension that uses unqualified stat calls, which will conflict with new System APIs. ```swift extension FilePath { func isRegularFile() -> Bool { var s = stat() // Calls Darwin.stat(_:_:) - unqualified! guard stat(self.string, &s) == 0 else { // Calls Darwin.stat(_:_:) - unqualified! return false } return s.st_mode & S_IFMT == S_IFREG } } ``` -------------------------------- ### Configure and Export Swift System Targets Source: https://github.com/apple/swift-system/blob/main/cmake/modules/CMakeLists.txt Sets up the export file path, configures the package file, and exports the defined targets with the SwiftSystem namespace. ```cmake set(SWIFT_SYSTEM_EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/SwiftSystemExports.cmake) configure_file(SwiftSystemConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/SwiftSystemConfig.cmake) get_property(SWIFT_SYSTEM_EXPORTS GLOBAL PROPERTY SWIFT_SYSTEM_EXPORTS) export(TARGETS ${SWIFT_SYSTEM_EXPORTS} NAMESPACE SwiftSystem:: FILE ${SWIFT_SYSTEM_EXPORTS_FILE} EXPORT_LINK_INTERFACE_LIBRARIES) ``` -------------------------------- ### Basic File Write Operation Source: https://github.com/apple/swift-system/blob/main/README.md Demonstrates opening a file for writing, appending, and creating it if it doesn't exist, then writing a UTF-8 encoded string to it. The file descriptor is automatically closed after the operation. ```swift import SystemPackage let message: String = "Hello, world!" + "\n" let path: FilePath = "/tmp/log" let fd = try FileDescriptor.open( path, .writeOnly, options: [.append, .create], permissions: .ownerReadWrite) try fd.closeAfter { _ = try fd.writeAll(message.utf8) } ``` -------------------------------- ### Configure Package.swift for Swift System Source: https://github.com/apple/swift-system/blob/main/README.md Include the Swift System package and its product in your executable target's dependencies within Package.swift. ```swift let package = Package( // name, platforms, products, etc. dependencies: [ .package(url: "https://github.com/apple/swift-system", from: "1.7.1"), // other dependencies ], targets: [ .target(name: "MyTarget", dependencies: [ .product(name: "SystemPackage", package: "swift-system"), ]), // other targets ] ) ``` -------------------------------- ### Stat Initializers Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Methods to initialize a Stat object from various file references including FilePath, UnsafePointer, and FileDescriptor. ```APIDOC ## Initializing Stat ### Description Creates a Stat object representing file status information. Initializers support different sources and symlink resolution behaviors. ### Parameters #### Path Parameters - **path** (FilePath or UnsafePointer) - Required - The file path to query. - **fd** (FileDescriptor) - Required - The file descriptor to query. #### Optional Parameters - **followTargetSymlink** (Bool) - Optional - Defaults to true. If true, follows symlinks (stat); if false, returns info about the link itself (lstat). - **retryOnInterrupt** (Bool) - Optional - Defaults to true. Whether to retry the system call if interrupted. - **flags** (Stat.Flags) - Optional - Flags for fstatat() behavior (e.g., .symlinkNoFollow). ### Request Example // Initialize from FilePath let stat = try Stat(myFilePath, followTargetSymlink: false) // Initialize from FileDescriptor let fdStat = try Stat(myFileDescriptor) ``` -------------------------------- ### Accessing File Metadata with Stat Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Demonstrates retrieving file status from paths and file descriptors, including symlink handling and platform-specific metadata. ```swift // Get file status from path String let stat = try Stat("/path/to/file") // From FileDescriptor let stat = try fd.stat() // From FilePath let stat = try filePath.stat() // `followTargetSymlink: true` (default) behaves like `stat()` // `followTargetSymlink: false` behaves like `lstat()` let stat = try symlinkPath.stat(followTargetSymlink: false) // Supply flags and optional file descriptor to use the `fstatat()` variant let stat = try Stat("path/to/file", relativeTo: fd, flags: .symlinkNoFollow) print("Size: \(stat.size) bytes") print("Size allocated: \(stat.sizeAllocated) bytes") print("Type: \(stat.type)") // .regular, .directory, .symbolicLink, etc. print("Permissions: \(stat.permissions)") print("Modified: \(stat.modificationTime)") // Platform-specific information when available #if canImport(Darwin) || os(FreeBSD) print("Creation time: \(stat.creationTime)") #endif ``` -------------------------------- ### Swift Stat Initializer Mappings Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Maps Swift Stat initializer calls to their corresponding Unix-like system calls. ```swift Stat(_ path: FilePath, followTargetSymlink: true) stat() ``` ```swift Stat(_ path: UnsafePointer, followTargetSymlink: true) stat() ``` ```swift Stat(_ path: FilePath, followTargetSymlink: false) lstat() ``` ```swift Stat(_ path: UnsafePointer, followTargetSymlink: false) lstat() ``` ```swift Stat(_ path: FilePath, relativeTo: FileDescriptor, flags: Stat.Flags) fstatat() ``` ```swift Stat(_ path: UnsafePointer, relativeTo: FileDescriptor, flags: Stat.Flags) fstatat() ``` ```swift Stat(_ fd: FileDescriptor) fstat() ``` ```swift FileDescriptor.stat() fstat() ``` ```swift FilePath.stat(followTargetSymlink: true) stat() ``` ```swift FilePath.stat(followTargetSymlink: false) lstat() ``` ```swift FilePath.stat(relativeTo: FileDescriptor, flags: Stat.Flags) fstatat() ``` -------------------------------- ### Extend Stat with UTCClock.Instant for Time Properties Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Extends the `Stat` type to provide access to time properties like access, modification, and change times using `UTCClock.Instant`. This approach reserves ergonomic names for future extensions. Note that `creationTime` is only available on Darwin and FreeBSD. ```swift extension Stat { /// Time of last access, given as a `UTCClock.Instant` /// /// The corresponding C property is `st_atim` (or `st_atimespec` on Darwin). public var accessTime: UTCClock.Instant { get set } /// Time of last modification, given as a `UTCClock.Instant` /// /// The corresponding C property is `st_mtim` (or `st_mtimespec` on Darwin). public var modificationTime: UTCClock.Instant { get set } /// Time of last status (inode) change, given as a `UTCClock.Instant` /// /// The corresponding C property is `st_ctim` (or `st_ctimespec` on Darwin). public var changeTime: UTCClock.Instant { get set } #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) /// Time of file creation, given as a `UTCClock.Instant` /// /// The corresponding C property is `st_birthtim` (or `st_birthtimespec` on Darwin). /// - Note: Only available on Darwin and FreeBSD. public var creationTime: UTCClock.Instant { get set } #endif } ``` -------------------------------- ### Stat Initializers Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Initializers for creating a Stat struct from file paths, supporting relative paths via FileDescriptor. ```APIDOC ## Initializer: init(_:relativeTo:flags:retryOnInterrupt:) ### Description Creates a Stat struct from a FilePath. If the path is relative, it is resolved against the provided FileDescriptor. ### Parameters #### Path Parameters - **path** (FilePath) - Required - The path to the file. - **relativeTo** (FileDescriptor) - Optional - The directory to resolve relative paths against. - **flags** (Stat.Flags) - Required - Flags for the stat operation. - **retryOnInterrupt** (Bool) - Optional - Whether to retry on interrupt (default: true). ## Initializer: init(_:flags:retryOnInterrupt:) ### Description Creates a Stat struct from a C-style path string. If relative, it is resolved against the current working directory. ### Parameters - **path** (UnsafePointer) - Required - The path to the file. - **flags** (Stat.Flags) - Required - Flags for the stat operation. - **retryOnInterrupt** (Bool) - Optional - Whether to retry on interrupt (default: true). ``` -------------------------------- ### Handling Stat Errors Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Shows how to catch Errno errors when initializing a Stat object. ```swift do { let stat = try Stat("/nonexistent/file") } catch Errno.noSuchFileOrDirectory { print("File not found") } catch { print("Other error: \(error)") } ``` -------------------------------- ### PipeOptions for Non-blocking and Close-on-Exec/Fork Source: https://github.com/apple/swift-system/blob/main/Proposals/0007-FileDescriptor-dup3-pipe2.md Defines options for creating pipes, including non-blocking I/O and flags to close the file descriptor on exec or fork. ```swift public struct PipeOptions: OptionSet, Sendable, Hashable, Codable { public var rawValue: CInt public init(rawValue: CInt) public static var nonBlocking: PipeOptions public static var closeOnExec: PipeOptions public static var closeOnFork: PipeOptions } ``` -------------------------------- ### Add Swift System Package Dependency Source: https://github.com/apple/swift-system/blob/main/README.md Add this line to your Package.swift file's dependencies to include the Swift System package. ```swift .package(url: "https://github.com/apple/swift-system", from: "1.7.1"), ``` -------------------------------- ### DuplicateOptions for Close-on-Exec/Fork Source: https://github.com/apple/swift-system/blob/main/Proposals/0007-FileDescriptor-dup3-pipe2.md Defines options for duplicating file descriptors, specifically flags to close the descriptor on exec or fork. ```swift public struct DuplicateOptions: OptionSet, Sendable, Hashable, Codable { public var rawValue: CInt public init(rawValue: CInt) public static var closeOnExec: DuplicateOptions public static var closeOnFork: DuplicateOptions } ``` -------------------------------- ### Implement internal system_stat wrapper Source: https://github.com/apple/swift-system/blob/main/Proposals/0008-backdeploy-cinterop-stat.md An internal helper function marked for inlining that calls the platform-specific global stat function. ```swift #if !os(Windows) @_alwaysEmitIntoClient internal func system_stat(_ path: UnsafePointer, _ s: inout CInterop.Stat) -> Int32 { stat(path, &s) } #endif ``` -------------------------------- ### Migration from unqualified stat to CInterop.stat Source: https://github.com/apple/swift-system/blob/main/Proposals/0008-backdeploy-cinterop-stat.md Comparison of code before and after migrating to the CInterop-qualified APIs. ```swift extension FilePath { func isRegularFile() throws -> Bool { var s = stat() guard stat(self.string, &s) == 0 else { throw Errno.current } return s.st_mode & S_IFMT == S_IFREG } } ``` ```swift extension FilePath { func isRegularFile() throws -> Bool { var s = CInterop.Stat() // stat() --> CInterop.Stat() guard CInterop.stat(self.string, &s) == 0 else { // stat(_:_:) --> CInterop.stat(_:_:) throw Errno.current } return s.st_mode & S_IFMT == S_IFREG } } ``` -------------------------------- ### CInterop.stat(_:_:) Function Source: https://github.com/apple/swift-system/blob/main/Proposals/0008-backdeploy-cinterop-stat.md A direct wrapper around the C stat() system call, intended for migration purposes when supporting older deployment targets. ```APIDOC ## CInterop.stat(_:_:) ### Description Calls the C stat() function to retrieve file metadata. This is a direct wrapper intended for migration purposes when supporting older deployment targets that do not support the newer, ergonomic Stat API. ### Parameters - **path** (UnsafePointer) - Required - A null-terminated C string representing the file path. - **s** (inout CInterop.Stat) - Required - An inout reference to a CInterop.Stat struct to populate with file metadata. ### Response - **Returns** (Int32) - 0 on success, -1 on error (check Errno.current for details). ``` -------------------------------- ### Create a Unidirectional Data Channel with pipe() Source: https://github.com/apple/swift-system/blob/main/Proposals/0007-FileDescriptor-dup3-pipe2.md Creates a unidirectional data channel for interprocess communication using `pipe(options:)`. Supports options like non-blocking I/O and close-on-exec/fork. ```swift public static func pipe( options: PipeOptions ) throws(Errno) -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) ``` -------------------------------- ### Stat Structure and Properties Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Details about the `Stat` structure and its available properties for file metadata. ```APIDOC ## Stat Structure ### Description Represents file status information. ### Properties - **st_birthtim** (timespec) - Time of file creation, given as a C `timespec` since the Epoch. Only available on Darwin and FreeBSD. - **flags** (FileFlags) - File flags. Only available on Darwin, FreeBSD, and OpenBSD. - **generationNumber** (Int) - File generation number. Only available on Darwin, FreeBSD, and OpenBSD. ### Conformance - Equatable - Hashable ``` -------------------------------- ### Duplicate File Descriptor with Options Source: https://github.com/apple/swift-system/blob/main/Proposals/0007-FileDescriptor-dup3-pipe2.md Duplicates an existing file descriptor with specified options, mirroring the dup3 system call. Use when you need to control flags like close-on-exec or close-on-fork during duplication. ```swift import System let fd0 = try FileDescriptor.open("/tmp/test.txt", .readOnly) let fd1 = FileDescriptor(rawValue: 731) let fd2 = fd0.duplicate(as: fd1, options: [.closeOnFork, .closeOnExec]) ``` -------------------------------- ### API definition for CInterop.stat back-deployment Source: https://github.com/apple/swift-system/blob/main/Proposals/0008-backdeploy-cinterop-stat.md The implementation of CInterop.Stat and CInterop.stat using @_alwaysEmitIntoClient to ensure availability on older OS versions. ```swift #if !os(Windows) @available(System 0.0.2, *) // Original availability of CInterop extension CInterop { public typealias Stat = stat @_alwaysEmitIntoClient public static func stat(_ path: UnsafePointer, _ s: inout CInterop.Stat) -> Int32 } #endif ``` -------------------------------- ### FileDescriptor and FilePath Stat Extensions Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Methods to retrieve file metadata from file descriptors or file paths, mapping to underlying C system calls. ```swift extension FileDescriptor { /// Creates a `Stat` struct for the file referenced by this `FileDescriptor`. /// /// The corresponding C function is `fstat()`. public func stat( retryOnInterrupt: Bool = true ) throws(Errno) -> Stat } extension FilePath { /// Creates a `Stat` struct for the file referenced by this `FilePath`. /// /// `followTargetSymlink` determines the behavior if `path` ends with a symbolic link. /// By default, `followTargetSymlink` is `true` and this initializer behaves like `stat()`. /// If `followTargetSymlink` is set to `false`, this initializer behaves like `lstat()` and /// returns information about the symlink itself. /// /// The corresponding C function is `stat()` or `lstat()` as described above. public func stat( followTargetSymlink: Bool = true, retryOnInterrupt: Bool = true ) throws(Errno) -> Stat /// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`. /// /// If `path` is relative, it is resolved against the current working directory. /// /// The corresponding C function is `fstatat()`. public func stat( flags: Stat.Flags, retryOnInterrupt: Bool = true ) throws(Errno) -> Stat /// Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`, /// including a `FileDescriptor` to resolve a relative path. /// /// If `path` is absolute (starts with a forward slash), then `fd` is ignored. /// If `path` is relative, it is resolved against the directory given by `fd`. /// /// The corresponding C function is `fstatat()`. public func stat( relativeTo fd: FileDescriptor, flags: Stat.Flags, retryOnInterrupt: Bool = true ) throws(Errno) -> Stat } ``` -------------------------------- ### FileDescriptor.pipe Source: https://github.com/apple/swift-system/blob/main/Proposals/0007-FileDescriptor-dup3-pipe2.md Creates a unidirectional data channel for interprocess communication using the `pipe2` C function. It returns a pair of file descriptors, one for reading and one for writing. ```APIDOC ## FileDescriptor.pipe ### Description Creates a unidirectional data channel, which can be used for interprocess communication. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method static func ### Endpoint N/A (SDK method) ### Returns - `(readEnd: FileDescriptor, writeEnd: FileDescriptor)`: The pair of file descriptors for the pipe. ### Throws - `Errno`: If the pipe creation fails. ### Options - `options`: `PipeOptions` - The behavior for creating the pipe. Possible values include `nonBlocking`, `closeOnExec`, and `closeOnFork`. ``` -------------------------------- ### FilePath Extensions for Stat Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Methods for retrieving `Stat` information using a `FilePath`. ```APIDOC ## FilePath Extensions ### Method 1 `func stat(followTargetSymlink: Bool = true, retryOnInterrupt: Bool = true) throws(Errno) -> Stat` ### Description Creates a `Stat` struct for the file referenced by this `FilePath`. `followTargetSymlink` determines behavior for symbolic links. Corresponds to C `stat()` or `lstat()`. ### Method 2 `func stat(flags: Stat.Flags, retryOnInterrupt: Bool = true) throws(Errno) -> Stat` ### Description Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`. Corresponds to C `fstatat()`. ### Method 3 `func stat(relativeTo fd: FileDescriptor, flags: Stat.Flags, retryOnInterrupt: Bool = true) throws(Errno) -> Stat` ### Description Creates a `Stat` struct for the file referenced by this `FilePath` using the given `Flags`, resolving relative paths against the provided `FileDescriptor`. Corresponds to C `fstatat()`. ``` -------------------------------- ### Define CInterop.stat extension Source: https://github.com/apple/swift-system/blob/main/Proposals/0008-backdeploy-cinterop-stat.md Provides a direct wrapper around the C stat system call for migration purposes on non-Windows platforms. ```swift #if !os(Windows) @available(System 0.0.2, *) // Original availability of CInterop extension CInterop { /// The C `stat` struct. public typealias Stat = stat /// Calls the C `stat()` function. /// /// This is a direct wrapper around the C `stat()` system call. /// For a more ergonomic Swift API, use `Stat` instead. /// /// - Warning: This API is primarily intended for migration purposes when /// supporting older deployment targets. If your deployment target supports /// it, prefer using the `Stat` API introduced in SYS-0006, which provides /// type-safe, ergonomic access to file metadata in Swift. /// /// - Parameters: /// - path: A null-terminated C string representing the file path. /// - s: An `inout` reference to a `CInterop.Stat` struct to populate. /// - Returns: 0 on success, -1 on error (check `Errno.current`). @_alwaysEmitIntoClient public static func stat(_ path: UnsafePointer, _ s: inout CInterop.Stat) -> Int32 { system_stat(path, &s) } } #endif ``` -------------------------------- ### FileFlags Static Properties Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md A collection of static properties for FileFlags representing file attributes such as read-only, offline, and system status. ```APIDOC ## FileFlags Static Properties ### Description Provides access to various file system flags used for compatibility and system-level file management. ### Properties - **userNoUnlink** (FileFlags) - Flag that may be changed by the file owner or superuser. - **offline** (FileFlags) - Corresponds to C constant `UF_OFFLINE`. Windows `FILE_ATTRIBUTE_OFFLINE` compatibility. - **readOnly** (FileFlags) - Corresponds to C constant `UF_READONLY`. Windows `FILE_ATTRIBUTE_READONLY` compatibility. - **reparse** (FileFlags) - Corresponds to C constant `UF_REPARSE`. Windows `FILE_ATTRIBUTE_REPARSE_POINT` compatibility. - **sparse** (FileFlags) - Corresponds to C constant `UF_SPARSE`. Windows `FILE_ATTRIBUTE_SPARSE_FILE` compatibility. - **system** (FileFlags) - Corresponds to C constant `UF_SYSTEM`. Windows `FILE_ATTRIBUTE_SYSTEM` compatibility. - **snapshot** (FileFlags) - Corresponds to C constant `SF_SNAPSHOT`. May only be changed by the superuser. ``` -------------------------------- ### Migrate FilePath.isRegularFile to the new Stat API Source: https://github.com/apple/swift-system/blob/main/Proposals/0008-backdeploy-cinterop-stat.md Use if #available to conditionally use the new Stat API while maintaining a fallback for older deployment targets. ```swift extension FilePath { func isRegularFile() throws -> Bool { if #available(macOS X, iOS Y, *) { return try stat().type == .regular // Calls FilePath.stat() } var s = CInterop.Stat() guard CInterop.stat(self.string, &s) == 0 else { throw Errno.current } return s.st_mode & S_IFMT == S_IFREG } } ``` -------------------------------- ### Stat Equatable and Hashable Conformance Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Implementations for comparing and hashing Stat structures based on raw bytes. ```swift // MARK: - Equatable and Hashable extension Stat: Equatable { /// Compares the raw bytes of two `Stat` structs for equality. public static func == (lhs: Self, rhs: Self) -> Bool } extension Stat: Hashable { /// Hashes the raw bytes of this `Stat` struct. public func hash(into hasher: inout Hasher) } ``` -------------------------------- ### Duplicate a File Descriptor with duplicate() Source: https://github.com/apple/swift-system/blob/main/Proposals/0007-FileDescriptor-dup3-pipe2.md Duplicates a file descriptor with specified target, options, and interrupt handling. Supports options like close-on-exec/fork and retries on interruption. ```swift @discardableResult public func duplicate( as target: FileDescriptor, options: DuplicateOptions, retryOnInterrupt: Bool = true ) throws(Errno) -> FileDescriptor ``` -------------------------------- ### FileMode Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md A strongly-typed file mode representing a C `mode_t`, allowing modification of type and permissions. ```APIDOC ## FileMode ### Description A strongly-typed file mode representing a C `mode_t`. The type and permissions of a `FileMode` can be modified for convenience, and `FileMode` handles the respective bit masking. - Note: Only available on Unix-like platforms. ### Initializers - `init(rawValue: CInterop.Mode)`: Creates a strongly-typed `FileMode` from the raw C value. - `init(_ rawValue: CInterop.Mode)`: Creates a strongly-typed `FileMode` from the raw C value. - `init(type: FileType, permissions: FilePermissions)`: Creates a `FileMode` from the given file type and permissions. This initializer masks the inputs with their respective bit masks. ### Properties - `rawValue: CInterop.Mode`: The raw C mode. - `type`: The file's type, from the mode's file-type bits. Setting this property will mask the `newValue` with the file-type bit mask `S_IFMT`. - `permissions`: The file's permissions, from the mode's permission bits. Setting this property will mask the `newValue` with the permissions bit mask `ALLPERMS`. ``` -------------------------------- ### Stat Struct Property Definitions Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Platform-specific properties for file metadata, including birth time, flags, and generation numbers. ```swift /// Time of file creation, given as a C `timespec` since the Epoch. /// /// The corresponding C property is `st_birthtim` (or `st_birthtimespec` on Darwin). /// - Note: Only available on Darwin and FreeBSD. public var st_birthtim: timespec { get set } #endif #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) /// File flags /// /// The corresponding C property is `st_flags`. /// - Note: Only available on Darwin, FreeBSD, and OpenBSD. public var flags: FileFlags { get set } /// File generation number /// /// The file generation number is used to distinguish between different files /// that have used the same inode over time. /// /// The corresponding C property is `st_gen`. /// - Note: Only available on Darwin, FreeBSD, and OpenBSD. public var generationNumber: Int { get set } #endif } ``` -------------------------------- ### FileFlags Type Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md This section details the FileFlags type, its properties, and available flags across different operating systems. ```APIDOC ## FileFlags A new `FileFlags` type represents file-specific flags found in a `stat` struct on Darwin, FreeBSD, and OpenBSD. This type would also be useful for an implementation of `chflags()`. ### Description File-specific flags found in the `st_flags` property of a `stat` struct or used as input to `chflags()`. - Note: Only available on Darwin, FreeBSD, and OpenBSD. ### Properties - `rawValue`: The raw C flags. ### Initializers - `init(rawValue: CInterop.FileFlags)`: Creates a strongly-typed `FileFlags` from the raw C value. ### Flags Available on Darwin, FreeBSD, and OpenBSD - `noDump`: Do not dump the file during backups. (C constant: `UF_NODUMP`) - Note: This flag may be changed by the file owner or superuser. - `userImmutable`: File may not be changed. (C constant: `UF_IMMUTABLE`) - Note: This flag may be changed by the file owner or superuser. - `userAppend`: Writes to the file may only append. (C constant: `UF_APPEND`) - Note: This flag may be changed by the file owner or superuser. - `archived`: File has been archived. (C constant: `SF_ARCHIVED`) - Note: This flag may only be changed by the superuser. - `systemImmutable`: File may not be changed. (C constant: `SF_IMMUTABLE`) - Note: This flag may only be changed by the superuser. - `systemAppend`: Writes to the file may only append. (C constant: `SF_APPEND`) - Note: This flag may only be changed by the superuser. ### Flags Available on Darwin and FreeBSD - `opaque`: Directory is opaque when viewed through a union mount. (C constant: `UF_OPAQUE`) - Note: This flag may be changed by the file owner or superuser. - `hidden`: File should not be displayed in a GUI. (C constant: `UF_HIDDEN`) - Note: This flag may be changed by the file owner or superuser. - `systemNoUnlink`: File may not be removed or renamed. (C constant: `SF_NOUNLINK`) - Note: This flag may only be changed by the superuser. ### Flags Available on Darwin only - `compressed`: File is compressed at the file system level. (C constant: `UF_COMPRESSED`) - Note: This flag is read-only. Attempting to change it will result in undefined behavior. - `tracked`: File is tracked for the purpose of document IDs. (C constant: `UF_TRACKED`) - Note: This flag may be changed by the file owner or superuser. - `dataVault`: File requires an entitlement for reading and writing. (C constant: `UF_DATAVAULT`) - Note: This flag may be changed by the file owner or superuser. - `restricted`: File requires an entitlement for writing. (C constant: `SF_RESTRICTED`) - Note: This flag may only be changed by the superuser. - `firmlink`: File is a firmlink. (C constant: `SF_FIRMLINK`) - Note: This flag may only be changed by the superuser. - `dataless`: File is a dataless placeholder (content is stored remotely). (C constant: `SF_DATALESS`) - Note: This flag is read-only. Attempting to change it will result in undefined behavior. ### Flags Available on FreeBSD Only - `userNoUnlink`: File may not be removed or renamed. (C constant: `UF_NOUNLINK`) ``` -------------------------------- ### Define FileFlags structure Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md The FileFlags struct conforms to OptionSet and provides access to platform-specific file flags via raw C values. ```swift /// File-specific flags found in the `st_flags` property of a `stat` struct /// or used as input to `chflags()`. /// /// - Note: Only available on Darwin, FreeBSD, and OpenBSD. @frozen public struct FileFlags: OptionSet, Sendable, Hashable, Codable { /// The raw C flags. public let rawValue: CInterop.FileFlags /// Creates a strongly-typed `FileFlags` from the raw C value. public init(rawValue: CInterop.FileFlags) // MARK: Flags Available on Darwin, FreeBSD, and OpenBSD /// Do not dump the file during backups. /// /// The corresponding C constant is `UF_NODUMP`. /// - Note: This flag may be changed by the file owner or superuser. public static var noDump: FileFlags { get } /// File may not be changed. /// /// The corresponding C constant is `UF_IMMUTABLE`. /// - Note: This flag may be changed by the file owner or superuser. public static var userImmutable: FileFlags { get } /// Writes to the file may only append. /// /// The corresponding C constant is `UF_APPEND`. /// - Note: This flag may be changed by the file owner or superuser. public static var userAppend: FileFlags { get } /// File has been archived. /// /// The corresponding C constant is `SF_ARCHIVED`. /// - Note: This flag may only be changed by the superuser. public static var archived: FileFlags { get } /// File may not be changed. /// /// The corresponding C constant is `SF_IMMUTABLE`. /// - Note: This flag may only be changed by the superuser. public static var systemImmutable: FileFlags { get } /// Writes to the file may only append. /// /// The corresponding C constant is `SF_APPEND`. /// - Note: This flag may only be changed by the superuser. public static var systemAppend: FileFlags { get } // MARK: Flags Available on Darwin and FreeBSD #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) /// Directory is opaque when viewed through a union mount. /// /// The corresponding C constant is `UF_OPAQUE`. /// - Note: This flag may be changed by the file owner or superuser. public static var opaque: FileFlags { get } /// File should not be displayed in a GUI. /// /// The corresponding C constant is `UF_HIDDEN`. /// - Note: This flag may be changed by the file owner or superuser. public static var hidden: FileFlags { get } /// File may not be removed or renamed. /// /// The corresponding C constant is `SF_NOUNLINK`. /// - Note: This flag may only be changed by the superuser. public static var systemNoUnlink: FileFlags { get } #endif // MARK: Flags Available on Darwin only #if SYSTEM_PACKAGE_DARWIN /// File is compressed at the file system level. /// /// The corresponding C constant is `UF_COMPRESSED`. /// - Note: This flag is read-only. Attempting to change it will result in undefined behavior. public static var compressed: FileFlags { get } /// File is tracked for the purpose of document IDs. /// /// The corresponding C constant is `UF_TRACKED`. /// - Note: This flag may be changed by the file owner or superuser. public static var tracked: FileFlags { get } /// File requires an entitlement for reading and writing. /// /// The corresponding C constant is `UF_DATAVAULT`. /// - Note: This flag may be changed by the file owner or superuser. public static var dataVault: FileFlags { get } /// File requires an entitlement for writing. /// /// The corresponding C constant is `SF_RESTRICTED`. /// - Note: This flag may only be changed by the superuser. public static var restricted: FileFlags { get } /// File is a firmlink. /// /// Firmlinks are used by macOS to create transparent links between /// the read-only system volume and writable data volume. For example, /// the `/Applications` folder on the system volume is a firmlink to /// the `/Applications` folder on the data volume, allowing the user /// to see both system- and user-installed applications in a single folder. /// /// The corresponding C constant is `SF_FIRMLINK`. /// - Note: This flag may only be changed by the superuser. public static var firmlink: FileFlags { get } /// File is a dataless placeholder (content is stored remotely). /// /// The system will attempt to materialize the file when accessed according to /// the dataless file materialization policy of the accessing thread or process. /// See `getiopolicy_np(3)`. /// /// The corresponding C constant is `SF_DATALESS`. /// - Note: This flag is read-only. Attempting to change it will result in undefined behavior. public static var dataless: FileFlags { get } #endif // MARK: Flags Available on FreeBSD Only #if os(FreeBSD) /// File may not be removed or renamed. /// /// The corresponding C constant is `UF_NOUNLINK`. ``` -------------------------------- ### FileDescriptor.duplicate Source: https://github.com/apple/swift-system/blob/main/Proposals/0007-FileDescriptor-dup3-pipe2.md Duplicates an existing file descriptor, creating a new reference to the same underlying system resource. This method corresponds to the `dup3` C function. ```APIDOC ## FileDescriptor.duplicate ### Description Duplicate this file descriptor and return the newly created copy. If the target descriptor is already in use, it is deallocated first. File descriptor flags like close-on-exec and close-on-fork are maintained separately. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method func ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters * **target** (`FileDescriptor`) - Required - The desired target file descriptor. #### Query Parameters None #### Request Body None ### Returns - `FileDescriptor`: The new file descriptor. ### Throws - `Errno`: If the duplication fails. ### Options - `options`: `DuplicateOptions` - The behavior for creating the target file descriptor. Possible values include `closeOnExec` and `closeOnFork`. - `retryOnInterrupt`: `Bool` - Whether to retry the operation if it throws `Errno.interrupted`. Defaults to `true`. ``` -------------------------------- ### Define FileMode Struct Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Represents a C `mode_t` in a strongly-typed manner. Only available on Unix-like platforms. It can be initialized from raw values or from a combination of FileType and FilePermissions. ```swift /// A strongly-typed file mode representing a C `mode_t`. /// /// - Note: Only available on Unix-like platforms. @frozen public struct FileMode: RawRepresentable, Sendable, Hashable, Codable { /// The raw C mode. public var rawValue: CInterop.Mode /// Creates a strongly-typed `FileMode` from the raw C value. public init(rawValue: CInterop.Mode) /// Creates a strongly-typed `FileMode` from the raw C value. public init(_ rawValue: CInterop.Mode) /// Creates a `FileMode` from the given file type and permissions. /// /// - Note: This initializer masks the inputs with their respective bit masks. public init(type: FileType, permissions: FilePermissions) /// The file's type, from the mode's file-type bits. /// /// Setting this property will mask the `newValue` with the file-type bit mask `S_IFMT`. public var type: FileType { get set } /// The file's permissions, from the mode's permission bits. /// /// Setting this property will mask the `newValue` with the permissions bit mask `ALLPERMS`. public var permissions: FilePermissions { get set } } ``` -------------------------------- ### FileDescriptor Extensions for Stat Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Methods for retrieving `Stat` information using a `FileDescriptor`. ```APIDOC ## FileDescriptor Extensions ### Method `func stat(retryOnInterrupt: Bool = true) throws(Errno) -> Stat` ### Description Creates a `Stat` struct for the file referenced by this `FileDescriptor`. Corresponds to the C `fstat()` function. ``` -------------------------------- ### Stat Properties Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Properties representing file metadata such as device ID, inode, permissions, and timestamps. ```APIDOC ## Stat Properties ### Metadata Properties - **deviceID** (DeviceID) - ID of device containing file. - **inode** (Inode) - Inode number. - **mode** (FileMode) - File mode. - **type** (FileType) - File type. - **permissions** (FilePermissions) - File permissions. - **linkCount** (Int) - Number of hard links. - **userID** (UserID) - User ID of owner. - **groupID** (GroupID) - Group ID of owner. - **specialDeviceID** (DeviceID) - Device ID for special files. - **size** (Int64) - Total size in bytes. - **preferredIOBlockSize** (Int) - Block size for filesystem I/O. - **blocksAllocated** (Int64) - Number of 512-byte blocks allocated. - **sizeAllocated** (Int64) - Total size allocated in bytes. ### Timestamp Properties - **st_atim** (timespec) - Time of last access. - **st_mtim** (timespec) - Time of last modification. - **st_ctim** (timespec) - Time of last status change. ``` -------------------------------- ### Define Inode Structure Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Defines a strongly-typed Inode struct conforming to RawRepresentable, Sendable, Hashable, and Codable. Use this for representing file system inode numbers. ```swift @frozen public struct Inode: RawRepresentable, Sendable, Hashable, Codable { public var rawValue: CInterop.Inode public init(rawValue: CInterop.Inode) public init(_ rawValue: CInterop.Inode) } ``` -------------------------------- ### Swift Stat Property Mappings Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Maps Swift Stat properties to their underlying C struct members across different operating systems. ```swift deviceID st_dev ``` ```swift inode st_ino ``` ```swift mode st_mode ``` ```swift linkCount st_nlink ``` ```swift userID st_uid ``` ```swift groupID st_gid ``` ```swift specialDeviceID st_rdev ``` ```swift size st_size ``` ```swift preferredIOBlockSize st_blksize ``` ```swift blocksAllocated st_blocks ``` ```swift st_atim st_atimespec ``` ```swift st_atim st_atim ``` ```swift st_mtim st_mtimespec ``` ```swift st_mtim st_mtim ``` ```swift st_ctim st_ctimespec ``` ```swift st_ctim st_ctim ``` ```swift st_birthtim st_birthtimespec ``` ```swift st_birthtim st_birthtim ``` ```swift flags st_flags ``` ```swift generationNumber st_gen ``` -------------------------------- ### Define FileType Enum Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Represents file types found in C `mode_t`. Only available on Unix-like platforms. The initializer stores the raw value directly and does not mask it with `S_IFMT`. ```swift /// A file type matching those contained in a C `mode_t`. /// /// - Note: Only available on Unix-like platforms. @frozen public struct FileType: RawRepresentable, Sendable, Hashable, Codable { /// The raw file-type bits from the C mode. public var rawValue: CInterop.Mode /// Creates a strongly-typed file type from the raw C `mode_t`. /// /// - Note: This initializer stores the `rawValue` directly and **does not** /// mask the value with `S_IFMT`. If the supplied `rawValue` contains bits /// outside of the `S_IFMT` mask, the resulting `FileType` will not compare /// equal to constants like `.directory` and `.symbolicLink`, which may /// be unexpected. /// /// If you're unsure whether the `mode_t` contains bits outside of `S_IFMT`, /// you can use `FileMode(rawValue:)` instead to get a strongly-typed /// `FileMode`, then call `.type` to get the properly masked `FileType`. public init(rawValue: CInterop.Mode) /// Directory /// /// The corresponding C constant is `S_IFDIR`. public static var directory: FileType { get } /// Character special device /// /// The corresponding C constant is `S_IFCHR`. public static var characterSpecial: FileType { get } /// Block special device /// /// The corresponding C constant is `S_IFBLK`. public static var blockSpecial: FileType { get } /// Regular file /// /// The corresponding C constant is `S_IFREG`. public static var regular: FileType { get } /// FIFO (or named pipe) /// /// The corresponding C constant is `S_IFIFO`. public static var fifo: FileType { get } /// Symbolic link /// /// The corresponding C constant is `S_IFLNK`. public static var symbolicLink: FileType { get } /// Socket /// /// The corresponding C constant is `S_IFSOCK`. public static var socket: FileType { get } #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) /// Whiteout file /// /// The corresponding C constant is `S_IFWHT`. public static var whiteout: FileType { get } #endif } ``` -------------------------------- ### FileType Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Represents file types similar to those in the C `mode_t` struct. It handles bit masking for file type identification. ```APIDOC ## FileType ### Description A file type matching those contained in a C `mode_t`. - Note: Only available on Unix-like platforms. ### Initializers - `init(rawValue: CInterop.Mode)`: Creates a strongly-typed file type from the raw C `mode_t`. This initializer stores the `rawValue` directly and **does not** mask the value with `S_IFMT`. If the supplied `rawValue` contains bits outside of the `S_IFMT` mask, the resulting `FileType` will not compare equal to constants like `.directory` and `.symbolicLink`, which may be unexpected. If you're unsure whether the `mode_t` contains bits outside of `S_IFMT`, you can use `FileMode(rawValue:)` instead to get a strongly-typed `FileMode`, then call `.type` to get the properly masked `FileType`. ### Properties - `rawValue: CInterop.Mode`: The raw file-type bits from the C mode. ### Static Properties - `directory`: Directory. The corresponding C constant is `S_IFDIR`. - `characterSpecial`: Character special device. The corresponding C constant is `S_IFCHR`. - `blockSpecial`: Block special device. The corresponding C constant is `S_IFBLK`. - `regular`: Regular file. The corresponding C constant is `S_IFREG`. - `fifo`: FIFO (or named pipe). The corresponding C constant is `S_IFIFO`. - `symbolicLink`: Symbolic link. The corresponding C constant is `S_IFLNK`. - `socket`: Socket. The corresponding C constant is `S_IFSOCK`. - `whiteout`: Whiteout file. The corresponding C constant is `S_IFWHT`. (Available on `SYSTEM_PACKAGE_DARWIN` or `os(FreeBSD)`) ``` -------------------------------- ### Define DeviceID Structure Source: https://github.com/apple/swift-system/blob/main/Proposals/0006-system-stat.md Defines a strongly-typed DeviceID struct conforming to RawRepresentable, Sendable, Hashable, and Codable. Use this for representing device identifiers, enabling future functionality like makedev. ```swift @frozen public struct DeviceID: RawRepresentable, Sendable, Hashable, Codable { public var rawValue: CInterop.DeviceID public init(rawValue: CInterop.DeviceID) public init(_ rawValue: CInterop.DeviceID) } ```