Sources/OrgPrograms/CommandLineTool.swift
53 lines · 2634 bytes
1import Foundation
2
3/// The `orgstar` command, which scripts/build-app.sh puts in the app as `Contents/Helpers/orgstar`,
4/// linked into a folder on the PATH by Settings ▸ General ▸ Install Command-Line Tool….
5public enum CommandLineTool {
6 public enum Failure: Error, Equatable {
7 /// This copy of the app has no command, as a build run from SwiftPM.
8 case missing
9 /// `path` is there and isn't a link.
10 case occupied(path: String)
11 /// The link can't be made in the folder.
12 case unwritable(folder: String, reason: String)
13 }
14
15 /// The command in the app at `app`.
16 public static func helper(in app: URL = Bundle.main.bundleURL) -> URL {
17 app.appendingPathComponent("Contents/Helpers/orgstar")
18 }
19
20 /// Where choosing a folder starts: `~/.local/bin` when it's there, else `/usr/local/bin`
21 /// when it's there, else the home folder.
22 public static func suggestedFolder(home: String = NSHomeDirectory()) -> URL {
23 let local = (home as NSString).appendingPathComponent(".local/bin")
24 for path in [local, "/usr/local/bin"] where FileManager.default.fileExists(atPath: path) { return URL(fileURLWithPath: path) }
25 return URL(fileURLWithPath: home)
26 }
27
28 /// Links `folder/orgstar` to `helper`, replacing a link already there. Returns the link.
29 @discardableResult
30 public static func install(_ helper: URL, in folder: URL) throws(Failure) -> URL {
31 let manager = FileManager.default
32 guard manager.isExecutableFile(atPath: helper.path) else { throw .missing }
33 let link = folder.appendingPathComponent("orgstar")
34 if let attributes = try? manager.attributesOfItem(atPath: link.path) {
35 guard attributes[.type] as? FileAttributeType == .typeSymbolicLink else { throw .occupied(path: link.path) }
36 }
37 let temporary = folder.appendingPathComponent(".orgstar-\(UUID().uuidString)")
38 do {
39 try manager.createSymbolicLink(at: temporary, withDestinationURL: helper)
40 // rename(2) replaces a link that's there in one step.
41 guard rename(temporary.path, link.path) == 0 else {
42 let reason = String(cString: strerror(errno))
43 try? manager.removeItem(at: temporary)
44 throw Failure.unwritable(folder: folder.path, reason: reason)
45 }
46 } catch let failure as Failure {
47 throw failure
48 } catch {
49 throw .unwritable(folder: folder.path, reason: (error as NSError).localizedFailureReason ?? error.localizedDescription)
50 }
51 return link
52 }
53}