Skip to content

Re-enable URL and NSURL initializers #373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions Sources/Foundation/NSPathUtilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -191,21 +191,23 @@ extension String {
temp.removeSubrange(startIndex..<prefix.endIndex)
return temp
}

#if !os(WASI)

internal func _tryToRemovePathPrefix(_ prefix: String) -> String? {
guard self != prefix else {
return nil
}

let temp = _stringByRemovingPrefix(prefix)
#if os(WASI)
return temp
#else
if FileManager.default.fileExists(atPath: temp) {
return temp
}

#endif

return nil
}
#endif
}

extension NSString {
Expand Down Expand Up @@ -335,7 +337,6 @@ extension NSString {
return result._stringByFixingSlashes()
}

#if !os(WASI)
public var expandingTildeInPath: String {
guard hasPrefix("~") else {
return _swiftObject
Expand All @@ -356,7 +357,6 @@ extension NSString {

return result
}
#endif

#if os(Windows)
public var unixPath: String {
Expand All @@ -370,8 +370,7 @@ extension NSString {
return converted._stringByFixingSlashes(stripTrailing: false)
}
#endif

#if !os(WASI)

public var standardizingPath: String {
#if os(Windows)
let expanded = unixPath.expandingTildeInPath
Expand Down Expand Up @@ -408,9 +407,11 @@ extension NSString {

default:
resolvedPath = resolvedPath._bridgeToObjectiveC().appendingPathComponent(component)
#if !os(WASI)
if let destination = FileManager.default._tryToResolveTrailingSymlinkInPath(resolvedPath) {
resolvedPath = destination
}
#endif
}
}

Expand All @@ -419,8 +420,7 @@ extension NSString {

return resolvedPath
}
#endif


public func stringsByAppendingPaths(_ paths: [String]) -> [String] {
if self == "" {
return paths
Expand Down Expand Up @@ -722,21 +722,27 @@ public func NSSearchPathForDirectoriesInDomains(_ directory: FileManager.SearchP
return path
}
}
#endif

public func NSHomeDirectory() -> String {
return NSHomeDirectoryForUser(nil)!
}

public func NSHomeDirectoryForUser(_ user: String?) -> String? {
#if os(WASI)
return nil
#else
let userName = user?._cfObject
guard let homeDir = CFCopyHomeDirectoryURLForUser(userName)?.takeRetainedValue() else {
return nil
}

let url: URL = homeDir._swiftObject
return url.path
#endif
}

#if !os(WASI)
public func NSUserName() -> String {
let userName = CFCopyUserName().takeRetainedValue()
return userName._swiftObject
Expand Down
25 changes: 16 additions & 9 deletions Sources/Foundation/NSURL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ internal let kCFURLPlatformPathStyle = kCFURLWindowsPathStyle
internal let kCFURLPlatformPathStyle = kCFURLPOSIXPathStyle
#endif

#if !os(WASI)
private func _standardizedPath(_ path: String) -> String {
if !path.isAbsolutePath {
return path._nsObject.standardizingPath
Expand All @@ -37,7 +36,6 @@ private func _standardizedPath(_ path: String) -> String {
return path
#endif
}
#endif

internal func _pathComponents(_ path: String?) -> [String]? {
guard let p = path else {
Expand Down Expand Up @@ -193,8 +191,7 @@ open class NSURL : NSObject, NSSecureCoding, NSCopying {
aCoder.encode(self.baseURL?._nsObject, forKey:"NS.base")
aCoder.encode(self.relativeString._bridgeToObjectiveC(), forKey:"NS.relative")
}

#if !os(WASI)

public init(fileURLWithPath path: String, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
super.init()

Expand All @@ -214,6 +211,7 @@ open class NSURL : NSObject, NSSecureCoding, NSCopying {
if validPathSeps.contains(where: { thePath.hasSuffix(String($0)) }) {
isDir = true
} else {
#if !os(WASI)
let absolutePath: String
if let absPath = baseURL?.appendingPathComponent(path).path {
absolutePath = absPath
Expand All @@ -222,6 +220,7 @@ open class NSURL : NSObject, NSSecureCoding, NSCopying {
}

let _ = FileManager.default.fileExists(atPath: absolutePath, isDirectory: &isDir)
#endif
}

self.init(fileURLWithPath: thePath, isDirectory: isDir.boolValue, relativeTo: baseURL)
Expand All @@ -238,9 +237,11 @@ open class NSURL : NSObject, NSSecureCoding, NSCopying {
if validPathSeps.contains(where: { thePath.hasSuffix(String($0)) }) {
isDir = true
} else {
#if !os(WASI)
if !FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
isDir = false
}
#endif
}
super.init()
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPlatformPathStyle, isDir.boolValue, nil)
Expand All @@ -251,7 +252,6 @@ open class NSURL : NSObject, NSSecureCoding, NSCopying {
let pathString = String(cString: path)
self.init(fileURLWithPath: pathString, isDirectory: isDir, relativeTo: baseURL)
}
#endif

public convenience init?(string URLString: String) {
self.init(string: URLString, relativeTo:nil)
Expand Down Expand Up @@ -893,16 +893,15 @@ extension NSURL {
open var deletingPathExtension: URL? {
return CFURLCreateCopyDeletingPathExtension(kCFAllocatorSystemDefault, _cfObject)?._swiftObject
}

#if !os(WASI)

/* The following methods work only on `file:` scheme URLs; for non-`file:` scheme URLs, these methods return the URL unchanged.
*/
open var standardizingPath: URL? {
// Documentation says it should expand initial tilde, but it does't do this on OS X.
// In remaining cases it works just like URLByResolvingSymlinksInPath.
return _resolveSymlinksInPath(excludeSystemDirs: true, preserveDirectoryFlag: true)
}

open var resolvingSymlinksInPath: URL? {
return _resolveSymlinksInPath(excludeSystemDirs: true)
}
Expand All @@ -920,8 +919,12 @@ extension NSURL {
if selfPath.isAbsolutePath {
absolutePath = selfPath
} else {
#if os(WASI)
return nil
#else
let workingDir = FileManager.default.currentDirectoryPath
absolutePath = workingDir._bridgeToObjectiveC().appendingPathComponent(selfPath)
#endif
}


Expand All @@ -942,15 +945,20 @@ extension NSURL {

default:
resolvedPath = resolvedPath._bridgeToObjectiveC().appendingPathComponent(component)
#if !os(WASI)
if let destination = FileManager.default._tryToResolveTrailingSymlinkInPath(resolvedPath) {
resolvedPath = destination
}
#endif
}
}

// It might be a responsibility of NSURL(fileURLWithPath:). Check it.
var isExistingDirectory: ObjCBool = false

#if !os(WASI)
let _ = FileManager.default.fileExists(atPath: resolvedPath, isDirectory: &isExistingDirectory)
#endif

if excludeSystemDirs {
resolvedPath = resolvedPath._tryToRemovePathPrefix("/private") ?? resolvedPath
Expand All @@ -966,7 +974,6 @@ extension NSURL {
return URL(fileURLWithPath: resolvedPath)
}
}
#endif

fileprivate func _pathByRemovingDots(_ comps: [String]) -> String {
var components = comps
Expand Down
8 changes: 1 addition & 7 deletions Sources/Foundation/URL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -504,8 +504,7 @@ public struct URL : ReferenceConvertible, Equatable {
guard !string.isEmpty, let inner = NSURL(string: string, relativeTo: url) else { return nil }
_url = URL._converted(from: inner)
}

#if !os(WASI)

/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
Expand Down Expand Up @@ -535,11 +534,6 @@ public struct URL : ReferenceConvertible, Equatable {
public init(fileURLWithPath path: String) {
_url = URL._converted(from: NSURL(fileURLWithPath: path.isEmpty ? "." : path))
}
#else
public init(fileURLWithPath path: String) {
_url = NSURL(string: "file://\(path)")!
}
#endif

/// Initializes a newly created URL using the contents of the given data, relative to a base URL.
///
Expand Down
45 changes: 21 additions & 24 deletions Sources/FoundationXML/XMLParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,13 @@ private func UTF8STRING(_ bytes: UnsafePointer<UInt8>?) -> String? {
return nil
}

#if !os(WASI)
internal func _NSXMLParserCurrentParser() -> _CFXMLInterface? {
if let parser = XMLParser.currentParser() {
return parser.interface
} else {
return nil
}
}
#endif

internal func _NSXMLParserExternalEntityWithURL(_ interface: _CFXMLInterface, urlStr: UnsafePointer<Int8>, identifier: UnsafePointer<Int8>, context: _CFXMLInterfaceParserContext, originalLoaderFunction: _CFXMLInterfaceExternalEntityLoader) -> _CFXMLInterfaceParserInput? {
let parser = interface.parser
Expand All @@ -65,13 +63,11 @@ internal func _NSXMLParserExternalEntityWithURL(_ interface: _CFXMLInterface, ur
if let allowedEntityURLs = parser.allowedExternalEntityURLs {
if let url = URL(string: String(describing: urlStr)) {
a = url
#if !os(WASI)
if let scheme = url.scheme {
if scheme == "file" {
a = URL(fileURLWithPath: url.path)
}
}
#endif
}
if let url = a {
let allowed = allowedEntityURLs.contains(url)
Expand Down Expand Up @@ -470,23 +466,33 @@ open class XMLParser : NSObject {

open var allowedExternalEntityURLs: Set<URL>?

#if !os(WASI)
#if os(WASI)
private static var _currentParser: XMLParser?
#endif

internal static func currentParser() -> XMLParser? {
#if os(WASI)
return _currentParser
#else
if let current = Thread.current.threadDictionary["__CurrentNSXMLParser"] {
return current as? XMLParser
} else {
return nil
}
#endif
}

internal static func setCurrentParser(_ parser: XMLParser?) {
#if os(WASI)
_currentParser = parser
#else
if let p = parser {
Thread.current.threadDictionary["__CurrentNSXMLParser"] = p
} else {
Thread.current.threadDictionary.removeObject(forKey: "__CurrentNSXMLParser")
}
}
#endif
}

internal func _handleParseResult(_ parseResult: Int32) -> Bool {
if parseResult == 0 {
Expand Down Expand Up @@ -563,9 +569,6 @@ open class XMLParser : NSObject {
internal func parseFrom(_ stream : InputStream) -> Bool {
var result = true

guard let buffer = malloc(_chunkSize)?.bindMemory(to: UInt8.self, capacity: _chunkSize) else { return false }
defer { free(buffer) }

stream.open()
defer { stream.close() }
parseLoop: while result {
Expand All @@ -588,27 +591,23 @@ open class XMLParser : NSObject {

return result
}
#endif

#else
internal func parse(from data: Data) -> Bool {
var data = data
var result = true
let buffer = malloc(_chunkSize)!.bindMemory(to: UInt8.self, capacity: _chunkSize)
defer { free(buffer) }
var range = NSRange(location: 0, length: min(_chunkSize, data.count))
var chunkStart = 0
var chunkEnd = min(_chunkSize, data.count)
while result {
let chunk = data.withUnsafeMutableBytes { (rawBuffer: UnsafeMutableRawBufferPointer) -> Data in
let ptr = rawBuffer.baseAddress!.advanced(by: range.location)
return Data(bytesNoCopy: ptr, count: range.length, deallocator: .none)
}
result = parseData(chunk)
if range.location + range.length >= data.count {
if chunkStart >= data.count || chunkEnd >= data.count {
break
}
range = NSRange(location: range.location + range.length, length: min(_chunkSize, data.count - (range.location + range.length)))
let chunk = data[chunkStart..<chunkEnd]
result = parseData(chunk)
chunkStart = chunkEnd
chunkEnd = min(chunkEnd + _chunkSize, data.count)
}
return result
}
#endif

// called to start the event-driven parse. Returns YES in the event of a successful parse, and NO in case of error.
open func parse() -> Bool {
Expand Down Expand Up @@ -1031,10 +1030,8 @@ extension NSObject {
func setupXMLParsing() {
_CFSetupXMLInterface()
_CFSetupXMLBridgeIfNeededUsingBlock {
#if !os(WASI)
__CFSwiftXMLParserBridge.CFBridge = CF.originalBridge
__CFSwiftXMLParserBridge.currentParser = _NSXMLParserCurrentParser
#endif
__CFSwiftXMLParserBridge._xmlExternalEntityWithURL = _NSXMLParserExternalEntityWithURL
__CFSwiftXMLParserBridge.getContext = _NSXMLParserGetContext
__CFSwiftXMLParserBridge.internalSubset = _NSXMLParserInternalSubset
Expand Down