proc_cli/commands/
ps.rs

1//! `proc ps` - List processes
2//!
3//! Examples:
4//!   proc ps                  # List all processes
5//!   proc ps node             # Filter by name
6//!   proc ps --in             # Processes in current directory
7//!   proc ps --in /project    # Processes in /project
8//!   proc ps --min-cpu 10     # Processes using >10% CPU
9
10use crate::core::{Process, ProcessStatus};
11use crate::error::Result;
12use crate::ui::{OutputFormat, Printer};
13use clap::Args;
14use std::path::PathBuf;
15
16/// List processes
17#[derive(Args, Debug)]
18pub struct PsCommand {
19    /// Process name or pattern to filter by
20    pub name: Option<String>,
21
22    /// Filter by directory (defaults to current directory if no path given)
23    #[arg(long = "in", short = 'i', num_args = 0..=1, default_missing_value = ".")]
24    pub in_dir: Option<String>,
25
26    /// Filter by executable path
27    #[arg(long, short = 'p')]
28    pub path: Option<String>,
29
30    /// Only show processes using more than this CPU %
31    #[arg(long)]
32    pub min_cpu: Option<f32>,
33
34    /// Only show processes using more than this memory (MB)
35    #[arg(long)]
36    pub min_mem: Option<f64>,
37
38    /// Filter by status: running, sleeping, stopped, zombie
39    #[arg(long)]
40    pub status: Option<String>,
41
42    /// Output as JSON
43    #[arg(long, short = 'j')]
44    pub json: bool,
45
46    /// Show verbose output with command line, cwd, and parent PID
47    #[arg(long, short = 'v')]
48    pub verbose: bool,
49
50    /// Limit the number of results
51    #[arg(long, short = 'n')]
52    pub limit: Option<usize>,
53
54    /// Sort by: cpu, mem, pid, name
55    #[arg(long, short = 's', default_value = "cpu")]
56    pub sort: String,
57}
58
59impl PsCommand {
60    pub fn execute(&self) -> Result<()> {
61        let format = if self.json {
62            OutputFormat::Json
63        } else {
64            OutputFormat::Human
65        };
66        let printer = Printer::new(format, self.verbose);
67
68        // Get base process list
69        let mut processes = if let Some(ref name) = self.name {
70            Process::find_by_name(name)?
71        } else {
72            Process::find_all()?
73        };
74
75        // Resolve --in filter path
76        let in_dir_filter: Option<PathBuf> = self.in_dir.as_ref().map(|p| {
77            if p == "." {
78                std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
79            } else {
80                let path = PathBuf::from(p);
81                if path.is_relative() {
82                    std::env::current_dir()
83                        .unwrap_or_else(|_| PathBuf::from("."))
84                        .join(path)
85                } else {
86                    path
87                }
88            }
89        });
90
91        // Resolve path filter
92        let path_filter: Option<PathBuf> = self.path.as_ref().map(|p| {
93            let path = PathBuf::from(p);
94            if path.is_relative() {
95                std::env::current_dir()
96                    .unwrap_or_else(|_| PathBuf::from("."))
97                    .join(path)
98            } else {
99                path
100            }
101        });
102
103        // Apply filters
104        processes.retain(|p| {
105            // Directory filter (--in)
106            if let Some(ref dir_path) = in_dir_filter {
107                if let Some(ref proc_cwd) = p.cwd {
108                    let proc_path = PathBuf::from(proc_cwd);
109                    if !proc_path.starts_with(dir_path) {
110                        return false;
111                    }
112                } else {
113                    return false;
114                }
115            }
116
117            // Path filter (executable path)
118            if let Some(ref exe_path) = path_filter {
119                if let Some(ref proc_exe) = p.exe_path {
120                    let proc_path = PathBuf::from(proc_exe);
121                    if !proc_path.starts_with(exe_path) {
122                        return false;
123                    }
124                } else {
125                    return false;
126                }
127            }
128
129            // CPU filter
130            if let Some(min_cpu) = self.min_cpu {
131                if p.cpu_percent < min_cpu {
132                    return false;
133                }
134            }
135
136            // Memory filter
137            if let Some(min_mem) = self.min_mem {
138                if p.memory_mb < min_mem {
139                    return false;
140                }
141            }
142
143            // Status filter
144            if let Some(ref status) = self.status {
145                let status_match = match status.to_lowercase().as_str() {
146                    "running" => matches!(p.status, ProcessStatus::Running),
147                    "sleeping" | "sleep" => matches!(p.status, ProcessStatus::Sleeping),
148                    "stopped" | "stop" => matches!(p.status, ProcessStatus::Stopped),
149                    "zombie" => matches!(p.status, ProcessStatus::Zombie),
150                    _ => true,
151                };
152                if !status_match {
153                    return false;
154                }
155            }
156
157            true
158        });
159
160        // Sort processes
161        match self.sort.to_lowercase().as_str() {
162            "cpu" => processes.sort_by(|a, b| {
163                b.cpu_percent
164                    .partial_cmp(&a.cpu_percent)
165                    .unwrap_or(std::cmp::Ordering::Equal)
166            }),
167            "mem" | "memory" => processes.sort_by(|a, b| {
168                b.memory_mb
169                    .partial_cmp(&a.memory_mb)
170                    .unwrap_or(std::cmp::Ordering::Equal)
171            }),
172            "pid" => processes.sort_by_key(|p| p.pid),
173            "name" => processes.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase())),
174            _ => {} // Keep default order
175        }
176
177        // Apply limit if specified
178        if let Some(limit) = self.limit {
179            processes.truncate(limit);
180        }
181
182        // Build context string for output (e.g., "in /path/to/dir")
183        let context = in_dir_filter
184            .as_ref()
185            .map(|p| format!("in {}", p.display()));
186
187        printer.print_processes_with_context(&processes, context.as_deref());
188        Ok(())
189    }
190}