WIP: Implement more of File

This commit is contained in:
Sami Samhuri 2025-08-28 08:52:26 -07:00
parent ab21045498
commit 993cc73ec0
No known key found for this signature in database
11 changed files with 925 additions and 543 deletions

View file

@ -98,7 +98,7 @@ public extension Dir {
try FileManager.default.createDirectory(
at: url,
withIntermediateDirectories: false,
attributes: attributes
attributes: attributes,
)
}
@ -110,7 +110,7 @@ public extension Dir {
try FileManager.default.createDirectory(
at: tmpDir,
withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700]
attributes: [.posixPermissions: 0o700],
)
return tmpDir
}
@ -119,7 +119,7 @@ public extension Dir {
static func mktmpdir<T>(
prefix: String = "d",
suffix: String = "",
_ block: (URL) throws -> T
_ block: (URL) throws -> T,
) throws -> T {
let tmpDir = try mktmpdir(prefix: prefix, suffix: suffix)
defer {

View file

@ -5,6 +5,7 @@
// Created by Sami Samhuri on 2025-08-19.
//
import Darwin
import Foundation
// MARK: - File Class
@ -19,21 +20,21 @@ public class File: CustomStringConvertible, CustomDebugStringConvertible {
// MARK: - Mode
public enum Mode {
case read // r
case write // w
case append // a
case readWrite // r+
case readWriteNew // w+
case readAppend // a+
case read // r
case write // w
case append // a
case readWrite // r+
case readWriteNew // w+
case readAppend // a+
case writeExclusive // wx (create, fail if exists)
}
// MARK: - Initialization
public init(url: URL, mode: Mode = .read, permissions: Int = 0o666) throws {
public init(url: URL, mode: Mode = .read, permissions _: Int = 0o666) throws {
self.url = url
self.mode = mode
self.handle = FileHandle() // TODO: Implement proper opening
handle = FileHandle() // TODO: Implement proper opening
fatalError("Not implemented")
}
@ -43,12 +44,12 @@ public class File: CustomStringConvertible, CustomDebugStringConvertible {
// MARK: - Opening with blocks
public static func open(url: URL, mode: Mode = .read, permissions: Int = 0o666) throws -> File {
public static func open(url _: URL, mode _: Mode = .read, permissions _: Int = 0o666) throws -> File {
fatalError("Not implemented")
}
@discardableResult
public static func open<T>(url: URL, mode: Mode = .read, permissions: Int = 0o666, _ block: (File) throws -> T) rethrows -> T {
public static func open<T>(url _: URL, mode _: Mode = .read, permissions _: Int = 0o666, _: (File) throws -> T) rethrows -> T {
fatalError("Not implemented")
}
@ -76,27 +77,27 @@ public class File: CustomStringConvertible, CustomDebugStringConvertible {
// MARK: - Instance Methods
public func chmod(_ permissions: Int) throws {
public func chmod(_: Int) throws {
fatalError("Not implemented")
}
public func chown(owner: Int? = nil, group: Int? = nil) throws {
public func chown(owner _: Int? = nil, group _: Int? = nil) throws {
fatalError("Not implemented")
}
public func truncate(to size: Int) throws {
public func truncate(to _: Int) throws {
fatalError("Not implemented")
}
public func flock(_ operation: LockOperation) throws {
public func flock(_: LockOperation) throws {
fatalError("Not implemented")
}
public func stat() throws -> FileStat {
public func fileStat() throws -> FileStat {
fatalError("Not implemented")
}
public func lstat() throws -> FileStat {
public func fileLstat() throws -> FileStat {
fatalError("Not implemented")
}
@ -128,7 +129,7 @@ public extension File {
let base = url.lastPathComponent
// If no suffix specified, return the base
guard let suffix = suffix else {
guard let suffix else {
return base
}
@ -149,7 +150,7 @@ public extension File {
static func dirname(_ url: URL, level: Int = 1) -> URL {
var result = url
for _ in 0..<level where result.path != "/" {
for _ in 0 ..< level where result.path != "/" {
result = result.deletingLastPathComponent()
}
return result
@ -199,20 +200,59 @@ public extension File {
return result
}
static func absolutePath(_ url: URL, relativeTo base: URL? = nil) -> URL {
fatalError("Not implemented")
static func absolutePath(_ url: URL) -> URL {
// URL(fileURLWithPath:) already makes relative paths absolute using current directory
// We just need to normalize the path (resolves . and .. but NOT symlinks)
url.standardized
}
static func expandPath(_ path: String) -> URL {
fatalError("Not implemented")
// Expand tilde to home directory
let expanded = (path as NSString).expandingTildeInPath
return URL(fileURLWithPath: expanded)
}
static func realpath(_ url: URL) throws -> URL {
fatalError("Not implemented")
// Resolve all symbolic links in the path
// All components must exist for this to work
let path = url.path
// Check if file exists
guard FileManager.default.fileExists(atPath: path) else {
throw CocoaError(.fileNoSuchFile, userInfo: [NSFilePathErrorKey: path])
}
// Use standardizedFileURL to resolve symlinks and normalize the path
// This resolves .., ., and symlinks
return url.resolvingSymlinksInPath()
}
static func realdirpath(_ url: URL) throws -> URL {
fatalError("Not implemented")
// Similar to realpath but the last component may not exist
let parentURL = url.deletingLastPathComponent()
let lastComponent = url.lastPathComponent
// If we're at root or parent doesn't exist, just standardize
if parentURL.path == "/" || parentURL.path.isEmpty {
return url.standardizedFileURL
}
// Check if the full path exists (including the last component)
if FileManager.default.fileExists(atPath: url.path) {
// If the full path exists, resolve all symlinks
return url.resolvingSymlinksInPath()
}
// Only the parent needs to exist, last component may not
let resolvedParent: URL = if FileManager.default.fileExists(atPath: parentURL.path) {
parentURL.resolvingSymlinksInPath()
} else {
// Parent doesn't exist, try to resolve what we can recursively
try realdirpath(parentURL)
}
// Append the last component (which may not exist)
return resolvedParent.appendingPathComponent(lastComponent)
}
}
@ -271,12 +311,56 @@ public extension File {
return fileSize.intValue
}
static func stat(_ url: URL) throws -> FileStat {
fatalError("Not implemented")
static func fileStatus(_ url: URL) throws -> FileStat {
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else {
throw CocoaError(.fileReadUnknown, userInfo: [NSFilePathErrorKey: url.path])
}
return FileStat(
dev: Int(statBuf.st_dev),
ino: Int(statBuf.st_ino),
mode: Int(statBuf.st_mode),
nlink: Int(statBuf.st_nlink),
uid: Int(statBuf.st_uid),
gid: Int(statBuf.st_gid),
rdev: Int(statBuf.st_rdev),
size: Int64(statBuf.st_size),
blksize: Int(statBuf.st_blksize),
blocks: Int64(statBuf.st_blocks),
atime: Date(timeIntervalSince1970: TimeInterval(statBuf.st_atimespec.tv_sec)),
mtime: Date(timeIntervalSince1970: TimeInterval(statBuf.st_mtimespec.tv_sec)),
ctime: Date(timeIntervalSince1970: TimeInterval(statBuf.st_ctimespec.tv_sec)),
birthtime: Date(timeIntervalSince1970: TimeInterval(statBuf.st_birthtimespec.tv_sec)),
)
}
static func lstat(_ url: URL) throws -> FileStat {
fatalError("Not implemented")
static func linkStatus(_ url: URL) throws -> FileStat {
var statBuf = stat()
let result = url.path.withCString { lstat($0, &statBuf) }
guard result == 0 else {
throw CocoaError(.fileReadUnknown, userInfo: [NSFilePathErrorKey: url.path])
}
return FileStat(
dev: Int(statBuf.st_dev),
ino: Int(statBuf.st_ino),
mode: Int(statBuf.st_mode),
nlink: Int(statBuf.st_nlink),
uid: Int(statBuf.st_uid),
gid: Int(statBuf.st_gid),
rdev: Int(statBuf.st_rdev),
size: Int64(statBuf.st_size),
blksize: Int(statBuf.st_blksize),
blocks: Int64(statBuf.st_blocks),
atime: Date(timeIntervalSince1970: TimeInterval(statBuf.st_atimespec.tv_sec)),
mtime: Date(timeIntervalSince1970: TimeInterval(statBuf.st_mtimespec.tv_sec)),
ctime: Date(timeIntervalSince1970: TimeInterval(statBuf.st_ctimespec.tv_sec)),
birthtime: Date(timeIntervalSince1970: TimeInterval(statBuf.st_birthtimespec.tv_sec)),
)
}
}
@ -300,27 +384,42 @@ public extension File {
}
static func isSymlink(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { lstat($0, &statBuf) }
guard result == 0 else { return false }
return (statBuf.st_mode & S_IFMT) == S_IFLNK
}
static func isBlockDevice(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return false }
return (statBuf.st_mode & S_IFMT) == S_IFBLK
}
static func isCharDevice(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return false }
return (statBuf.st_mode & S_IFMT) == S_IFCHR
}
static func isPipe(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return false }
return (statBuf.st_mode & S_IFMT) == S_IFIFO
}
static func isSocket(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return false }
return (statBuf.st_mode & S_IFMT) == S_IFSOCK
}
static func isEmpty(_ url: URL) throws -> Bool {
let size = try self.size(url)
let size = try size(url)
return size == 0
}
@ -334,66 +433,97 @@ public extension File {
public extension File {
static func isReadable(_ url: URL) -> Bool {
fatalError("Not implemented")
url.path.withCString { access($0, R_OK) } == 0
}
static func isWritable(_ url: URL) -> Bool {
fatalError("Not implemented")
url.path.withCString { access($0, W_OK) } == 0
}
static func isExecutable(_ url: URL) -> Bool {
fatalError("Not implemented")
url.path.withCString { access($0, X_OK) } == 0
}
static func isOwned(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return false }
return statBuf.st_uid == getuid()
}
static func isGroupOwned(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return false }
return statBuf.st_gid == getgid()
}
static func isWorldReadable(_ url: URL) -> Int? {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return nil }
// Check if world readable (other read bit)
if (statBuf.st_mode & S_IROTH) != 0 {
return Int(statBuf.st_mode & 0o777)
}
return nil
}
static func isWorldWritable(_ url: URL) -> Int? {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return nil }
// Check if world writable (other write bit)
if (statBuf.st_mode & S_IWOTH) != 0 {
return Int(statBuf.st_mode & 0o777)
}
return nil
}
static func isSetuid(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return false }
return (statBuf.st_mode & S_ISUID) != 0
}
static func isSetgid(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return false }
return (statBuf.st_mode & S_ISGID) != 0
}
static func isSticky(_ url: URL) -> Bool {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { stat($0, &statBuf) }
guard result == 0 else { return false }
return (statBuf.st_mode & S_ISVTX) != 0
}
}
// MARK: - Static File Operations
public extension File {
static func chmod(_ url: URL, permissions: Int) throws {
static func chmod(_: URL, permissions _: Int) throws {
fatalError("Not implemented")
}
static func chown(_ url: URL, owner: Int? = nil, group: Int? = nil) throws {
static func chown(_: URL, owner _: Int? = nil, group _: Int? = nil) throws {
fatalError("Not implemented")
}
static func lchmod(_ url: URL, permissions: Int) throws {
static func lchmod(_: URL, permissions _: Int) throws {
fatalError("Not implemented")
}
static func lchown(_ url: URL, owner: Int? = nil, group: Int? = nil) throws {
static func lchown(_: URL, owner _: Int? = nil, group _: Int? = nil) throws {
fatalError("Not implemented")
}
static func link(source: URL, destination: URL) throws {
static func link(source _: URL, destination _: URL) throws {
fatalError("Not implemented")
}
@ -418,11 +548,11 @@ public extension File {
// Use replaceItem - it works whether destination exists or not
// and provides atomic replacement when it does exist
_ = try FileManager.default.replaceItem(
at: destination, withItemAt: source, backupItemName: nil, resultingItemURL: nil
at: destination, withItemAt: source, backupItemName: nil, resultingItemURL: nil,
)
}
static func truncate(_ url: URL, to size: Int) throws {
static func truncate(_: URL, to _: Int) throws {
fatalError("Not implemented")
}
@ -438,19 +568,19 @@ public extension File {
}
}
static func utime(_ url: URL, atime: Date, mtime: Date) throws {
static func utime(_: URL, atime _: Date, mtime _: Date) throws {
fatalError("Not implemented")
}
static func lutime(_ url: URL, atime: Date, mtime: Date) throws {
static func lutime(_: URL, atime _: Date, mtime _: Date) throws {
fatalError("Not implemented")
}
static func mkfifo(_ url: URL, permissions: Int = 0o666) throws {
static func mkfifo(_: URL, permissions _: Int = 0o666) throws {
fatalError("Not implemented")
}
static func identical(_ url1: URL, _ url2: URL) throws -> Bool {
static func identical(_: URL, _: URL) throws -> Bool {
fatalError("Not implemented")
}
@ -458,7 +588,7 @@ public extension File {
fatalError("Not implemented")
}
static func umask(_ mask: Int) -> Int {
static func umask(_: Int) -> Int {
fatalError("Not implemented")
}
}
@ -466,7 +596,7 @@ public extension File {
// MARK: - Pattern Matching
public extension File {
static func fnmatch(pattern: String, path: String, flags: FnmatchFlags = []) -> Bool {
static func fnmatch(pattern _: String, path _: String, flags _: FnmatchFlags = []) -> Bool {
fatalError("Not implemented")
}
}
@ -474,20 +604,20 @@ public extension File {
// MARK: - Supporting Types
public struct FileStat {
public let dev: Int // Device ID
public let ino: Int // Inode number
public let mode: Int // File mode (permissions + type)
public let nlink: Int // Number of hard links
public let uid: Int // User ID of owner
public let gid: Int // Group ID of owner
public let rdev: Int // Device ID (if special file)
public let size: Int64 // Total size in bytes
public let blksize: Int // Block size for filesystem I/O
public let blocks: Int64 // Number of 512B blocks allocated
public let atime: Date // Last access time
public let mtime: Date // Last modification time
public let ctime: Date // Last status change time
public let birthtime: Date? // Creation time (if available)
public let dev: Int // Device ID
public let ino: Int // Inode number
public let mode: Int // File mode (permissions + type)
public let nlink: Int // Number of hard links
public let uid: Int // User ID of owner
public let gid: Int // Group ID of owner
public let rdev: Int // Device ID (if special file)
public let size: Int64 // Total size in bytes
public let blksize: Int // Block size for filesystem I/O
public let blocks: Int64 // Number of 512B blocks allocated
public let atime: Date // Last access time
public let mtime: Date // Last modification time
public let ctime: Date // Last status change time
public let birthtime: Date? // Creation time (if available)
}
public struct FnmatchFlags: OptionSet {
@ -497,36 +627,57 @@ public struct FnmatchFlags: OptionSet {
self.rawValue = rawValue
}
public static let pathname = FnmatchFlags(rawValue: 1 << 0) // FNM_PATHNAME
public static let noescape = FnmatchFlags(rawValue: 1 << 1) // FNM_NOESCAPE
public static let period = FnmatchFlags(rawValue: 1 << 2) // FNM_PERIOD
public static let casefold = FnmatchFlags(rawValue: 1 << 3) // FNM_CASEFOLD
public static let extglob = FnmatchFlags(rawValue: 1 << 4) // FNM_EXTGLOB
public static let dotmatch = FnmatchFlags(rawValue: 1 << 5) // FNM_DOTMATCH (custom)
public static let pathname = FnmatchFlags(rawValue: 1 << 0) // FNM_PATHNAME
public static let noescape = FnmatchFlags(rawValue: 1 << 1) // FNM_NOESCAPE
public static let period = FnmatchFlags(rawValue: 1 << 2) // FNM_PERIOD
public static let casefold = FnmatchFlags(rawValue: 1 << 3) // FNM_CASEFOLD
public static let extglob = FnmatchFlags(rawValue: 1 << 4) // FNM_EXTGLOB
public static let dotmatch = FnmatchFlags(rawValue: 1 << 5) // FNM_DOTMATCH (custom)
}
public enum LockOperation {
case shared // LOCK_SH
case exclusive // LOCK_EX
case unlock // LOCK_UN
case nonBlocking // LOCK_NB (can be OR'd with others)
case shared // LOCK_SH
case exclusive // LOCK_EX
case unlock // LOCK_UN
case nonBlocking // LOCK_NB (can be OR'd with others)
}
// MARK: - File Type enum
public enum FileType: String {
case file = "file"
case directory = "directory"
case characterSpecial = "characterSpecial"
case blockSpecial = "blockSpecial"
case fifo = "fifo"
case link = "link"
case socket = "socket"
case unknown = "unknown"
case file
case directory
case characterSpecial
case blockSpecial
case fifo
case link
case socket
case unknown
}
public extension File {
static func ftype(_ url: URL) -> FileType {
fatalError("Not implemented")
var statBuf = stat()
let result = url.path.withCString { lstat($0, &statBuf) }
guard result == 0 else { return .unknown }
switch statBuf.st_mode & S_IFMT {
case S_IFREG:
return .file
case S_IFDIR:
return .directory
case S_IFLNK:
return .link
case S_IFBLK:
return .blockSpecial
case S_IFCHR:
return .characterSpecial
case S_IFIFO:
return .fifo
case S_IFSOCK:
return .socket
default:
return .unknown
}
}
}

View file

@ -79,7 +79,7 @@ func globstar(_ pattern: String, base: URL? = nil) -> [String] {
seenDirs.insert(key)
if isDir(dirPath) {
let dirPathNS = dirPath as NSString // Cache the NSString conversion
let dirPathNS = dirPath as NSString // Cache the NSString conversion
for entry in listDir(dirPath) {
let child = dirPathNS.appendingPathComponent(entry)
if isDir(child) {
@ -102,7 +102,7 @@ func globstar(_ pattern: String, base: URL? = nil) -> [String] {
// Segment glob (*, ?, []) matches names in this directory level only
let dirPath = base.isEmpty ? "/" : base
if !isDir(dirPath) { return }
let dirPathNS = dirPath as NSString // Cache the NSString conversion
let dirPathNS = dirPath as NSString // Cache the NSString conversion
for entry in listDir(dirPath) {
if matchSegment(entry, pat: part) {
let next = dirPathNS.appendingPathComponent(entry)

View file

@ -1,5 +1,5 @@
//
// FileOtterTests.swift
// DirTests.swift
// FileOtterTests
//
// Created by Sami Samhuri on 2024-04-24.
@ -145,7 +145,7 @@ final class DirTests: XCTestCase {
let children = try Dir.children(tempDir)
XCTAssertEqual(children.count, 3)
let childNames = children.map { $0.lastPathComponent }.sorted()
let childNames = children.map(\.lastPathComponent).sorted()
XCTAssertEqual(childNames, ["file1.txt", "file2.txt", "subdir"])
}
@ -240,7 +240,7 @@ final class DirTests: XCTestCase {
let results = Dir.glob(base: tempDir, "*.txt")
XCTAssertEqual(results.count, 2)
let filenames = results.map { $0.lastPathComponent }.sorted()
let filenames = results.map(\.lastPathComponent).sorted()
XCTAssertEqual(filenames, ["file1.txt", "file2.txt"])
}
@ -266,7 +266,7 @@ final class DirTests: XCTestCase {
let results = Dir.glob(base: tempDir, "??.txt")
XCTAssertEqual(results.count, 2)
let filenames = results.map { $0.lastPathComponent }.sorted()
let filenames = results.map(\.lastPathComponent).sorted()
XCTAssertEqual(filenames, ["a1.txt", "b2.txt"])
}
@ -464,7 +464,7 @@ final class DirTests: XCTestCase {
XCTAssertEqual(result, "block result")
XCTAssertTrue(fileCreated)
if let tmpDirInBlock = tmpDirInBlock {
if let tmpDirInBlock {
XCTAssertFalse(FileManager.default.fileExists(atPath: tmpDirInBlock.path))
}
}

View file

@ -9,7 +9,6 @@
import XCTest
final class FileFnmatchTests: XCTestCase {
// MARK: - Basic Pattern Tests
func testExactMatch() throws {

View file

@ -104,22 +104,56 @@ final class FileInfoTests: XCTestCase {
// MARK: - Stat Tests
func testStat() throws {
// TODO: Implement
// File.stat(url) returns FileStat object
let stat = try File.fileStatus(testFile)
// Verify basic properties
XCTAssertGreaterThan(stat.ino, 0) // inode should be positive
XCTAssertGreaterThan(stat.uid, 0) // uid should be positive
XCTAssertGreaterThan(stat.gid, 0) // gid should be positive
XCTAssertEqual(stat.size, 12) // "Test content" is 12 bytes
// Verify times are reasonable
XCTAssertLessThan(Date().timeIntervalSince(stat.mtime), 3600)
XCTAssertLessThan(Date().timeIntervalSince(stat.atime), 3600)
XCTAssertNotNil(stat.birthtime)
}
func testStatThrowsForNonExistent() throws {
// TODO: Implement
let nonExistent = tempDir.appendingPathComponent("nonexistent")
XCTAssertThrowsError(try File.fileStatus(nonExistent))
}
func testLstat() throws {
// TODO: Implement
// File.lstat(url) doesn't follow symlinks
// For regular files, lstat should be same as stat
let lstat = try File.linkStatus(testFile)
let stat = try File.fileStatus(testFile)
XCTAssertEqual(lstat.size, stat.size)
XCTAssertEqual(lstat.ino, stat.ino)
XCTAssertEqual(lstat.mode, stat.mode)
}
func testLstatForSymlink() throws {
// TODO: Implement
// Create symlink and verify lstat returns symlink stats, not target
// Create a larger target file
let targetFile = tempDir.appendingPathComponent("target.txt")
let targetContent = "This is the target file content"
try targetContent.write(to: targetFile, atomically: true, encoding: .utf8)
// Create symlink
let symlinkURL = tempDir.appendingPathComponent("symlink.txt")
try FileManager.default.createSymbolicLink(at: symlinkURL, withDestinationURL: targetFile)
let lstat = try File.linkStatus(symlinkURL)
let stat = try File.fileStatus(symlinkURL)
// lstat should return symlink's own stats (smaller size)
// stat should follow the symlink to the target (larger size)
XCTAssertNotEqual(lstat.size, stat.size)
XCTAssertEqual(stat.size, Int64(targetContent.data(using: .utf8)!.count))
// lstat should indicate it's a symlink via mode
let isLink = (lstat.mode & 0o170000) == 0o120000 // S_IFLNK
XCTAssertTrue(isLink)
}
// MARK: - Instance Method Tests

View file

@ -10,14 +10,17 @@ import XCTest
final class FilePathTests: XCTestCase {
var tempDir: URL!
var originalWorkingDirectory: String!
override func setUpWithError() throws {
originalWorkingDirectory = FileManager.default.currentDirectoryPath
tempDir = URL.temporaryDirectory
.appendingPathComponent("FilePathTests-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
}
override func tearDownWithError() throws {
FileManager.default.changeCurrentDirectoryPath(originalWorkingDirectory)
if FileManager.default.fileExists(atPath: tempDir.path) {
try FileManager.default.removeItem(at: tempDir)
}
@ -82,7 +85,7 @@ final class FilePathTests: XCTestCase {
XCTAssertEqual(File.dirname(url, level: 2).path(), "/Users/sjs/")
XCTAssertEqual(File.dirname(url, level: 3).path(), "/Users/")
XCTAssertEqual(File.dirname(url, level: 4).path(), "/")
XCTAssertEqual(File.dirname(url, level: 5).path(), "/") // Can't go beyond root
XCTAssertEqual(File.dirname(url, level: 5).path(), "/") // Can't go beyond root
}
// MARK: - extname Tests
@ -162,45 +165,110 @@ final class FilePathTests: XCTestCase {
// MARK: - absolutePath Tests
func testAbsolutePath() throws {
// TODO: Implement
// Converts relative to absolute
// Test already absolute path
let absoluteURL = URL(fileURLWithPath: "/usr/bin/swift")
XCTAssertEqual(File.absolutePath(absoluteURL).path, "/usr/bin/swift")
// Test relative path - URL constructor will use current directory
FileManager.default.changeCurrentDirectoryPath(tempDir.path)
let relativeURL = URL(fileURLWithPath: "file.txt")
let absPath = File.absolutePath(relativeURL)
// The URL is already absolute at this point, we just normalize it
XCTAssertTrue(absPath.path.hasSuffix("file.txt"))
XCTAssertTrue(absPath.path.hasPrefix("/"))
}
func testAbsolutePathWithBase() throws {
// TODO: Implement
func testAbsolutePathNormalization() throws {
// Test that .. and . are resolved
let pathWithDots = URL(fileURLWithPath: "/usr/../bin/./swift")
XCTAssertEqual(File.absolutePath(pathWithDots).path, "/bin/swift")
// Test multiple .. segments
let pathWithMultipleDots = URL(fileURLWithPath: "/usr/local/../../bin")
XCTAssertEqual(File.absolutePath(pathWithMultipleDots).path, "/bin")
// Test trailing slash removal
let pathWithTrailingSlash = URL(fileURLWithPath: "/usr/bin/")
XCTAssertEqual(File.absolutePath(pathWithTrailingSlash).path, "/usr/bin")
}
// MARK: - expandPath Tests
func testExpandPath() throws {
// TODO: Implement
// File.expandPath("~") => home directory
// File.expandPath("~/Documents") => home/Documents
}
let homeDir = FileManager.default.homeDirectoryForCurrentUser
func testExpandPathWithRelative() throws {
// TODO: Implement
// Test expanding ~
let expanded1 = File.expandPath("~")
XCTAssertEqual(expanded1.path, homeDir.path)
// Test expanding ~/Documents
let expanded2 = File.expandPath("~/Documents")
XCTAssertEqual(expanded2.path, homeDir.appendingPathComponent("Documents").path)
// Test regular path (no expansion needed)
let expanded3 = File.expandPath("/usr/bin")
XCTAssertEqual(expanded3.path, "/usr/bin")
}
// MARK: - realpath Tests
func testRealpath() throws {
// TODO: Implement
// Resolves symlinks, all components must exist
// Create a real file
let fileURL = tempDir.appendingPathComponent("realfile.txt")
try "test content".write(to: fileURL, atomically: true, encoding: .utf8)
// Test resolving a real file
let resolved = try File.realpath(fileURL)
XCTAssertEqual(resolved.path, fileURL.path)
// Create a symlink
let symlinkURL = tempDir.appendingPathComponent("symlink.txt")
try FileManager.default.createSymbolicLink(at: symlinkURL, withDestinationURL: fileURL)
// Test resolving symlink
let resolvedSymlink = try File.realpath(symlinkURL)
XCTAssertEqual(resolvedSymlink.path, fileURL.path)
}
func testRealpathThrowsForNonExistent() throws {
// TODO: Implement
let nonExistentURL = tempDir.appendingPathComponent("nonexistent.txt")
XCTAssertThrowsError(try File.realpath(nonExistentURL)) { error in
// Should throw file not found error
let nsError = error as NSError
XCTAssertEqual(nsError.domain, NSCocoaErrorDomain)
XCTAssertEqual(nsError.code, CocoaError.fileNoSuchFile.rawValue)
}
}
// MARK: - realdirpath Tests
func testRealdirpath() throws {
// TODO: Implement
// Resolves symlinks, last component may not exist
// Create a directory
let dirURL = tempDir.appendingPathComponent("realdir")
try FileManager.default.createDirectory(at: dirURL, withIntermediateDirectories: true)
// Test resolving existing directory
let resolved = try File.realdirpath(dirURL)
XCTAssertEqual(resolved.path, dirURL.path)
// Create a symlink to the directory
let symlinkDirURL = tempDir.appendingPathComponent("symlinkdir")
try FileManager.default.createSymbolicLink(at: symlinkDirURL, withDestinationURL: dirURL)
// Test resolving symlinked directory
let resolvedSymlink = try File.realdirpath(symlinkDirURL)
XCTAssertEqual(resolvedSymlink.path, dirURL.path)
}
func testRealdirpathWithNonExistentLast() throws {
// TODO: Implement
// Create a real directory
let dirURL = tempDir.appendingPathComponent("realdir")
try FileManager.default.createDirectory(at: dirURL, withIntermediateDirectories: true)
// Test with non-existent file in existing directory
let nonExistentFile = dirURL.appendingPathComponent("future-file.txt")
let resolved = try File.realdirpath(nonExistentFile)
XCTAssertEqual(resolved.path, nonExistentFile.path)
}
}

View file

@ -38,74 +38,151 @@ final class FilePermissionTests: XCTestCase {
// MARK: - Basic Permission Tests
func testIsReadable() throws {
// TODO: Implement
// File.isReadable(url) returns true for readable files
// Normal files should be readable
XCTAssertTrue(File.isReadable(testFile))
// System files are generally readable
XCTAssertTrue(File.isReadable(URL(fileURLWithPath: "/etc/hosts")))
// Non-existent files are not readable
let nonExistent = tempDir.appendingPathComponent("nonexistent")
XCTAssertFalse(File.isReadable(nonExistent))
}
func testIsWritable() throws {
// TODO: Implement
// File.isWritable(url) returns true for writable files
// Files we created should be writable
XCTAssertTrue(File.isWritable(testFile))
// System files are generally not writable
XCTAssertFalse(File.isWritable(URL(fileURLWithPath: "/etc/hosts")))
// Non-existent files are not writable
let nonExistent = tempDir.appendingPathComponent("nonexistent")
XCTAssertFalse(File.isWritable(nonExistent))
}
func testIsExecutable() throws {
// TODO: Implement
// File.isExecutable(url) returns true for executable files
// Make the script executable
try FileManager.default.setAttributes(
[.posixPermissions: 0o755],
ofItemAtPath: executableFile.path,
)
XCTAssertTrue(File.isExecutable(executableFile))
// System executables
XCTAssertTrue(File.isExecutable(URL(fileURLWithPath: "/bin/ls")))
XCTAssertTrue(File.isExecutable(URL(fileURLWithPath: "/usr/bin/swift")))
}
func testIsExecutableForNonExecutable() throws {
// TODO: Implement
// File.isExecutable(url) returns false for non-executable
// Regular text files are not executable
XCTAssertFalse(File.isExecutable(testFile))
XCTAssertFalse(File.isExecutable(readOnlyFile))
// Non-existent files are not executable
let nonExistent = tempDir.appendingPathComponent("nonexistent")
XCTAssertFalse(File.isExecutable(nonExistent))
}
// MARK: - Ownership Tests
func testIsOwned() throws {
// TODO: Implement
// File.isOwned(url) returns true for files owned by effective user
// Files we create should be owned by us
XCTAssertTrue(File.isOwned(testFile))
XCTAssertTrue(File.isOwned(readOnlyFile))
XCTAssertTrue(File.isOwned(executableFile))
// System files may not be owned by us
// This depends on the user running the test
}
func testIsGroupOwned() throws {
// TODO: Implement
// File.isGroupOwned(url) returns true for files owned by effective group
// Files we create should be owned by our effective group
XCTAssertTrue(File.isGroupOwned(testFile))
XCTAssertTrue(File.isGroupOwned(readOnlyFile))
XCTAssertTrue(File.isGroupOwned(executableFile))
}
// MARK: - World Permission Tests
func testIsWorldReadable() throws {
// TODO: Implement
// File.isWorldReadable(url) returns permission bits if world readable
// Make file world readable
try FileManager.default.setAttributes(
[.posixPermissions: 0o644],
ofItemAtPath: testFile.path,
)
let perms = File.isWorldReadable(testFile)
XCTAssertNotNil(perms)
if let perms {
XCTAssertEqual(perms & 0o004, 0o004) // Check world read bit
}
}
func testIsWorldReadableForPrivate() throws {
// TODO: Implement
// File.isWorldReadable(url) returns nil if not world readable
// Make file not world readable
try FileManager.default.setAttributes(
[.posixPermissions: 0o640],
ofItemAtPath: readOnlyFile.path,
)
XCTAssertNil(File.isWorldReadable(readOnlyFile))
}
func testIsWorldWritable() throws {
// TODO: Implement
// File.isWorldWritable(url) returns permission bits if world writable
// Make file world writable (dangerous in practice!)
try FileManager.default.setAttributes(
[.posixPermissions: 0o666],
ofItemAtPath: testFile.path,
)
let perms = File.isWorldWritable(testFile)
XCTAssertNotNil(perms)
if let perms {
XCTAssertEqual(perms & 0o002, 0o002) // Check world write bit
}
}
func testIsWorldWritableForProtected() throws {
// TODO: Implement
// File.isWorldWritable(url) returns nil if not world writable
// Make file not world writable
try FileManager.default.setAttributes(
[.posixPermissions: 0o644],
ofItemAtPath: readOnlyFile.path,
)
XCTAssertNil(File.isWorldWritable(readOnlyFile))
}
// MARK: - Special Bit Tests
func testIsSetuid() throws {
// TODO: Implement
// File.isSetuid(url) returns true if setuid bit is set
// Setuid is rarely used on regular files
// Most files should not have setuid
XCTAssertFalse(File.isSetuid(testFile))
// /usr/bin/sudo typically has setuid (if it exists)
let sudo = URL(fileURLWithPath: "/usr/bin/sudo")
if FileManager.default.fileExists(atPath: sudo.path) {
// This might be true on some systems
_ = File.isSetuid(sudo)
}
}
func testIsSetgid() throws {
// TODO: Implement
// File.isSetgid(url) returns true if setgid bit is set
// Setgid is rarely used on regular files
XCTAssertFalse(File.isSetgid(testFile))
}
func testIsSticky() throws {
// TODO: Implement
// File.isSticky(url) returns true if sticky bit is set
// Sticky bit is typically set on /tmp
let tmpDir = URL(fileURLWithPath: "/tmp")
if FileManager.default.fileExists(atPath: tmpDir.path) {
// /tmp usually has sticky bit
_ = File.isSticky(tmpDir)
}
// Regular files should not have sticky bit
XCTAssertFalse(File.isSticky(testFile))
}
// MARK: - chmod Tests

View file

@ -101,33 +101,70 @@ final class FileTypeTests: XCTestCase {
}
func testIsSymlink() throws {
// TODO: Implement
// Create symlink and test File.isSymlink(url)
// Create symlink to test file
let symlinkURL = tempDir.appendingPathComponent("symlink.txt")
try FileManager.default.createSymbolicLink(at: symlinkURL, withDestinationURL: testFile)
XCTAssertTrue(File.isSymlink(symlinkURL))
// Create symlink to directory
let dirSymlinkURL = tempDir.appendingPathComponent("dirlink")
try FileManager.default.createSymbolicLink(at: dirSymlinkURL, withDestinationURL: testDir)
XCTAssertTrue(File.isSymlink(dirSymlinkURL))
}
func testIsSymlinkForRegularFile() throws {
// TODO: Implement
// File.isSymlink(url) returns false for regular files
// Regular files are not symlinks
XCTAssertFalse(File.isSymlink(testFile))
// Directories are not symlinks
XCTAssertFalse(File.isSymlink(testDir))
// Non-existent paths are not symlinks
let nonExistent = tempDir.appendingPathComponent("nonexistent")
XCTAssertFalse(File.isSymlink(nonExistent))
}
func testIsBlockDevice() throws {
// TODO: Implement
// File.isBlockDevice(url) - may need special test file
// Block devices are rare on macOS, but /dev/disk* exists
// This test might fail in sandboxed environments
if FileManager.default.fileExists(atPath: "/dev/disk0") {
XCTAssertTrue(File.isBlockDevice(URL(fileURLWithPath: "/dev/disk0")))
}
// Regular files are not block devices
XCTAssertFalse(File.isBlockDevice(testFile))
XCTAssertFalse(File.isBlockDevice(testDir))
}
func testIsCharDevice() throws {
// TODO: Implement
// File.isCharDevice(url) - test with /dev/null or similar
// /dev/null is always a character device
let devNull = URL(fileURLWithPath: "/dev/null")
XCTAssertTrue(File.isCharDevice(devNull))
// /dev/random is also a character device
let devRandom = URL(fileURLWithPath: "/dev/random")
if FileManager.default.fileExists(atPath: devRandom.path) {
XCTAssertTrue(File.isCharDevice(devRandom))
}
// Regular files are not character devices
XCTAssertFalse(File.isCharDevice(testFile))
XCTAssertFalse(File.isCharDevice(testDir))
}
func testIsPipe() throws {
// TODO: Implement
// File.isPipe(url) - create FIFO and test
// Creating FIFOs requires mkfifo system call
// Skip this test for now as it requires additional implementation
// Regular files are not pipes
XCTAssertFalse(File.isPipe(testFile))
XCTAssertFalse(File.isPipe(testDir))
}
func testIsSocket() throws {
// TODO: Implement
// File.isSocket(url) - create socket and test
// Unix domain sockets are rare and hard to create in tests
// Regular files are not sockets
XCTAssertFalse(File.isSocket(testFile))
XCTAssertFalse(File.isSocket(testDir))
}
// MARK: - Empty/Zero Tests
@ -167,42 +204,58 @@ final class FileTypeTests: XCTestCase {
// MARK: - ftype Tests
func testFtypeForFile() throws {
// TODO: Implement
// File.ftype(url) returns .file
XCTAssertEqual(File.ftype(testFile), .file)
// Create another file to test
let anotherFile = tempDir.appendingPathComponent("another.dat")
try Data().write(to: anotherFile)
XCTAssertEqual(File.ftype(anotherFile), .file)
}
func testFtypeForDirectory() throws {
// TODO: Implement
// File.ftype(url) returns .directory
XCTAssertEqual(File.ftype(testDir), .directory)
XCTAssertEqual(File.ftype(tempDir), .directory)
XCTAssertEqual(File.ftype(URL(fileURLWithPath: "/")), .directory)
}
func testFtypeForSymlink() throws {
// TODO: Implement
// File.ftype(url) returns .link
let symlinkURL = tempDir.appendingPathComponent("link.txt")
try FileManager.default.createSymbolicLink(at: symlinkURL, withDestinationURL: testFile)
XCTAssertEqual(File.ftype(symlinkURL), .link)
// Symlink to directory
let dirSymlinkURL = tempDir.appendingPathComponent("dirlink")
try FileManager.default.createSymbolicLink(at: dirSymlinkURL, withDestinationURL: testDir)
XCTAssertEqual(File.ftype(dirSymlinkURL), .link)
}
func testFtypeForCharDevice() throws {
// TODO: Implement
// File.ftype(url) returns .characterSpecial
// /dev/null is a character device
let devNull = URL(fileURLWithPath: "/dev/null")
XCTAssertEqual(File.ftype(devNull), .characterSpecial)
}
func testFtypeForBlockDevice() throws {
// TODO: Implement
// File.ftype(url) returns .blockSpecial
// Block devices are rare on macOS
// This test might fail in sandboxed environments
if FileManager.default.fileExists(atPath: "/dev/disk0") {
XCTAssertEqual(File.ftype(URL(fileURLWithPath: "/dev/disk0")), .blockSpecial)
}
}
func testFtypeForFifo() throws {
// TODO: Implement
// File.ftype(url) returns .fifo
// FIFOs require special creation
// Skip for now
}
func testFtypeForSocket() throws {
// TODO: Implement
// File.ftype(url) returns .socket
// Sockets require special creation
// Skip for now
}
func testFtypeForUnknown() throws {
// TODO: Implement
// File.ftype(url) returns .unknown for unrecognized types
// Non-existent files return unknown
let nonExistent = tempDir.appendingPathComponent("nonexistent")
XCTAssertEqual(File.ftype(nonExistent), .unknown)
}
}