forked from raycast/script-commands
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopy-last-download.swift
executable file
·43 lines (34 loc) · 1.13 KB
/
copy-last-download.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
#!/usr/bin/swift
// Required parameters:
// @raycast.schemaVersion 1
// @raycast.title Copy Last Download
// @raycast.mode silent
// @raycast.packageName System
//
// Optional parameters:
// @raycast.icon 💁
import AppKit
// MARK: - Main
guard let download = getLatestDownload() else {
print("No recent downloads")
exit(1)
}
copyToPasteboard(download)
print("Copied \(download.lastPathComponent)")
// MARK: - Convenience
func getLatestDownload() -> URL? {
guard let downloadsDirectory = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first else { return nil }
return try? FileManager.default
.contentsOfDirectory(at: downloadsDirectory, includingPropertiesForKeys: [.addedToDirectoryDateKey], options: .skipsHiddenFiles)
.sorted { $0.addedToDirectoryDate > $1.addedToDirectoryDate }
.first
}
func copyToPasteboard(_ url: URL) {
NSPasteboard.general.clearContents()
NSPasteboard.general.writeObjects([url as NSPasteboardWriting])
}
extension URL {
var addedToDirectoryDate: Date {
return (try? resourceValues(forKeys: [.addedToDirectoryDateKey]).addedToDirectoryDate) ?? .distantPast
}
}