55 lines
1.4 KiB
Rust
55 lines
1.4 KiB
Rust
//! Background bash control — list, cancel, and inspect background processes.
|
|||
|
|
|
||
|
|
use std::collections::HashMap;
|
||
|
|
use std::sync::{Arc, Mutex};
|
||
|
|
|
||
|
|
use super::job::BashJob;
|
||
|
|
|
||
|
|
/// Central registry of all running background bash jobs.
|
||
|
|
pub struct BashControl {
|
||
|
|
jobs: Mutex<HashMap<String, Arc<BashJob>>>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl BashControl {
|
||
|
|
pub fn new() -> Self {
|
||
|
|
BashControl {
|
||
|
|
jobs: Mutex::new(HashMap::new()),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Register a new background job.
|
||
|
|
pub fn register(&self, job: Arc<BashJob>) {
|
||
|
|
if let Ok(mut guard) = self.jobs.lock() {
|
||
|
|
guard.insert(job.id.clone(), job);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Cancel a job by ID.
|
||
|
|
pub fn cancel(&self, id: &str) -> bool {
|
||
|
|
if let Ok(mut guard) = self.jobs.lock() {
|
||
|
|
if let Some(job) = guard.remove(id) {
|
||
|
|
job.cancel();
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
false
|
||
|
|
}
|
||
|
|
|
||
|
|
/// List all active jobs.
|
||
|
|
pub fn list(&self) -> Vec<(String, String, bool)> {
|
||
|
|
let mut guard = self.jobs.lock().unwrap();
|
||
|
|
guard.retain(|_, j| j.is_running());
|
||
|
|
guard
|
||
|
|
.iter()
|
||
|
|
.map(|(id, job)| (id.clone(), job.command.clone(), job.is_running()))
|
||
|
|
.collect()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Clean up completed jobs.
|
||
|
|
pub fn prune(&self) {
|
||
|
|
if let Ok(mut guard) = self.jobs.lock() {
|
||
|
|
guard.retain(|_, j| j.is_running());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|