Repository navigation
Expand file tree
/
Copy pathAppleScripts.swift
More file actions
530 lines (477 loc) · 21.7 KB
/
Copy pathAppleScripts.swift
File metadata and controls
530 lines (477 loc) · 21.7 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//
// AppleScripts.swift
// SwiftAppleScriptBridge — example
//
// An example of the file layout suggested in the README: every script the app uses,
// gathered in one place as `AppleScriptObject` values, each with a doc comment that
// shows up in Quick Help wherever it is called.
//
// These target the Finder, so they run on any Mac without extra software. Copy the
// file into your own project and replace the bundle identifier and the scripts.
//
// Swift 6 language mode: `AppleScriptObject` is not `Sendable`, so each `static let`
// below needs `nonisolated(unsafe) static let` to compile. Swift 5 mode needs nothing.
// See the README, and issue #2.
//
// Not compiled as part of the package.
//
import Foundation
import Carbon
import SwiftAppleScriptBridge
/// Every AppleScript the app runs, in one place.
///
/// Scripts with `$key` placeholders take their values at call time, through the `with:`
/// parameter of `AppleScriptBridge.executeAppleScript(_:with:)`.
enum AppleScripts {
/// The application these scripts drive. Keeping it in one constant means a move to
/// another app, or another version of the same app, touches a single line.
static let targetApp = "com.apple.finder"
// MARK: - NO RETURN VALUE
/// Brings the Finder to the front, launching it if necessary.
///
/// - Returns: Nothing. `executeAppleScript` yields `nil` for `.none`.
static let activateApp = AppleScriptBridge.AppleScriptObject(
name: "activateApp",
script: """
tell application id "\(targetApp)"
activate
end tell
"""
)
/// Reveals an item in the Finder and brings the window forward.
///
/// - Parameter itemPath: **SET AT RUNTIME**: POSIX path of the item to reveal.
/// - Returns: Nothing.
static let revealItem = AppleScriptBridge.AppleScriptObject(
name: "revealItem",
script: """
tell application id "\(targetApp)"
reveal (POSIX file "$itemPath" as alias)
activate
end tell
"""
)
// MARK: - INT
/// Counts the Finder windows currently open.
///
/// - Returns: An `Int`. `0` means no window is open — which is a real answer, not a
/// failure. Failure is reported by throwing.
static let countOpenWindows = AppleScriptBridge.AppleScriptObject(
name: "countOpenWindows",
returnType: .int,
script: """
tell application id "\(targetApp)"
return count of windows
end tell
"""
)
/// Counts the items directly inside a folder, without descending into it.
///
/// - Parameter folderPath: **SET AT RUNTIME**: POSIX path of the folder to count.
/// - Returns: An `Int` with the number of items.
static let countItemsInFolder = AppleScriptBridge.AppleScriptObject(
name: "countItemsInFolder",
returnType: .int,
script: """
tell application id "\(targetApp)"
return count of items of (POSIX file "$folderPath" as alias)
end tell
"""
)
// MARK: - STRING
/// Reads the name of the startup disk.
///
/// - Returns: A `String` with the volume name.
static let startupDiskName = AppleScriptBridge.AppleScriptObject(
name: "startupDiskName",
returnType: .string,
script: """
tell application id "\(targetApp)"
return name of startup disk
end tell
"""
)
/// Reads the POSIX path of the folder shown in the frontmost Finder window.
///
/// - Returns: A `String` with the POSIX path, or an empty string when no window is open.
static let frontWindowPath = AppleScriptBridge.AppleScriptObject(
name: "frontWindowPath",
returnType: .string,
script: """
tell application id "\(targetApp)"
if (count of windows) is 0 then return ""
return POSIX path of (target of front window as alias)
end tell
"""
)
// MARK: - BOOL
/// Reports whether an item exists on disk.
///
/// - Parameter itemPath: **SET AT RUNTIME**: POSIX path of the item to look for.
/// - Returns: A `Bool`.
static let itemExists = AppleScriptBridge.AppleScriptObject(
name: "itemExists",
returnType: .bool,
script: """
tell application id "\(targetApp)"
return exists (POSIX file "$itemPath")
end tell
"""
)
/// Moves an item to the trash, reporting whether it worked.
///
/// Returning `true` at the end of a `try` block, and `false` from the handler, is the
/// simplest way to give Swift a yes-or-no answer about work the script performed.
///
/// - Parameter itemPath: **SET AT RUNTIME**: POSIX path of the item to trash.
/// - Returns: A `Bool`, `true` on success.
static let trashItem = AppleScriptBridge.AppleScriptObject(
name: "trashItem",
returnType: .bool,
script: """
tell application id "\(targetApp)"
try
delete (POSIX file "$itemPath" as alias)
return true
on error
return false
end try
end tell
"""
)
// MARK: - LIST
/// Lists the names of the items directly inside a folder.
///
/// The script joins the names into one piece of text separated by line feeds, because
/// that is what the `.list` return type splits on. Returning a real AppleScript list
/// would not survive the trip.
///
/// - Parameter folderPath: **SET AT RUNTIME**: POSIX path of the folder to read.
/// - Returns: A `[String]` of item names, in Finder order.
static let itemNamesInFolder = AppleScriptBridge.AppleScriptObject(
name: "itemNamesInFolder",
returnType: .list,
script: """
tell application id "\(targetApp)"
set theNames to name of every item of (POSIX file "$folderPath" as alias)
end tell
set savedDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set theResult to theNames as text
set AppleScript's text item delimiters to savedDelimiters
return theResult
"""
)
// MARK: - RECORD
/// Reads a few properties of a single item.
///
/// The record is assembled as text rather than returned as an AppleScript record, since
/// that is the form `.record` parses. Keep it flat: nested records and lists are not
/// supported — use `.json` for those.
///
/// - Parameter itemPath: **SET AT RUNTIME**: POSIX path of the item to inspect.
/// - Returns: A `[String: Any]` with `itemName` (`String`), `itemSize` (`Int`) and
/// `isFolder` (`Bool`).
static let itemProperties = AppleScriptBridge.AppleScriptObject(
name: "itemProperties",
returnType: .record,
script: """
tell application id "\(targetApp)"
set theItem to (POSIX file "$itemPath" as alias)
set theName to name of theItem
set theSize to (size of theItem) as integer
set theIsFolder to (class of theItem is folder)
end tell
return "{itemName:\\"" & theName & "\\", itemSize:" & theSize & ", isFolder:" & theIsFolder & "}"
"""
)
// MARK: - JSON
/// Reads the same properties for every item in a folder, as nested JSON.
///
/// `.record` only handles one flat record, so anything nested — a list of records, here —
/// has to be built as a JSON string inside the script and parsed with `.json`.
///
/// Note the `escapeText` handler: values coming from the file system can contain quotes
/// and backslashes, and they have to be escaped on the way out just as the bridge escapes
/// them on the way in. Skipping this produces JSON that fails to parse, and you get `nil`.
///
/// - Parameter folderPath: **SET AT RUNTIME**: POSIX path of the folder to read.
/// - Returns: A `[String: Any]` with `count` (`Int`) and `items`, an array of dictionaries
/// carrying `name` and `size`.
static let folderContentsAsJSON = AppleScriptBridge.AppleScriptObject(
name: "folderContentsAsJSON",
returnType: .json,
script: """
on escapeText(theText)
set savedDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to "\\\\"
set theParts to text items of theText
set AppleScript's text item delimiters to "\\\\\\\\"
set theText to theParts as text
set AppleScript's text item delimiters to "\\""
set theParts to text items of theText
set AppleScript's text item delimiters to "\\\\\\""
set theText to theParts as text
set AppleScript's text item delimiters to savedDelimiters
return theText
end escapeText
tell application id "\(targetApp)"
set theItems to every item of (POSIX file "$folderPath" as alias)
end tell
set theEntries to {}
repeat with anItem in theItems
tell application id "\(targetApp)"
set theName to name of anItem
set theSize to (size of anItem) as integer
end tell
set end of theEntries to "{\\"name\\":\\"" & escapeText(theName) & "\\",\\"size\\":" & theSize & "}"
end repeat
set savedDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to ","
set theArray to theEntries as text
set AppleScript's text item delimiters to savedDelimiters
return "{\\"count\\":" & (count of theEntries) & ",\\"items\\":[" & theArray & "]}"
"""
)
// MARK: - WILDCARD
/// Reads a property that answers with a constant rather than with a value, without coercing it.
///
/// A disk's `format` is one of the constants in the Finder's `edfm` enumeration — `APFS format`
/// is `'dfap'`, `ExFAT format` is `'dfxf'` — and none of the coercing return types can carry
/// one: `.string` yields `nil` and `.int` yields `0`. `.wildCard` hands over what the Apple event
/// actually carried, so the constant arrives as `.constant` with its four-character code intact.
///
/// The same applies to any property whose *type* depends on state, which is the case this return
/// type exists for: a number most of the time, `missing value` when there is nothing to report.
///
/// - Parameter diskName: **SET AT RUNTIME**: Name of the disk to inspect, without a colon.
/// - Returns: An `AppleScriptValue`, `.constant` for any disk the Finder can describe.
static let diskFormat = AppleScriptBridge.AppleScriptObject(
name: "diskFormat",
returnType: .wildCard,
script: """
tell application id "\(targetApp)"
return format of disk "$diskName"
end tell
"""
)
// MARK: - OSTYPE
/// Reads the same property as `diskFormat`, declaring up front that it answers with a constant.
///
/// A disk's `format` is always one of the Finder's `edfm` constants, so there is no type to
/// discover at the call site — only a code to compare. `.osType` says so and hands the raw
/// `FourCharCode` over directly, where `.wildCard` would wrap it in `.constant` and leave the
/// caller to switch. Use `.wildCard` when the type varies, this when it does not.
///
/// - Parameter diskName: **SET AT RUNTIME**: Name of the disk to inspect, without a colon.
/// - Returns: A `FourCharCode`: one of the codes the Finder's dictionary documents, `'msng'` if the
/// Finder has no format to report for that disk, or `nil` if what came back was not a constant at all.
static let diskFormatConstant = AppleScriptBridge.AppleScriptObject(
name: "diskFormatConstant",
returnType: .osType,
script: """
tell application id "\(targetApp)"
return format of disk "$diskName"
end tell
"""
)
// MARK: - VARIABLES AND RAW VALUES
/// Creates a folder inside a parent folder, showing how the three placeholder forms differ.
///
/// `"$parentPath"` and `"$folderName"` are quoted, so they arrive as text with their quotes
/// and backslashes already escaped by the bridge. `$revealAfter` is bare, so it arrives as a
/// real AppleScript boolean and needs no coercion.
///
/// - Parameter parentPath: **SET AT RUNTIME**: POSIX path of the parent folder.
/// - Parameter folderName: **SET AT RUNTIME**: Name of the folder to create.
/// - Parameter revealAfter: **SET AT RUNTIME**: Whether to reveal the new folder afterwards.
/// - Returns: A `String` with the POSIX path of the new folder, or an empty string on failure.
static let createFolder = AppleScriptBridge.AppleScriptObject(
name: "createFolder",
returnType: .string,
script: """
tell application id "\(targetApp)"
try
set theParent to (POSIX file "$parentPath" as alias)
set theFolder to make new folder at theParent with properties {name:"$folderName"}
if $revealAfter then reveal theFolder
return POSIX path of (theFolder as alias)
on error
return ""
end try
end tell
"""
)
/// Moves several items to a destination folder in a single script.
///
/// The paths are passed as a Swift `[String]`, which the bridge renders as an AppleScript list
/// with every element escaped. The placeholder is written bare — `$itemPaths`, not
/// `"$itemPaths"` — because it renders as a list literal rather than as text. See
/// `moveItems(_:to:)` below.
///
/// - Parameter itemPaths: **SET AT RUNTIME**: POSIX paths of the items to move, as `[String]`.
/// - Parameter destinationPath: **SET AT RUNTIME**: POSIX path of the destination folder.
/// - Returns: An `Int` with the number of items moved.
static let moveItems = AppleScriptBridge.AppleScriptObject(
name: "moveItems",
returnType: .int,
script: """
set thePaths to $itemPaths
set movedCount to 0
tell application id "\(targetApp)"
set theDestination to (POSIX file "$destinationPath" as alias)
repeat with aPath in thePaths
try
move (POSIX file aPath as alias) to theDestination
set movedCount to movedCount + 1
end try
end repeat
end tell
return movedCount
"""
)
}
// MARK: - CALLING THE SCRIPTS
/// Example call sites, showing how each return type comes back into Swift.
enum FinderTasks {
/// Counts the items in a folder.
///
/// - Parameter url: The folder to count.
/// - Returns: The number of items, or `0` if the script failed.
static func itemCount(in url: URL) -> Int {
do {
let result = try AppleScriptBridge.executeAppleScript(
AppleScripts.countItemsInFolder,
with: ["folderPath": url.path(percentEncoded: false)]
)
return result as? Int ?? 0
} catch let error as AppleScriptBridge.AppleScriptError {
print(error.description)
return 0
} catch {
print(error.localizedDescription)
return 0
}
}
/// Lists the names of the items in a folder.
///
/// - Parameter url: The folder to read.
/// - Returns: The item names, or an empty array if the script failed.
static func itemNames(in url: URL) -> [String] {
let result = try? AppleScriptBridge.executeAppleScript(
AppleScripts.itemNamesInFolder,
with: ["folderPath": url.path(percentEncoded: false)]
)
return result as? [String] ?? []
}
/// Reads the name, size and kind of a single item.
///
/// - Parameter url: The item to inspect.
/// - Returns: A tuple of the item's name, size and whether it is a folder, or `nil` on failure.
static func properties(of url: URL) -> (name: String, size: Int, isFolder: Bool)? {
guard
let result = try? AppleScriptBridge.executeAppleScript(
AppleScripts.itemProperties,
with: ["itemPath": url.path(percentEncoded: false)]
) as? [String: Any],
let name = result["itemName"] as? String,
let size = result["itemSize"] as? Int,
let isFolder = result["isFolder"] as? Bool
else { return nil }
return (name, size, isFolder)
}
/// Reads every item in a folder as nested JSON.
///
/// - Parameter url: The folder to read.
/// - Returns: Each item's name and size, or an empty array on failure.
static func contents(of url: URL) -> [(name: String, size: Int)] {
guard
let result = try? AppleScriptBridge.executeAppleScript(
AppleScripts.folderContentsAsJSON,
with: ["folderPath": url.path(percentEncoded: false)]
) as? [String: Any],
let items = result["items"] as? [[String: Any]]
else { return [] }
return items.compactMap { entry in
guard let name = entry["name"] as? String, let size = entry["size"] as? Int else { return nil }
return (name, size)
}
}
/// Reads the filesystem format of a disk.
///
/// The shape of a `.wildCard` call site: cast the result once, then switch on the type the script
/// actually answered with rather than on the one you hoped for. Constants carry no meaning of their
/// own — what `'dfap'` means comes from the Finder's dictionary — so the codes are compared here
/// against the ones that dictionary documents.
///
/// - Parameter name: The disk to inspect, for example `"Macintosh HD"`.
/// - Returns: The format's name, or a description of what came back instead.
static func format(ofDisk name: String) -> String {
let result = try? AppleScriptBridge.executeAppleScript(
AppleScripts.diskFormat,
with: ["diskName": name]
)
switch result as? AppleScriptBridge.AppleScriptValue {
case .constant(let code):
let format = String(appleScriptFourCharCode: code)
switch format {
case "dfap": return "APFS"
case "dfh+": return "Mac OS Extended"
case "dfxf": return "ExFAT"
case "dfsm": return "SMB"
default: return "other (\(format))"
}
case .missingValue: return "no format reported"
case .none: return "the script failed"
default: return "unexpected type"
}
}
/// Reads the filesystem format of a disk as its four-character code.
///
/// The shape of an `.osType` call site, which is the whole point of the return type: one cast, then
/// a comparison against the codes the Finder's dictionary documents. Nothing to switch on, since the
/// property cannot answer with anything but a constant.
///
/// `missing value` is a constant too, and `.osType` hands it over as the code `'msng'` rather than as
/// `nil` — so it has to be ruled out before a comparison can mean anything, or a disk the Finder
/// cannot describe would be reported as "some other format". Everything this function cannot read
/// collapses into `nil`; declare `.wildCard` instead where a failed script, an absent value and an
/// unexpected type have to be told apart.
///
/// - Parameter name: The disk to inspect, for example `"Macintosh HD"`.
/// - Returns: `true` if the disk is APFS-formatted, `false` for any other format the Finder names,
/// `nil` if the script failed or the Finder reported no format at all.
static func isAPFS(disk name: String) -> Bool? {
let result = try? AppleScriptBridge.executeAppleScript(
AppleScripts.diskFormatConstant,
with: ["diskName": name]
)
guard let code = result as? FourCharCode, code != FourCharCode(cMissingValue) else { return nil }
return code == "dfap".appleScriptFourCharCode
}
/// Moves several items to a destination folder.
///
/// Shows a Swift collection crossing over as an AppleScript list: the `[String]` is rendered as
/// `{"...", "..."}` with each path escaped on the way in, so a filename containing a quote
/// cannot break out of its literal. Dictionaries cross over the same way, as records, and the
/// two nest — an `[[String: Any]]` arrives as a list of records.
///
/// `AppleScriptRawValue` is still there for source no type mapping covers, such as an
/// expression or a terminology fragment the caller assembled:
/// `"target": AppleScriptBridge.AppleScriptRawValue("front window")`.
///
/// - Parameters:
/// - urls: The items to move.
/// - destination: The folder to move them into.
/// - Returns: The number of items actually moved.
static func moveItems(_ urls: [URL], to destination: URL) -> Int {
let result = try? AppleScriptBridge.executeAppleScript(
AppleScripts.moveItems,
with: [
"itemPaths": urls.map { $0.path(percentEncoded: false) },
"destinationPath": destination.path(percentEncoded: false)
]
)
return result as? Int ?? 0
}
}