Skip to main content

proc_cli/commands/
find_in.rs

1//! `proc in` - Filter processes by working directory
2//!
3//! Examples:
4//!   proc in .                  # Processes in current directory
5//!   proc in /path/to/project   # Processes in specific directory
6//!   proc in . --by node        # Node processes in cwd
7//!   proc in ~/projects         # Processes in ~/projects
8
9use crate::core::{sort_processes, Process, ProcessStatus, SortKey};
10use crate::error::{ProcError, Result};
11use crate::ui::{OutputFormat, Printer};
12use clap::Args;
13use std::path::PathBuf;
14
15/// Filter processes by working directory
16#[derive(Args, Debug)]
17pub struct InCommand {
18    /// Directory path (absolute, relative, or . for cwd)
19    pub path: String,
20
21    /// Filter by process name
22    #[arg(long = "by", short = 'b')]
23    pub by_name: Option<String>,
24
25    /// Only show processes using more than this CPU %
26    #[arg(long)]
27    pub min_cpu: Option<f32>,
28
29    /// Only show processes using more than this memory (MB)
30    #[arg(long)]
31    pub min_mem: Option<f64>,
32
33    /// Filter by status: running, sleeping, stopped, zombie
34    #[arg(long)]
35    pub status: Option<String>,
36
37    /// Only show processes running longer than this (seconds)
38    #[arg(long)]
39    pub min_uptime: Option<u64>,
40
41    /// Only show children of this parent PID
42    #[arg(long)]
43    pub parent: Option<u32>,
44
45    /// Output as JSON
46    #[arg(long, short = 'j')]
47    pub json: bool,
48
49    /// Show verbose output with command line, cwd, and parent PID
50    #[arg(long, short = 'v')]
51    pub verbose: bool,
52
53    /// Limit the number of results
54    #[arg(long, short = 'n')]
55    pub limit: Option<usize>,
56
57    /// Sort by: cpu, mem, pid, name
58    #[arg(long, short = 's', value_enum, default_value_t = SortKey::Cpu)]
59    pub sort: SortKey,
60}
61
62impl InCommand {
63    /// Expand ~ to home directory
64    fn expand_tilde(path: &str) -> PathBuf {
65        if let Some(stripped) = path.strip_prefix("~/") {
66            if let Ok(home) = std::env::var("HOME") {
67                return PathBuf::from(home).join(stripped);
68            }
69        } else if path == "~" {
70            if let Ok(home) = std::env::var("HOME") {
71                return PathBuf::from(home);
72            }
73        }
74        PathBuf::from(path)
75    }
76
77    /// Executes the in command, listing processes in the specified directory.
78    pub fn execute(&self) -> Result<()> {
79        let format = if self.json {
80            OutputFormat::Json
81        } else {
82            OutputFormat::Human
83        };
84        let printer = Printer::new(format, self.verbose);
85
86        // Get base process list
87        let mut processes = if let Some(ref name) = self.by_name {
88            Process::find_by_name(name)?
89        } else {
90            Process::find_all()?
91        };
92
93        // Resolve directory path
94        let dir_filter = if self.path == "." {
95            std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
96        } else {
97            let expanded = Self::expand_tilde(&self.path);
98            if expanded.is_relative() {
99                std::env::current_dir()
100                    .unwrap_or_else(|_| PathBuf::from("."))
101                    .join(expanded)
102            } else {
103                expanded
104            }
105        };
106
107        // A path that doesn't exist is a typo, not an empty directory (same as `proc for`)
108        if !dir_filter.is_dir() {
109            return Err(ProcError::InvalidInput(format!(
110                "Directory not found: {}",
111                self.path
112            )));
113        }
114
115        // Apply filters
116        processes.retain(|p| {
117            // Directory filter (required for this command)
118            if let Some(ref proc_cwd) = p.cwd {
119                let proc_path = PathBuf::from(proc_cwd);
120                if !proc_path.starts_with(&dir_filter) {
121                    return false;
122                }
123            } else {
124                return false;
125            }
126
127            // CPU filter
128            if let Some(min_cpu) = self.min_cpu {
129                if p.cpu_percent < min_cpu {
130                    return false;
131                }
132            }
133
134            // Memory filter
135            if let Some(min_mem) = self.min_mem {
136                if p.memory_mb < min_mem {
137                    return false;
138                }
139            }
140
141            // Status filter
142            if let Some(ref status) = self.status {
143                let status_match = match status.to_lowercase().as_str() {
144                    "running" => matches!(p.status, ProcessStatus::Running),
145                    "sleeping" | "sleep" => matches!(p.status, ProcessStatus::Sleeping),
146                    "stopped" | "stop" => matches!(p.status, ProcessStatus::Stopped),
147                    "zombie" => matches!(p.status, ProcessStatus::Zombie),
148                    _ => true,
149                };
150                if !status_match {
151                    return false;
152                }
153            }
154
155            // Uptime filter
156            if let Some(min_uptime) = self.min_uptime {
157                if let Some(start_time) = p.start_time {
158                    let now = std::time::SystemTime::now()
159                        .duration_since(std::time::UNIX_EPOCH)
160                        .map(|d| d.as_secs())
161                        .unwrap_or(0);
162                    if now.saturating_sub(start_time) < min_uptime {
163                        return false;
164                    }
165                } else {
166                    return false;
167                }
168            }
169
170            // Parent PID filter
171            if let Some(ppid) = self.parent {
172                if p.parent_pid != Some(ppid) {
173                    return false;
174                }
175            }
176
177            true
178        });
179
180        // Sort processes
181        sort_processes(&mut processes, self.sort);
182
183        // Apply limit if specified
184        if let Some(limit) = self.limit {
185            processes.truncate(limit);
186        }
187
188        // Build context string for output
189        let mut context_parts = vec![format!("in {}", dir_filter.display())];
190        if let Some(ref name) = self.by_name {
191            context_parts.push(format!("by '{}'", name));
192        }
193        let context = Some(context_parts.join(" "));
194
195        printer.print_processes_as("in", &processes, context.as_deref());
196        Ok(())
197    }
198}