Sources/OrgstarCLI/Host.swift

cf1c2de361bd33dc4f739537ae53e36a30076444
orgstar/Sources/OrgstarCLI/Host.swift

89 lines · 3364 bytes

 1import Foundation
 2
 3/// What the tool takes from outside the files: the environment, the time, the standard streams
 4/// and `open`. Tests give their own.
 5struct Host {
 6    var environment: [String: String]
 7    var now: Date
 8    var calendar: Calendar
 9    var currentDirectory: String
10    /// Standard input's text; nil when it is a terminal.
11    var input: () -> String?
12    var output: (Data) -> Void
13    var error: (String) -> Void
14    /// Runs `/usr/bin/open` with these arguments and returns its exit status.
15    var open: ([String]) -> Int32
16    /// The running executable, through any links to it.
17    var executable: URL
18
19    static func process() -> Host {
20        Host(
21            environment: ProcessInfo.processInfo.environment,
22            now: Date(),
23            calendar: .current,
24            currentDirectory: FileManager.default.currentDirectoryPath,
25            input: {
26                guard isatty(STDIN_FILENO) == 0 else { return nil }
27                return String(decoding: FileHandle.standardInput.readDataToEndOfFile(), as: UTF8.self)
28            },
29            output: { FileHandle.standardOutput.write($0) },
30            error: { FileHandle.standardError.write(Data($0.utf8)) },
31            open: { arguments in
32                let process = Process()
33                process.executableURL = URL(fileURLWithPath: "/usr/bin/open")
34                process.arguments = arguments
35                do {
36                    try process.run()
37                    process.waitUntilExit()
38                    return process.terminationStatus
39                } catch {
40                    return 1
41                }
42            },
43            executable: URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath()
44        )
45    }
46
47    func print(_ text: String) {
48        output(Data((text.hasSuffix("\n") ? text : text + "\n").utf8))
49    }
50
51    /// The app this executable is inside, as `Contents/Helpers/orgstar`; nil for a build run
52    /// from its build folder.
53    var app: URL? {
54        let contents = executable.deletingLastPathComponent().deletingLastPathComponent()
55        let app = contents.deletingLastPathComponent()
56        guard executable.deletingLastPathComponent().lastPathComponent == "Helpers", contents.lastPathComponent == "Contents",
57              app.pathExtension == "app" else { return nil }
58        return app
59    }
60
61    /// `path` from the command line: `~` expanded, and relative to the current folder.
62    func absolute(_ path: String) -> String {
63        let expanded = (path as NSString).expandingTildeInPath
64        if expanded.hasPrefix("/") { return (expanded as NSString).standardizingPath }
65        return ((currentDirectory as NSString).appendingPathComponent(expanded) as NSString).standardizingPath
66    }
67}
68
69enum ExitCode: Int32 {
70    case success = 0
71    /// A file couldn't be read, written or exported.
72    case failure = 1
73    /// An unknown command or option, or a missing argument.
74    case usage = 2
75    /// No such file, heading, view or template, or no running clock.
76    case notFound = 3
77    /// The command won't do it: questions without answers, a file it can't change.
78    case refused = 4
79}
80
81struct Failure: Error {
82    let code: ExitCode
83    let message: String
84
85    init(_ code: ExitCode, _ message: String) {
86        self.code = code
87        self.message = message
88    }
89}
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