Skip to content

Instantly share code, notes, and snippets.

@alanzeino
Last active March 5, 2021 01:30
Show Gist options
  • Save alanzeino/d344a95a4af1f1991aa0188465023b4d to your computer and use it in GitHub Desktop.
Save alanzeino/d344a95a4af1f1991aa0188465023b4d to your computer and use it in GitHub Desktop.
#!/usr/bin/swift
// Run: $ swift noCrashplan.swift
// Background: https://github.com/KrauseFx/overkill/issues/3#issuecomment-270505227
import Foundation
import Cocoa
import ServiceManagement
let badApps = [ "Code42 CrashPlan", "CrashPlanService", "CrashPlanLauncher", "CrashPlanWeb" ]
class Thing {
let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
return dateFormatter
}()
func createListener() {
let workspaceNotificationCenter = NSWorkspace.shared.notificationCenter
workspaceNotificationCenter.addObserver(self, selector: #selector(self.appWillLaunch(note:)), name: NSWorkspace.willLaunchApplicationNotification, object: nil)
}
func scriptFirstLaunched() {
let runningApplications = NSWorkspace.shared.runningApplications
for currentApp in runningApplications.enumerated() {
let runningApp = runningApplications[currentApp.offset]
guard let appName = runningApp.localizedName else { continue }
log("Current running applications: \(appName)")
if badApps.contains(appName) {
self.terminateProcessWith(Int(runningApp.processIdentifier), appName)
}
}
}
@objc func appWillLaunch(note: Notification) {
guard let processName: String = note.userInfo?["NSApplicationName"] as? String else { return }
guard let processId = note.userInfo?["NSApplicationProcessIdentifier"] as? Int else { return }
if badApps.contains(processName) {
self.terminateProcessWith(processId, processName)
}
}
func terminateProcessWith(_ processId: Int,_ processName: String) {
log("Attempting to terminate \(processName) with pid \(processId)")
guard let process = NSRunningApplication.init(processIdentifier: pid_t(processId)) else { return }
let result = process.forceTerminate()
switch result {
case true: log("Terminated \(processName) successfully.")
case false: log("Unable to terminate \(processName).")
}
}
func log(_ message: String) {
print("[\(dateFormatter.string(from: Date()))] \(message)")
}
}
let thing = Thing()
thing.scriptFirstLaunched()
thing.createListener()
RunLoop.main.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment