proc_cli/commands/
orphans.rs1use crate::core::{apply_filters, Process};
10use crate::error::Result;
11use crate::ui::{plural, Printer};
12use clap::Args;
13use dialoguer::Confirm;
14
15#[derive(Args, Debug)]
17pub struct OrphansCommand {
18 #[arg(long, short = 'k')]
20 pub kill: bool,
21
22 #[arg(long)]
24 pub dry_run: bool,
25
26 #[arg(long, short = 'y')]
28 pub yes: bool,
29
30 #[arg(long, short = 'j')]
32 pub json: bool,
33
34 #[arg(long, short = 'v')]
36 pub verbose: bool,
37
38 #[arg(long = "in", short = 'i', num_args = 0..=1, default_missing_value = ".")]
40 pub in_dir: Option<String>,
41
42 #[arg(long = "by", short = 'b')]
44 pub by_name: Option<String>,
45}
46
47impl OrphansCommand {
48 pub fn execute(&self) -> Result<()> {
50 let printer = Printer::from_flags(self.json, self.verbose);
51
52 let mut processes = Process::find_orphans()?;
53
54 apply_filters(&mut processes, &self.in_dir, &self.by_name);
56
57 if processes.is_empty() {
58 printer.print_empty_result("orphans", "No orphaned processes found");
59 return Ok(());
60 }
61
62 printer.warning(&format!(
63 "Found {} orphaned process{}",
64 processes.len(),
65 plural(processes.len())
66 ));
67 printer.print_processes_as("orphans", &processes, None);
68
69 if self.kill && self.dry_run {
71 printer.warning(&format!(
72 "Dry run: would kill {} orphaned process{}",
73 processes.len(),
74 plural(processes.len())
75 ));
76 return Ok(());
77 }
78
79 if self.kill {
81 if !self.yes && !self.json {
82 let confirmed = Confirm::new()
83 .with_prompt(format!(
84 "Kill {} orphaned process{}?",
85 processes.len(),
86 plural(processes.len())
87 ))
88 .default(false)
89 .interact()?;
90
91 if !confirmed {
92 printer.warning("Cancelled");
93 return Ok(());
94 }
95 }
96
97 let mut killed = Vec::new();
98 let mut failed = Vec::new();
99
100 for proc in processes {
101 match proc.kill_and_wait() {
102 Ok(_) => killed.push(proc),
103 Err(e) => failed.push((proc, e.to_string())),
104 }
105 }
106
107 printer.print_kill_result(&killed, &failed);
108 }
109
110 Ok(())
111 }
112}