Skip to main content

proc_cli/commands/
list.rs

1//! `proc list` - List processes
2//!
3//! Examples:
4//!   proc list                  # List all processes
5//!   proc list node             # Only the processes named node
6//!   proc list node --cmd       # ... or with node anywhere in their command line
7//!   proc list node python      # Several names: separate arguments
8//!   proc list --in             # Processes in current directory
9//!   proc list --in /project    # Processes in /project
10//!   proc list --min-cpu 10     # Processes using >10% CPU
11//!
12//! Commas still work (`proc list node,python`) but are deprecated.
13
14use 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/// List processes
24#[derive(Args, Debug)]
25pub struct ListCommand {
26    /// Process name(s) to filter by (separate arguments for several)
27    #[arg(num_args = 0..)]
28    pub name: Vec<String>,
29
30    /// Match the names as a substring of the process name or full command line (like pkill -f)
31    #[arg(long)]
32    pub cmd: bool,
33
34    /// Filter by directory; takes the next word as the directory unless it starts with '-'
35    /// (bare --in is the current directory, --in=DIR is explicit)
36    #[arg(long = "in", short = 'i', num_args = 0..=1, default_missing_value = ".")]
37    pub in_dir: Option<String>,
38
39    /// Filter by executable path
40    #[arg(long, short = 'p')]
41    pub path: Option<String>,
42
43    /// Only show processes using more than this CPU %
44    #[arg(long)]
45    pub min_cpu: Option<f32>,
46
47    /// Only show processes using more than this memory (MB)
48    #[arg(long)]
49    pub min_mem: Option<f64>,
50
51    /// Filter by status: running, sleeping, stopped, zombie
52    #[arg(long, value_enum, ignore_case = true)]
53    pub status: Option<StatusFilter>,
54
55    /// Only show processes running longer than this (seconds)
56    #[arg(long)]
57    pub min_uptime: Option<u64>,
58
59    /// Only show children of this parent PID
60    #[arg(long)]
61    pub parent: Option<u32>,
62
63    /// Output as JSON
64    #[arg(long, short = 'j')]
65    pub json: bool,
66
67    /// Show verbose output with command line, cwd, parent PID, and uptime
68    #[arg(long, short = 'v')]
69    pub verbose: bool,
70
71    /// Print full directories and arguments instead of fitting the terminal width
72    #[arg(long, short = 'w')]
73    pub wide: bool,
74
75    /// Limit the number of results
76    #[arg(long, short = 'n')]
77    pub limit: Option<usize>,
78
79    /// Sort by: cpu, mem (biggest first); pid, name (ascending). Ties come by PID
80    #[arg(long, short = 's', value_enum, default_value_t = SortKey::Cpu)]
81    pub sort: SortKey,
82}
83
84impl ListCommand {
85    /// Executes the list command, displaying processes matching the filters.
86    pub fn execute(&self) -> Result<()> {
87        let printer = Printer::from_flags(self.json, self.verbose).wide(self.wide);
88
89        // Get base process list (several names as separate arguments; each may
90        // still be a comma-separated list)
91        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        // Real CPU readings for the table, --min-cpu and --sort cpu
110        Process::measure_cpu(&mut processes);
111
112        // Resolve --in filter path
113        let in_dir_filter = resolve_in_dir(&self.in_dir);
114
115        // Resolve path filter
116        let path_filter: Option<PathBuf> =
117            self.path.as_ref().map(|p| resolve_dir(PathBuf::from(p)));
118
119        // Apply filters
120        processes.retain(|p| self.keeps(p, &in_dir_filter, &path_filter));
121
122        // Sort processes
123        sort_processes(&mut processes, self.sort);
124
125        // Apply limit if specified
126        if let Some(limit) = self.limit {
127            processes.truncate(limit);
128        }
129
130        // Build context string for output (e.g., "in /path/to/dir")
131        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    /// Whether a process passes every filter: `--in`, `--path`, `--min-cpu`,
140    /// `--min-mem`, `--status`, `--min-uptime` and `--parent`.
141    fn keeps(
142        &self,
143        p: &Process,
144        in_dir_filter: &Option<PathBuf>,
145        path_filter: &Option<PathBuf>,
146    ) -> bool {
147        // Directory filter (--in)
148        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        // Path filter (executable path)
159        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        // CPU filter
171        if let Some(min_cpu) = self.min_cpu {
172            if p.cpu_percent < min_cpu {
173                return false;
174            }
175        }
176
177        // Memory filter
178        if let Some(min_mem) = self.min_mem {
179            if p.memory_mb < min_mem {
180                return false;
181            }
182        }
183
184        // Status filter
185        if let Some(status) = self.status {
186            if !status.matches(p.status) {
187                return false;
188            }
189        }
190
191        // Uptime filter
192        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        // Parent PID filter
207        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    /// A process record with no working directory, executable or start time,
242    /// which some processes really are (a zombie has none on Linux; protected
243    /// system processes on Windows and other users' on macOS have no cwd)
244    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        // and each filter on its own can still turn it away
304        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}