use crate::bridge::{
build_status, run_tcp_client_stub, run_tcp_listener_stub, run_udp_client_stub, run_udp_listener_stub,
spawn_tcp_listener_daemon, spawn_udp_listener_daemon,
};
use crate::config::{BridgeMode, ResolvedBridgeCommand};
use anyhow::Result;
use tokio::runtime::Runtime;
use serde_json;
pub fn run_bridge_command(cmd: ResolvedBridgeCommand) -> Result<()> {
match cmd {
ResolvedBridgeCommand::Listen(l) if l.mode == BridgeMode::Tcp => {
if l.daemon {
let _ = spawn_tcp_listener_daemon(l);
println!("[bridge] tcp listener daemon started");
} else {
let rt = Runtime::new()?;
rt.block_on(run_tcp_listener_stub(l))?;
println!("[bridge] tcp listener stub finished");
}
}
ResolvedBridgeCommand::Connect(c) if c.mode == BridgeMode::Tcp => {
let rt = Runtime::new()?;
rt.block_on(run_tcp_client_stub(c))?;
println!("[bridge] tcp client stub finished");
}
ResolvedBridgeCommand::Listen(l) if l.mode == BridgeMode::Udp => {
if l.daemon {
let _ = spawn_udp_listener_daemon(l);
println!("[bridge] udp listener daemon started");
} else {
let rt = Runtime::new()?;
rt.block_on(run_udp_listener_stub(l))?;
println!("[bridge] udp listener stub finished");
}
}
ResolvedBridgeCommand::Connect(c) if c.mode == BridgeMode::Udp => {
let rt = Runtime::new()?;
rt.block_on(run_udp_client_stub(c))?;
println!("[bridge] udp client stub finished");
}
ResolvedBridgeCommand::Status(s) => {
let status = build_status(&ResolvedBridgeCommand::Status(s.clone()), None);
let json = serde_json::to_string_pretty(&status)?;
println!("{}", json);
}
_ => unreachable!(),
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn status_runs_without_panic() {
let cmd = ResolvedBridgeCommand::Status(crate::config::ResolvedBridgeStatus {
bind: "127.0.0.1:0".into(),
socket: std::path::PathBuf::from("/tmp/wsl-clip.sock"),
mode: BridgeMode::Tcp,
});
run_bridge_command(cmd).unwrap();
}
#[test]
fn daemon_listen_returns_immediately() {
let cmd = ResolvedBridgeCommand::Listen(crate::config::ResolvedBridgeListen {
bind: "127.0.0.1:0".into(),
mode: BridgeMode::Tcp,
idle_exit: None,
ttl: None,
max_bytes: 1024,
token: None,
token_file: None,
daemon: true,
log_file: None,
});
run_bridge_command(cmd).unwrap();
}
}