use crate::error::IpcError;
#[cfg(unix)]
use std::path::PathBuf;
#[cfg(unix)]
use std::os::unix::net::UnixStream;
#[cfg(windows)]
use crate::windows_pipe::{NamedPipeStream, connect_named_pipe};
#[cfg(unix)]
pub(crate) fn connect_to_daemon() -> Result<UnixStream, IpcError> {
let socket_path = get_socket_path()?;
UnixStream::connect(socket_path)
.map_err(IpcError::ConnectionFailed)
}
#[cfg(windows)]
pub(crate) fn connect_to_daemon() -> Result<NamedPipeStream, IpcError> {
let pipe_path = get_pipe_path();
connect_named_pipe(&pipe_path)
.map_err(IpcError::ConnectionFailed)
}
#[cfg(unix)]
fn get_socket_path() -> Result<PathBuf, IpcError> {
if let Ok(path) = std::env::var("KODEGEND_STATUS_SOCKET") {
return Ok(PathBuf::from(path));
}
let user_socket = dirs::runtime_dir()
.or_else(dirs::data_local_dir)
.map(|dir| dir.join("kodegend").join("status.sock"));
if let Some(path) = &user_socket
&& path.exists() {
return Ok(path.clone());
}
let system_socket = PathBuf::from("/var/run/kodegend/status.sock");
if system_socket.exists() {
return Ok(system_socket);
}
user_socket.ok_or(IpcError::SocketPathNotFound)
}
#[cfg(windows)]
fn get_pipe_path() -> String {
if let Ok(path) = std::env::var("KODEGEND_STATUS_PIPE") {
return path;
}
r"\\.\pipe\kodegend\status".to_string()
}