Skip to content

Commit

Permalink
✨ Trigger hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
oschrenk committed Jan 25, 2025
1 parent 504143e commit ed9fb15
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
3 changes: 2 additions & 1 deletion Sources/Cli/Watch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ struct Watch: ParsableCommand {

mutating func run() {
let repo = EventRepo()
repo.registerForEventStoreChanges()
let hooks = Loader.readConfig()?.hooks ?? []
repo.registerForEventStoreChanges(hooks: hooks)
dispatchMain()
}
}
15 changes: 15 additions & 0 deletions Sources/Config.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import Foundation

struct Config: Codable {
let iconize: [Rule]?
let hooks: [Hook]?
Expand All @@ -12,4 +14,17 @@ struct Rule: Codable {
struct Hook: Codable {
let path: String
let args: [String]?

func trigger() {
let task = Process()
task.executableURL = URL(fileURLWithPath: path)
task.arguments = args ?? []
do {
try task.run()
task.waitUntilExit()
print("Fired event \(path) with args \(args ?? [])")
} catch {
print("Failed to execute command \(path): \(error)")
}
}
}
11 changes: 7 additions & 4 deletions Sources/IO/EventRepo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import EventKit

final class EventRepo {
private let eventStore = EKEventStore()
private var hooks: [Hook] = []

private func grantAccess() -> EKEventStore {
if #available(macOS 14, *) {
Expand Down Expand Up @@ -93,18 +94,20 @@ final class EventRepo {
StdOut.print("Saved Event")
}

/// Register for EKEventStoreChangedNotification
func registerForEventStoreChanges() {
func registerForEventStoreChanges(hooks: [Hook]) {
self.hooks = hooks
NotificationCenter.default.addObserver(
self,
selector: #selector(eventStoreChanged(_:)),
name: .EKEventStoreChanged,
object: eventStore
object: nil // Listen to all EKEventStore changes
)
}

@objc private func eventStoreChanged(_: Notification) {
print("Event store has changed!")
for hook in hooks {
hook.trigger()
}
}

deinit {
Expand Down

0 comments on commit ed9fb15

Please sign in to comment.