Skip to main content

proc_cli/commands/
info.rs

1//! Info command - Get detailed process information
2//!
3//! Usage:
4//!   proc info 1234              # Info for PID
5//!   proc info :3000             # Info for process on port 3000
6//!   proc info node              # Info for processes named node
7//!   proc info :3000,:8080       # Info for multiple targets
8//!   proc info :3000,1234,node   # Mixed targets (port + PID + name)
9
10use crate::core::{parse_targets, resolve_in_dir, resolve_target, Process};
11use crate::error::Result;
12use crate::ui::{colorize_status, format_duration, format_memory, OutputFormat, Printer};
13use clap::Args;
14use colored::*;
15use serde::Serialize;
16use std::path::PathBuf;
17
18/// Show detailed process information
19#[derive(Args, Debug)]
20pub struct InfoCommand {
21    /// Target(s): PID, :port, or name (comma-separated for multiple)
22    #[arg(required = true)]
23    targets: Vec<String>,
24
25    /// Output as JSON
26    #[arg(long, short = 'j')]
27    json: bool,
28
29    /// Show extra details
30    #[arg(long, short = 'v')]
31    verbose: bool,
32
33    /// Filter by directory (defaults to current directory if no path given)
34    #[arg(long = "in", short = 'i', num_args = 0..=1, default_missing_value = ".")]
35    pub in_dir: Option<String>,
36
37    /// Filter by process name
38    #[arg(long = "by", short = 'b')]
39    pub by_name: Option<String>,
40}
41
42impl InfoCommand {
43    /// Executes the info command, displaying detailed process information.
44    pub fn execute(&self) -> Result<()> {
45        let format = if self.json {
46            OutputFormat::Json
47        } else {
48            OutputFormat::Human
49        };
50        let printer = Printer::new(format, self.verbose);
51
52        // Flatten targets - support both space-separated and comma-separated
53        let all_targets: Vec<String> = self.targets.iter().flat_map(|t| parse_targets(t)).collect();
54
55        let mut found = Vec::new();
56        let mut not_found = Vec::new();
57        let mut seen_pids = std::collections::HashSet::new();
58
59        for target in &all_targets {
60            match resolve_target(target) {
61                Ok(processes) => {
62                    if processes.is_empty() {
63                        not_found.push(target.clone());
64                    } else {
65                        for proc in processes {
66                            // Deduplicate by PID
67                            if seen_pids.insert(proc.pid) {
68                                found.push(proc);
69                            }
70                        }
71                    }
72                }
73                Err(_) => not_found.push(target.clone()),
74            }
75        }
76
77        // Apply --in and --by filters
78        let in_dir_filter = resolve_in_dir(&self.in_dir);
79        found.retain(|p| {
80            if let Some(ref dir_path) = in_dir_filter {
81                if let Some(ref cwd) = p.cwd {
82                    if !PathBuf::from(cwd).starts_with(dir_path) {
83                        return false;
84                    }
85                } else {
86                    return false;
87                }
88            }
89            if let Some(ref name) = self.by_name {
90                if !p.name.to_lowercase().contains(&name.to_lowercase()) {
91                    return false;
92                }
93            }
94            true
95        });
96
97        if self.json {
98            printer.print_json(&InfoOutput {
99                action: "info",
100                success: !found.is_empty(),
101                found_count: found.len(),
102                not_found_count: not_found.len(),
103                processes: &found,
104                not_found: &not_found,
105            });
106        } else {
107            for proc in &found {
108                self.print_process_info(proc);
109            }
110
111            if !not_found.is_empty() {
112                printer.warning(&format!("Not found: {}", not_found.join(", ")));
113            }
114        }
115
116        Ok(())
117    }
118
119    fn print_process_info(&self, proc: &Process) {
120        println!(
121            "{} Process {}",
122            "✓".green().bold(),
123            proc.pid.to_string().cyan().bold()
124        );
125        println!();
126        println!("  {} {}", "Name:".bright_black(), proc.name.white().bold());
127        println!(
128            "  {} {}",
129            "PID:".bright_black(),
130            proc.pid.to_string().cyan()
131        );
132
133        if let Some(ref cwd) = proc.cwd {
134            println!("  {} {}", "Directory:".bright_black(), cwd);
135        }
136
137        if let Some(ref path) = proc.exe_path {
138            println!("  {} {}", "Path:".bright_black(), path);
139        }
140
141        if let Some(ref user) = proc.user {
142            println!("  {} {}", "User:".bright_black(), user);
143        }
144
145        if let Some(ppid) = proc.parent_pid {
146            println!(
147                "  {} {}",
148                "Parent PID:".bright_black(),
149                ppid.to_string().cyan()
150            );
151        }
152
153        let status_str = format!("{:?}", proc.status);
154        let status_colored = colorize_status(&proc.status, &status_str);
155        println!("  {} {}", "Status:".bright_black(), status_colored);
156
157        println!("  {} {:.1}%", "CPU:".bright_black(), proc.cpu_percent);
158        println!(
159            "  {} {}",
160            "Memory:".bright_black(),
161            format_memory(proc.memory_mb)
162        );
163
164        if let Some(start_time) = proc.start_time {
165            let duration = std::time::SystemTime::now()
166                .duration_since(std::time::UNIX_EPOCH)
167                .map(|d| d.as_secs().saturating_sub(start_time))
168                .unwrap_or(0);
169
170            let uptime = format_duration(duration);
171            println!("  {} {}", "Uptime:".bright_black(), uptime);
172        }
173
174        if self.verbose {
175            if let Some(ref cmd) = proc.command {
176                println!("  {} {}", "Command:".bright_black(), cmd.bright_black());
177            }
178        }
179
180        println!();
181    }
182}
183
184#[derive(Serialize)]
185struct InfoOutput<'a> {
186    action: &'static str,
187    success: bool,
188    found_count: usize,
189    not_found_count: usize,
190    processes: &'a [Process],
191    not_found: &'a [String],
192}