Sources/OrgCore/Paths.swift

28 lines · 1360 bytes

 1import Foundation
 2
 3/// Paths as written in Org files and settings, where `~` is the home folder.
 4public enum OrgPaths {
 5    /// The account's home folder. On the Mac this is the real one even in the sandbox, where
 6    /// `NSHomeDirectory()` and `expandingTildeInPath` give the app's container.
 7    public static let home: String = {
 8        #if os(macOS)
 9        getpwuid(getuid())?.pointee.pw_dir.map { String(cString: $0) } ?? NSHomeDirectory()
10        #else
11        NSHomeDirectory()
12        #endif
13    }()
14
15    /// `path` with a leading `~` or `~/` taken from `home`; otherwise, `~user` included, as
16    /// `expandingTildeInPath` gives it.
17    public static func expandingTilde(_ path: String, home: String = home) -> String {
18        guard path == "~" || path.hasPrefix("~/") else { return (path as NSString).expandingTildeInPath }
19        return ((home + path.dropFirst()) as NSString).expandingTildeInPath
20    }
21
22    /// `path` with `home` at its start written as `~`, as `abbreviatingWithTildeInPath` does.
23    public static func abbreviatingWithTilde(_ path: String, home: String = home) -> String {
24        let normalized = path.hasPrefix("~") ? path : (path as NSString).expandingTildeInPath
25        if normalized == home { return "~" }
26        return normalized.hasPrefix(home + "/") ? "~" + normalized.dropFirst(home.count) : normalized
27    }
28}