1use crate::core::filters::resolve_dir;
15use crate::core::{
16 flatten_targets, resolve_in_dir, sort_processes, NameMatch, Process, SortKey, StatusFilter,
17};
18use crate::error::Result;
19use crate::ui::Printer;
20use clap::Args;
21use std::path::PathBuf;
22
23#[derive(Args, Debug)]
25pub struct ListCommand {
26 #[arg(num_args = 0..)]
28 pub name: Vec<String>,
29
30 #[arg(long)]
32 pub cmd: bool,
33
34 #[arg(long = "in", short = 'i', num_args = 0..=1, default_missing_value = ".")]
37 pub in_dir: Option<String>,
38
39 #[arg(long, short = 'p')]
41 pub path: Option<String>,
42
43 #[arg(long)]
45 pub min_cpu: Option<f32>,
46
47 #[arg(long)]
49 pub min_mem: Option<f64>,
50
51 #[arg(long, value_enum, ignore_case = true)]
53 pub status: Option<StatusFilter>,
54
55 #[arg(long)]
57 pub min_uptime: Option<u64>,
58
59 #[arg(long)]
61 pub parent: Option<u32>,
62
63 #[arg(long, short = 'j')]
65 pub json: bool,
66
67 #[arg(long, short = 'v')]
69 pub verbose: bool,
70
71 #[arg(long, short = 'w')]
73 pub wide: bool,
74
75 #[arg(long, short = 'n')]
77 pub limit: Option<usize>,
78
79 #[arg(long, short = 's', value_enum, default_value_t = SortKey::Cpu)]
81 pub sort: SortKey,
82}
83
84impl ListCommand {
85 pub fn execute(&self) -> Result<()> {
87 let printer = Printer::from_flags(self.json, self.verbose).wide(self.wide);
88
89 let mut processes = if !self.name.is_empty() {
92 let names = flatten_targets(&self.name);
93 let mut all = Vec::new();
94 let mut seen = std::collections::HashSet::new();
95 for n in &names {
96 if let Ok(found) = Process::find_by_name(n, NameMatch::from_flag(self.cmd)) {
97 for p in found {
98 if seen.insert(p.pid) {
99 all.push(p);
100 }
101 }
102 }
103 }
104 all
105 } else {
106 Process::find_all()?
107 };
108
109 Process::measure_cpu(&mut processes);
111
112 let in_dir_filter = resolve_in_dir(&self.in_dir);
114
115 let path_filter: Option<PathBuf> =
117 self.path.as_ref().map(|p| resolve_dir(PathBuf::from(p)));
118
119 processes.retain(|p| self.keeps(p, &in_dir_filter, &path_filter));
121
122 sort_processes(&mut processes, self.sort);
124
125 if let Some(limit) = self.limit {
127 processes.truncate(limit);
128 }
129
130 let context = in_dir_filter
132 .as_ref()
133 .map(|p| format!("in {}", p.display()));
134
135 printer.print_processes_with_context(&processes, context.as_deref());
136 Ok(())
137 }
138
139 fn keeps(
142 &self,
143 p: &Process,
144 in_dir_filter: &Option<PathBuf>,
145 path_filter: &Option<PathBuf>,
146 ) -> bool {
147 if let Some(ref dir_path) = in_dir_filter {
149 if let Some(ref proc_cwd) = p.cwd {
150 if !crate::core::filters::cwd_within(proc_cwd, dir_path) {
151 return false;
152 }
153 } else {
154 return false;
155 }
156 }
157
158 if let Some(ref exe_path) = path_filter {
160 if let Some(ref proc_exe) = p.exe_path {
161 let proc_path = PathBuf::from(proc_exe);
162 if !proc_path.starts_with(exe_path) {
163 return false;
164 }
165 } else {
166 return false;
167 }
168 }
169
170 if let Some(min_cpu) = self.min_cpu {
172 if p.cpu_percent < min_cpu {
173 return false;
174 }
175 }
176
177 if let Some(min_mem) = self.min_mem {
179 if p.memory_mb < min_mem {
180 return false;
181 }
182 }
183
184 if let Some(status) = self.status {
186 if !status.matches(p.status) {
187 return false;
188 }
189 }
190
191 if let Some(min_uptime) = self.min_uptime {
193 if let Some(start_time) = p.start_time {
194 let now = std::time::SystemTime::now()
195 .duration_since(std::time::UNIX_EPOCH)
196 .map(|d| d.as_secs())
197 .unwrap_or(0);
198 if now.saturating_sub(start_time) < min_uptime {
199 return false;
200 }
201 } else {
202 return false;
203 }
204 }
205
206 if let Some(ppid) = self.parent {
208 if p.parent_pid != Some(ppid) {
209 return false;
210 }
211 }
212
213 true
214 }
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use crate::core::ProcessStatus;
221
222 fn command() -> ListCommand {
223 ListCommand {
224 name: Vec::new(),
225 cmd: false,
226 in_dir: None,
227 path: None,
228 min_cpu: None,
229 min_mem: None,
230 status: None,
231 min_uptime: None,
232 parent: None,
233 json: false,
234 verbose: false,
235 wide: false,
236 limit: None,
237 sort: SortKey::Cpu,
238 }
239 }
240
241 fn bare_process() -> Process {
245 Process {
246 pid: 1,
247 name: "x".to_string(),
248 exe_path: None,
249 cwd: None,
250 command: None,
251 argv0: None,
252 raw: None,
253 cpu_percent: 0.0,
254 memory_mb: 0.0,
255 status: ProcessStatus::Sleeping,
256 user: None,
257 parent_pid: None,
258 start_time: None,
259 uptime_secs: None,
260 }
261 }
262
263 #[test]
264 fn a_process_with_no_working_directory_fails_in() {
265 let dir = Some(PathBuf::from("/"));
266 assert!(!command().keeps(&bare_process(), &dir, &None));
267 assert!(command().keeps(&bare_process(), &None, &None));
268 }
269
270 #[test]
271 fn a_process_with_no_executable_fails_path() {
272 let path = Some(PathBuf::from("/usr"));
273 assert!(!command().keeps(&bare_process(), &None, &path));
274 }
275
276 #[test]
277 fn a_process_with_no_start_time_fails_min_uptime() {
278 let cmd = ListCommand {
279 min_uptime: Some(0),
280 ..command()
281 };
282 assert!(!cmd.keeps(&bare_process(), &None, &None));
283 }
284
285 #[test]
286 fn a_process_that_passes_every_filter_is_kept() {
287 let mut process = bare_process();
288 process.cwd = Some("/srv/app".to_string());
289 process.exe_path = Some("/usr/bin/node".to_string());
290 process.start_time = Some(0);
291 process.parent_pid = Some(7);
292 let cmd = ListCommand {
293 min_cpu: Some(0.0),
294 min_mem: Some(0.0),
295 status: Some(StatusFilter::Sleeping),
296 min_uptime: Some(1),
297 parent: Some(7),
298 ..command()
299 };
300 let dir = Some(PathBuf::from("/srv"));
301 let path = Some(PathBuf::from("/usr/bin"));
302 assert!(cmd.keeps(&process, &dir, &path));
303 let other_parent = ListCommand {
305 parent: Some(8),
306 ..command()
307 };
308 assert!(!other_parent.keeps(&process, &dir, &path));
309 }
310
311 #[test]
312 fn each_filter_turns_away_a_process_that_fails_it() {
313 let mut process = bare_process();
314 process.start_time = Some(
315 std::time::SystemTime::now()
316 .duration_since(std::time::UNIX_EPOCH)
317 .unwrap()
318 .as_secs(),
319 );
320 process.memory_mb = 1.0;
321 let turned_away = [
322 ListCommand {
323 min_cpu: Some(50.0),
324 ..command()
325 },
326 ListCommand {
327 min_mem: Some(500.0),
328 ..command()
329 },
330 ListCommand {
331 status: Some(StatusFilter::Zombie),
332 ..command()
333 },
334 ListCommand {
335 min_uptime: Some(3600),
336 ..command()
337 },
338 ListCommand {
339 parent: Some(7),
340 ..command()
341 },
342 ];
343 for cmd in &turned_away {
344 assert!(!cmd.keeps(&process, &None, &None), "{cmd:?}");
345 }
346 }
347}