Sources/OrgCore/Paths.swift

6ac7ed3093107adb7b5305b1753116a881386321
orgstar/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}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form