Skip to content

Commit

Permalink
fix: service start/stop on MacOS (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
medcl authored Feb 20, 2024
1 parent 26671e8 commit 64c8add
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions src/launchd.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use super::{
utils, ServiceInstallCtx, ServiceLevel, ServiceManager, ServiceStartCtx, ServiceStopCtx,
ServiceUninstallCtx,
utils, ServiceInstallCtx, ServiceLevel, ServiceManager, ServiceStartCtx,
ServiceStopCtx, ServiceUninstallCtx,
};
use plist::Dictionary;
use plist::Value;
use plist::{Dictionary, Value};
use std::{
ffi::OsStr,
io,
Expand Down Expand Up @@ -77,6 +76,16 @@ impl LaunchdServiceManager {
user: self.user,
}
}

fn get_plist_path(&self, qualified_name: String) -> PathBuf {
let dir_path = if self.user {
user_agent_dir_path().unwrap()
} else {
global_daemon_dir_path()
};
let plist_path = dir_path.join(format!("{}.plist", qualified_name));
plist_path
}
}

impl ServiceManager for LaunchdServiceManager {
Expand Down Expand Up @@ -121,24 +130,24 @@ impl ServiceManager for LaunchdServiceManager {
}

fn uninstall(&self, ctx: ServiceUninstallCtx) -> io::Result<()> {
let dir_path = if self.user {
user_agent_dir_path()?
} else {
global_daemon_dir_path()
};
let qualified_name = ctx.label.to_qualified_name();
let plist_path = dir_path.join(format!("{}.plist", qualified_name));
let plist_path = self.get_plist_path(ctx.label.to_qualified_name());

launchctl("unload", plist_path.to_string_lossy().as_ref())?;
std::fs::remove_file(plist_path)
}

fn start(&self, ctx: ServiceStartCtx) -> io::Result<()> {
let plist_path = self.get_plist_path(ctx.label.to_qualified_name());

launchctl("load", plist_path.to_string_lossy().as_ref())?;
launchctl("start", &ctx.label.to_qualified_name())
}

fn stop(&self, ctx: ServiceStopCtx) -> io::Result<()> {
launchctl("stop", &ctx.label.to_qualified_name())
let plist_path = self.get_plist_path(ctx.label.to_qualified_name());

let _ =launchctl("stop", &ctx.label.to_qualified_name());
launchctl("unload", plist_path.to_string_lossy().as_ref())
}

fn level(&self) -> ServiceLevel {
Expand Down Expand Up @@ -192,15 +201,20 @@ fn global_daemon_dir_path() -> PathBuf {

fn user_agent_dir_path() -> io::Result<PathBuf> {
Ok(dirs::home_dir()
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Unable to locate home directory"))?
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Unable to locate home directory",
)
})?
.join("Library")
.join("LaunchAgents"))
}

fn make_plist<'a>(
config: &LaunchdInstallConfig,
label: &str,
args: impl Iterator<Item = &'a OsStr>,
args: impl Iterator<Item=&'a OsStr>,
username: Option<String>,
working_directory: Option<PathBuf>,
environment: Option<Vec<(String, String)>>,
Expand Down

0 comments on commit 64c8add

Please sign in to comment.