3

I am reading old files that still use HFS style paths, such as VolumeName:Folder:File.

I need to convert them into POSIX paths.

I do not like to do string replacement as it is a bit tricky, nor do I want to invoke AppleScript or Shell operations for this task.

Is there a framework function to accomplish this? Deprecation is not an issue.

BTW, here's a solution for the inverse operation.

Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149

2 Answers2

3

The “reverse” operation of CFURLCopyFileSystemPath() is CFURLCreateWithFileSystemPath(). Similarly as in the referenced Q&A, you have create the path style from the raw enumeration value since CFURLPathStyle.cfurlhfsPathStyle is deprecated and not available. Example:

let hfsPath = "Macintosh HD:Applications:Xcode.app"
if let url = CFURLCreateWithFileSystemPath(nil, hfsPath as CFString,
                                           CFURLPathStyle(rawValue: 1)!, true) as URL? {
    print(url.path) // /Applications/Xcode.app
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
3

A solution in Obj-C and Swift as category / extension of NSString / String. The unavailable kCFURLHFSPathStyle style is circumvented in the same way as in the linked question.

Objective-C

@implementation NSString (POSIX_HFS)

    - (NSString *)POSIXPathFromHFSPath
    {
        NSString *posixPath = nil;
        CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)self, 1, [self hasSuffix:@":"]); // kCFURLHFSPathStyle
        if (fileURL)    {
            posixPath = [(__bridge NSURL*)fileURL path];
            CFRelease(fileURL);
        }

        return posixPath;
    }

@end

Swift

extension String {

    func posixPathFromHFSPath() -> String?
    {
        guard let fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                                          self as CFString?,
                                                          CFURLPathStyle(rawValue:1)!,
                                                          self.hasSuffix(":")) else { return nil }
        return (fileURL as URL).path
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Would you also know an answer for this: https://stackoverflow.com/questions/55381517 – Thomas Tempelmann Mar 27 '19 at 18:23
  • I'm afraid, no. Do you really need Terminal.app? There is `NSTask` or `NSUserUnixTask` (for sandboxed apps). – vadian Mar 27 '19 at 18:30
  • Nope, as I wrote in the cursive text of my question, I use Terminal's behavior only as an example. I need to generate these paths to retain compatibility with an older app, for data exchange. – Thomas Tempelmann Mar 27 '19 at 18:37