Skip to content

Instantly share code, notes, and snippets.

@stephancasas
Created June 26, 2024 22:20
Show Gist options
  • Save stephancasas/ffe915eeb9b8a70f16102eb4b99eeec7 to your computer and use it in GitHub Desktop.
Save stephancasas/ffe915eeb9b8a70f16102eb4b99eeec7 to your computer and use it in GitHub Desktop.
A type representing a Mach service's launchd info property list
//
// MachServiceLaunchInfo.swift
//
//
// Created by Stephan Casas on 6/26/24.
//
import Foundation;
/// A type representing a Mach service's `launchd` information property list.
struct MachServiceLaunchInfo: Encodable {
let label: String;
let machServices: [String: Bool];
let program: String;
let programArguments: [String];
/// Create a new `launchd` information representation with the given properties.
init(label: String, machServices: [String : Bool], program: String, programArguments: [String]) {
self.label = label
self.machServices = machServices
self.program = program
self.programArguments = programArguments
}
enum CodingKeys: CodingKey {
case Label, MachServices, Program, ProgramArguments;
}
func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self);
try container.encode(self.label, forKey: .Label);
try container.encode(self.machServices, forKey: .MachServices);
try container.encode(self.program, forKey: .Program);
try container.encode(self.programArguments, forKey: .ProgramArguments);
}
}
// MARK: - Privileged Helper Tools
extension MachServiceLaunchInfo {
/// Create a new `launchd` information representation for a privileged helper tool with the given program name.
static func launchInfoForPrivilegedHelperTool(named programName: String) -> MachServiceLaunchInfo {
let execPath = "/Library/PrivilegedHelperTools/\(programName)";
return .init(
label: programName,
machServices: [programName: true],
program: execPath,
programArguments: [execPath]);
}
/// Create and write a `launchd` information property list for a privileged helper tool with the given program name.
static func writeLaunchInfoForPrivilegedHelperTool(named programName: String) throws {
let encoder = PropertyListEncoder();
encoder.outputFormat = .xml;
try encoder.encode(Self.launchInfoForPrivilegedHelperTool(named: programName))
.write(to: .init(filePath: "/Library/LaunchDaemons/\(programName).plist"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment