-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
OpenCommandRunner.swift
78 lines (70 loc) · 2.51 KB
/
OpenCommandRunner.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import Apps
import AXEssibility
import Cocoa
import Foundation
final class OpenCommandRunner {
struct Plugins {
let finderFolder: OpenFolderInFinder
let parser = OpenURLParser()
let open: OpenFilePlugin
let swapTab: OpenURLSwapTabsPlugin
}
private let plugins: Plugins
private let workspace: WorkspaceProviding
init(_ commandRunner: ScriptCommandRunner, workspace: WorkspaceProviding) {
self.plugins = .init(
finderFolder: OpenFolderInFinder(commandRunner, workspace: workspace),
open: OpenFilePlugin(workspace: workspace),
swapTab: OpenURLSwapTabsPlugin(commandRunner))
self.workspace = workspace
}
func run(_ path: String, checkCancellation: Bool, application: Application?) async throws {
do {
if plugins.finderFolder.validate(application?.bundleIdentifier) {
try await plugins.finderFolder.execute(path, checkCancellation: checkCancellation)
} else if path.isUrl {
try await plugins.swapTab.execute(path,
appName: application?.displayName ?? "Safari",
appPath: application?.path,
bundleIdentifier: application?.bundleIdentifier,
checkCancellation: checkCancellation)
} else {
try await plugins.open.execute(path, application: application)
}
} catch {
let url = URL(fileURLWithPath: path)
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? false
// TODO: Check if this is what we want.
if application?.bundleName == "Finder", isDirectory == true {
try await plugins.finderFolder.execute(path, checkCancellation: checkCancellation)
} else {
try await plugins.open.execute(path, application: application)
}
}
}
}
extension String {
var sanitizedPath: String { _sanitizePath() }
mutating func sanitizePath() {
self = _sanitizePath()
}
/// Expand the tile character used in the path & replace any escaped spaces
///
/// - Returns: A new string that expanded and has no escaped whitespace
private func _sanitizePath() -> String {
var path = (self as NSString).expandingTildeInPath
path = path.replacingOccurrences(of: "", with: "\\ ")
return path
}
var isUrl: Bool {
if let url = URL(string: self) {
if url.host == nil || url.isFileURL {
return false
} else {
return true
}
} else {
return false
}
}
}