Skip to content

Commit

Permalink
Remove @dynamicMember generally
Browse files Browse the repository at this point in the history
  • Loading branch information
mxcl committed Jul 21, 2019
1 parent d2bb2a1 commit 621d1b0
Show file tree
Hide file tree
Showing 13 changed files with 198 additions and 131 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -3,3 +3,4 @@
/*.xcodeproj
/build
/docs
/.swiftpm
11 changes: 6 additions & 5 deletions README.md
Expand Up @@ -32,7 +32,7 @@ let foo = try Path.root.join("foo").copy(into: Path.root.join("bar").mkdir())
print(foo) // => /bar/foo
print(foo.isFile) // => true

// we support dynamic members (_use_sparingly_):
// we support dynamic-member-syntax when joining named static members, eg:
let prefs = Path.home.Library.Preferences // => /Users/mxcl/Library/Preferences

// a practical example: installing a helper executable
Expand Down Expand Up @@ -107,10 +107,11 @@ We support `@dynamicMemberLookup`:
let ls = Path.root.usr.bin.ls // => /usr/bin/ls
```

This is less commonly useful than you would think, hence our documentation
does not use it. Usually you are joining variables or other `String` arguments
or trying to describe files (and files usually have extensions). However when
you need it, it’s *lovely*.
We only provide this for “starting” function, eg. `Path.home` or `Bundle.path`.
This is because we found in practice it was easy to write incorrect code, since
everything would compile if we allowed arbituary variables to take *any* named
property as valid syntax. What we have is what you want most of the time but
much less dangerous.

## Initializing from user-input

Expand Down
48 changes: 24 additions & 24 deletions Sources/Extensions.swift
Expand Up @@ -13,46 +13,46 @@ public extension Bundle {
Returns the path for the shared-frameworks directory in this bundle.
- Note: This is typically `ShareFrameworks`
*/
var sharedFrameworks: Path {
return sharedFrameworksPath.flatMap(Path.init) ?? defaultSharedFrameworksPath
var sharedFrameworks: DynamicPath {
return sharedFrameworksPath.flatMap(DynamicPath.init) ?? defaultSharedFrameworksPath
}

/**
Returns the path for the private-frameworks directory in this bundle.
- Note: This is typically `Frameworks`
*/
var privateFrameworks: Path {
return privateFrameworksPath.flatMap(Path.init) ?? defaultSharedFrameworksPath
var privateFrameworks: DynamicPath {
return privateFrameworksPath.flatMap(DynamicPath.init) ?? defaultSharedFrameworksPath
}

/// Returns the path for the resources directory in this bundle.
var resources: Path {
return resourcePath.flatMap(Path.init) ?? defaultResourcesPath
var resources: DynamicPath {
return resourcePath.flatMap(DynamicPath.init) ?? defaultResourcesPath
}

/// Returns the path for this bundle.
var path: Path {
return Path(string: bundlePath)
var path: DynamicPath {
return DynamicPath(string: bundlePath)
}

/// Returns the executable for this bundle, if there is one, not all bundles have one hence `Optional`.
var executable: Path? {
return executablePath.flatMap(Path.init)
var executable: DynamicPath? {
return executablePath.flatMap(DynamicPath.init)
}
}

/// Extensions on `String` that work with `Path` rather than `String` or `URL`
public extension String {
/// Initializes this `String` with the contents of the provided path.
@inlinable
init(contentsOf path: Path) throws {
init<P: Pathish>(contentsOf path: P) throws {
try self.init(contentsOfFile: path.string)
}

/// - Returns: `to` to allow chaining
@inlinable
@discardableResult
func write(to: Path, atomically: Bool = false, encoding: String.Encoding = .utf8) throws -> Path {
func write<P: Pathish>(to: P, atomically: Bool = false, encoding: String.Encoding = .utf8) throws -> P {
try write(toFile: to.string, atomically: atomically, encoding: encoding)
return to
}
Expand All @@ -62,14 +62,14 @@ public extension String {
public extension Data {
/// Initializes this `Data` with the contents of the provided path.
@inlinable
init(contentsOf path: Path) throws {
init<P: Pathish>(contentsOf path: P) throws {
try self.init(contentsOf: path.url)
}

/// - Returns: `to` to allow chaining
@inlinable
@discardableResult
func write(to: Path, atomically: Bool = false) throws -> Path {
func write<P: Pathish>(to: P, atomically: Bool = false) throws -> P {
let opts: NSData.WritingOptions
if atomically {
#if !os(Linux)
Expand All @@ -89,39 +89,39 @@ public extension Data {
public extension FileHandle {
/// Initializes this `FileHandle` for reading at the location of the provided path.
@inlinable
convenience init(forReadingAt path: Path) throws {
convenience init<P: Pathish>(forReadingAt path: P) throws {
try self.init(forReadingFrom: path.url)
}

/// Initializes this `FileHandle` for writing at the location of the provided path.
@inlinable
convenience init(forWritingAt path: Path) throws {
convenience init<P: Pathish>(forWritingAt path: P) throws {
try self.init(forWritingTo: path.url)
}

/// Initializes this `FileHandle` for reading and writing at the location of the provided path.
@inlinable
convenience init(forUpdatingAt path: Path) throws {
convenience init<P: Pathish>(forUpdatingAt path: P) throws {
try self.init(forUpdating: path.url)
}
}

internal extension Bundle {
var defaultSharedFrameworksPath: Path {
var defaultSharedFrameworksPath: DynamicPath {
#if os(macOS)
return path.join("Contents/Frameworks")
return path.Contents.Frameworks
#elseif os(Linux)
return path.join("lib")
return path.lib
#else
return path.join("Frameworks")
return path.Frameworks
#endif
}

var defaultResourcesPath: Path {
var defaultResourcesPath: DynamicPath {
#if os(macOS)
return path.join("Contents/Resources")
return path.Contents.Resources
#elseif os(Linux)
return path.join("share")
return path.share
#else
return path
#endif
Expand Down
22 changes: 12 additions & 10 deletions Sources/Path+Attributes.swift
@@ -1,6 +1,6 @@
import Foundation

public extension Path {
public extension Pathish {
//MARK: Filesystem Attributes

/**
Expand Down Expand Up @@ -38,7 +38,7 @@ public extension Path {
@discardableResult
func chmod(_ octal: Int) throws -> Path {
try FileManager.default.setAttributes([.posixPermissions: octal], ofItemAtPath: string)
return self
return Path(self)
}

/**
Expand All @@ -57,7 +57,7 @@ public extension Path {
try FileManager.default.setAttributes(attrs, ofItemAtPath: string)
}
#endif
return self
return Path(self)
}

/**
Expand All @@ -73,22 +73,18 @@ public extension Path {
do {
attrs = try FileManager.default.attributesOfItem(atPath: string)
} catch CocoaError.fileReadNoSuchFile {
return self
return Path(self)
}
let b = attrs[.immutable] as? Bool ?? false
if b {
attrs[.immutable] = false
try FileManager.default.setAttributes(attrs, ofItemAtPath: string)
}
#endif
return self
}

enum Kind {
case file, symlink, directory
return Path(self)
}

var kind: Kind? {
var kind: Path.Kind? {
var buf = stat()
guard lstat(string, &buf) == 0 else {
return nil
Expand All @@ -102,3 +98,9 @@ public extension Path {
}
}
}

public extension Path {
enum Kind {
case file, symlink, directory
}
}
13 changes: 8 additions & 5 deletions Sources/Path+Codable.swift
Expand Up @@ -23,18 +23,19 @@ public extension CodingUserInfoKey {
Provided for relative-path coding. See the instructions in our
[README](https://github.com/mxcl/Path.swift/#codable).
*/
extension Path: Codable {
extension Path: Codable {
/// - SeeAlso: `CodingUserInfoKey.relativePath`
/// :nodoc:
public init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer().decode(String.self)
if value.hasPrefix("/") {
string = value
} else {
guard let root = decoder.userInfo[.relativePath] as? Path else {
throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Path cannot decode a relative path if `userInfo[.relativePath]` not set to a Path object."))
}
} else if let root = decoder.userInfo[.relativePath] as? Path {
string = (root/value).string
} else if let root = decoder.userInfo[.relativePath] as? DynamicPath {
string = (root/value).string
} else {
throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Path cannot decode a relative path if `userInfo[.relativePath]` not set to a Path object."))
}
}

Expand All @@ -44,6 +45,8 @@ extension Path: Codable {
var container = encoder.singleValueContainer()
if let root = encoder.userInfo[.relativePath] as? Path {
try container.encode(relative(to: root))
} else if let root = encoder.userInfo[.relativePath] as? DynamicPath {
try container.encode(relative(to: root))
} else {
try container.encode(string)
}
Expand Down
38 changes: 19 additions & 19 deletions Sources/Path+CommonDirectories.swift
Expand Up @@ -4,17 +4,17 @@ extension Path {
//MARK: Common Directories

/// Returns a `Path` containing `FileManager.default.currentDirectoryPath`.
public static var cwd: Path {
return Path(string: FileManager.default.currentDirectoryPath)
public static var cwd: DynamicPath {
return .init(string: FileManager.default.currentDirectoryPath)
}

/// Returns a `Path` representing the root path.
public static var root: Path {
return Path(string: "/")
public static var root: DynamicPath {
return .init(string: "/")
}

/// Returns a `Path` representing the user’s home directory
public static var home: Path {
public static var home: DynamicPath {
let string: String
#if os(macOS)
if #available(OSX 10.12, *) {
Expand All @@ -25,30 +25,30 @@ extension Path {
#else
string = NSHomeDirectory()
#endif
return Path(string: string)
return .init(string: string)
}

/// Helper to allow search path and domain mask to be passed in.
private static func path(for searchPath: FileManager.SearchPathDirectory) -> Path {
private static func path(for searchPath: FileManager.SearchPathDirectory) -> DynamicPath {
#if os(Linux)
// the urls(for:in:) function is not implemented on Linux
//TODO strictly we should first try to use the provided binary tool

let foo = { ProcessInfo.processInfo.environment[$0].flatMap(Path.init) ?? $1 }
let foo = { ProcessInfo.processInfo.environment[$0].flatMap(Path.init).map(DynamicPath.init) ?? $1 }

switch searchPath {
case .documentDirectory:
return Path.home/"Documents"
return Path.home.Documents
case .applicationSupportDirectory:
return foo("XDG_DATA_HOME", Path.home/".local/share")
return foo("XDG_DATA_HOME", Path.home[dynamicMember: ".local/share"])
case .cachesDirectory:
return foo("XDG_CACHE_HOME", Path.home/".cache")
return foo("XDG_CACHE_HOME", Path.home[dynamicMember: ".cache"])
default:
fatalError()
}
#else
guard let pathString = FileManager.default.urls(for: searchPath, in: .userDomainMask).first?.path else { return defaultUrl(for: searchPath) }
return Path(string: pathString)
return DynamicPath(string: pathString)
#endif
}

Expand All @@ -57,7 +57,7 @@ extension Path {
- Note: There is no standard location for documents on Linux, thus we return `~/Documents`.
- Note: You should create a subdirectory before creating any files.
*/
public static var documents: Path {
public static var documents: DynamicPath {
return path(for: .documentDirectory)
}

Expand All @@ -66,7 +66,7 @@ extension Path {
- Note: On Linux this is `XDG_CACHE_HOME`.
- Note: You should create a subdirectory before creating any files.
*/
public static var caches: Path {
public static var caches: DynamicPath {
return path(for: .cachesDirectory)
}

Expand All @@ -75,20 +75,20 @@ extension Path {
- Note: On Linux is `XDG_DATA_HOME`.
- Note: You should create a subdirectory before creating any files.
*/
public static var applicationSupport: Path {
public static var applicationSupport: DynamicPath {
return path(for: .applicationSupportDirectory)
}
}

#if !os(Linux)
func defaultUrl(for searchPath: FileManager.SearchPathDirectory) -> Path {
func defaultUrl(for searchPath: FileManager.SearchPathDirectory) -> DynamicPath {
switch searchPath {
case .documentDirectory:
return Path.home/"Documents"
return Path.home.Documents
case .applicationSupportDirectory:
return Path.home/"Library/Application Support"
return Path.home.Library[dynamicMember: "Application Support"]
case .cachesDirectory:
return Path.home/"Library/Caches"
return Path.home.Library.Caches
default:
fatalError()
}
Expand Down

0 comments on commit 621d1b0

Please sign in to comment.