Branchwell

Textley / app · textley.ai / Sources / Textley / FinderColorLabel.swift

1import AppKit
2import Darwin
3
4enum FinderColorLabel: Int, CaseIterable, Sendable {
5 case red = 6
6 case orange = 7
7 case yellow = 5
8 case green = 2
9 case blue = 4
10 case purple = 3
11 case gray = 1
12
13 // Finder stores each tag as its name followed by a newline and a color index.
14 private static let attribute = "com.apple.metadata:_kMDItemUserTags"
15
16 var name: String { NSWorkspace.shared.fileLabels[rawValue] }
17 var color: NSColor { NSWorkspace.shared.fileLabelColors[rawValue] }
18 private var tag: String { "\(name)\n\(rawValue)" }
19
20 static func colors(at url: URL) -> [Self] {
21 let tags = (try? readTags(at: url)) ?? legacyTag(at: url)
22 let colors = Set(tags.compactMap { tag in
23 tag.lastIndex(of: "\n")
24 .flatMap { Int(tag[tag.index(after: $0)...]) }
25 .flatMap(Self.init(rawValue:))
26 })
27 return allCases.filter(colors.contains)
28 }
29
30 static func standardColors(at url: URL) -> Set<Self> {
31 let tags = Set((try? readTags(at: url)) ?? legacyTag(at: url))
32 return Set(allCases.filter { tags.contains($0.tag) })
33 }
34
35 func toggle(at url: URL) throws {
36 var coordinationError: NSError?
37 var writeError: Error?
38 NSFileCoordinator().coordinate(writingItemAt: url, options: [], error: &coordinationError) { coordinatedURL in
39 do {
40 let storedTags = try Self.readTags(at: coordinatedURL)
41 let legacy = storedTags == nil ? Self.legacyTag(at: coordinatedURL) : []
42 var tags = storedTags ?? legacy
43 if tags.contains(tag) {
44 tags.removeAll { $0 == tag }
45 } else {
46 tags.append(tag)
47 }
48 let bytes = try PropertyListSerialization.data(fromPropertyList: tags, format: .binary, options: 0)
49 try coordinatedURL.withUnsafeFileSystemRepresentation { path in
50 guard let path else { throw CocoaError(.fileWriteInvalidFileName) }
51 let status = bytes.withUnsafeBytes {
52 setxattr(path, Self.attribute, $0.baseAddress, $0.count, 0, XATTR_NOFOLLOW)
53 }
54 guard status == 0 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }
55 }
56 if !legacy.isEmpty {
57 try (coordinatedURL as NSURL).setResourceValue(0, forKey: .labelNumberKey)
58 }
59 } catch {
60 writeError = error
61 }
62 }
63 if let coordinationError { throw coordinationError }
64 if let writeError { throw writeError }
65 }
66
67 private static func legacyTag(at url: URL) -> [String] {
68 let freshURL = URL(fileURLWithPath: url.path)
69 guard let index = try? freshURL.resourceValues(forKeys: [.labelNumberKey]).labelNumber,
70 let color = Self(rawValue: index) else { return [] }
71 return [color.tag]
72 }
73
74 private static func readTags(at url: URL) throws -> [String]? {
75 try url.withUnsafeFileSystemRepresentation { path in
76 guard let path else { throw CocoaError(.fileReadInvalidFileName) }
77 let size = getxattr(path, attribute, nil, 0, 0, XATTR_NOFOLLOW)
78 if size == -1 && errno == ENOATTR { return nil }
79 guard size >= 0 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }
80 var bytes = Data(count: size)
81 let count = bytes.withUnsafeMutableBytes {
82 getxattr(path, attribute, $0.baseAddress, size, 0, XATTR_NOFOLLOW)
83 }
84 guard count >= 0 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }
85 guard let tags = try PropertyListSerialization.propertyList(from: bytes.prefix(count), format: nil) as? [String] else {
86 throw CocoaError(.fileReadCorruptFile)
87 }
88 return tags
89 }
90 }
91}