proc-cli 1.13.2

A semantic CLI tool for process management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! `proc on` - Port/process lookup
//!
//! Usage:
//!   proc on :3000              # What process is on port 3000?
//!   proc on :3000,:8080        # What's on multiple ports?
//!   proc on 1234               # What ports is PID 1234 listening on?
//!   proc on node               # What ports are node processes listening on?
//!   proc on node --in .        # Node processes in cwd and their ports

use crate::core::{
    find_ports_for_pid, parse_target, parse_targets, resolve_in_dir, resolve_target, PortInfo,
    Process, TargetType,
};
use crate::error::{ExitCode, ProcError, Result};
use crate::ui::{format_duration, format_memory, Printer};
use clap::Args;
use colored::*;
use serde::Serialize;
use std::path::PathBuf;

/// Show what's on a port, or what ports a process is on
#[derive(Args, Debug)]
pub struct OnCommand {
    /// Target(s): :port, PID, or process name (comma-separated for multiple)
    pub target: String,

    /// Filter by directory (defaults to current directory if no path given)
    #[arg(long = "in", short = 'i', num_args = 0..=1, default_missing_value = ".")]
    pub in_dir: Option<String>,

    /// Filter by process name
    #[arg(long = "by", short = 'b')]
    pub by_name: Option<String>,

    /// Output as JSON
    #[arg(long, short = 'j')]
    pub json: bool,

    /// Show verbose output (full command line)
    #[arg(long, short = 'v')]
    pub verbose: bool,
}

impl OnCommand {
    /// Executes the on command, performing bidirectional port/process lookup.
    pub fn execute(&self) -> Result<()> {
        let targets = parse_targets(&self.target);

        // For single target, use original behavior
        if targets.len() == 1 {
            return match parse_target(&targets[0]) {
                TargetType::Port(port) => self.show_process_on_port(port),
                TargetType::Pid(pid) => self.show_ports_for_pid(pid),
                TargetType::Name(name) => self.show_ports_for_name(&name),
            };
        }

        if self.json {
            return self.show_multi_json(&targets);
        }

        // Multi-target handling
        let mut not_found = Vec::new();

        for target in &targets {
            match parse_target(target) {
                TargetType::Port(port) => {
                    if let Err(e) = self.show_process_on_port(port) {
                        println!("{} Port {}: {}", "⚠".yellow(), port, e);
                        not_found.push(target.clone());
                    }
                }
                TargetType::Pid(pid) => {
                    if let Err(e) = self.show_ports_for_pid(pid) {
                        println!("{} PID {}: {}", "⚠".yellow(), pid, e);
                        not_found.push(target.clone());
                    }
                }
                TargetType::Name(ref name) => {
                    if let Err(e) = self.show_ports_for_name(name) {
                        println!("{} '{}': {}", "⚠".yellow(), name, e);
                        not_found.push(target.clone());
                    }
                }
            }
        }

        if not_found.len() == targets.len() {
            // Each target already printed its own warning
            return Err(ProcError::reported(
                ExitCode::NotFound,
                format!("No process found matching '{}'", self.target),
            ));
        }

        Ok(())
    }

    /// Multi-target JSON: one envelope with a result per matched process
    fn show_multi_json(&self, targets: &[String]) -> Result<()> {
        let mut results: Vec<TargetResult> = Vec::new();
        let mut not_found: Vec<String> = Vec::new();

        for target in targets {
            let found = match parse_target(target) {
                TargetType::Port(port) => {
                    self.lookup_port(port)
                        .map(|(port_info, process)| match process {
                            Some(process) => vec![(process, vec![port_info])],
                            None => Vec::new(),
                        })
                }
                TargetType::Pid(pid) => self.lookup_pid(pid).map(|found| vec![found]),
                TargetType::Name(ref name) => self.lookup_name(name),
            };

            match found {
                Ok(found) if !found.is_empty() => {
                    results.extend(found.into_iter().map(|(process, ports)| TargetResult {
                        target: target.clone(),
                        process,
                        ports,
                    }))
                }
                _ => not_found.push(target.clone()),
            }
        }

        if results.is_empty() {
            return Err(ProcError::ProcessNotFound(self.target.clone()));
        }

        Printer::from_flags(true, self.verbose).print_json(&MultiTargetOutput {
            action: "on",
            success: true,
            count: results.len(),
            results,
            not_found,
        });

        Ok(())
    }

    /// Check if process matches --in filter
    fn matches_in_filter(&self, proc: &Process) -> bool {
        if let Some(ref dir_path) = resolve_in_dir(&self.in_dir) {
            if let Some(ref proc_cwd) = proc.cwd {
                let proc_path = PathBuf::from(proc_cwd);
                proc_path.starts_with(dir_path)
            } else {
                false
            }
        } else {
            true
        }
    }

    /// Check if process matches --by filter
    fn matches_by_filter(&self, proc: &Process) -> bool {
        if let Some(ref name) = self.by_name {
            crate::core::matches_by_filter(proc, name)
        } else {
            true
        }
    }

    /// Check if process matches all filters (--in and --by)
    fn matches_filters(&self, proc: &Process) -> bool {
        self.matches_in_filter(proc) && self.matches_by_filter(proc)
    }

    /// Find the listener on a port and its process, applying --in/--by
    fn lookup_port(&self, port: u16) -> Result<(PortInfo, Option<Process>)> {
        let port_info = match PortInfo::find_by_port(port)? {
            Some(info) => info,
            None => return Err(ProcError::PortNotFound(port)),
        };

        let process = Process::find_by_pid(port_info.pid)?;

        // Apply --in and --by filters if present
        if let Some(ref proc) = process {
            if !self.matches_filters(proc) {
                return Err(ProcError::ProcessNotFound(format!(
                    "port {} (process not in specified directory)",
                    port
                )));
            }
        }

        Ok((port_info, process))
    }

    /// Show what process is on a specific port
    fn show_process_on_port(&self, port: u16) -> Result<()> {
        let (port_info, process) = self.lookup_port(port)?;

        if self.json {
            let printer = Printer::from_flags(true, self.verbose);
            let output = PortLookupOutput {
                action: "on",
                query_type: "port_to_process",
                success: true,
                port: Some(port_info.port),
                protocol: Some(format!("{:?}", port_info.protocol).to_lowercase()),
                address: port_info.address.clone(),
                process: process.as_ref(),
                ports: None,
            };
            printer.print_json(&output);
        } else {
            self.print_process_on_port(&port_info, process.as_ref());
        }

        Ok(())
    }

    /// Find a process by PID and its listening ports, applying --in/--by
    fn lookup_pid(&self, pid: u32) -> Result<(Process, Vec<PortInfo>)> {
        let process = Process::find_by_pid(pid)?
            .ok_or_else(|| ProcError::ProcessNotFound(pid.to_string()))?;

        // Apply --in and --by filters if present
        if !self.matches_filters(&process) {
            return Err(ProcError::ProcessNotFound(format!(
                "PID {} (not in specified directory)",
                pid
            )));
        }

        let ports = find_ports_for_pid(pid)?;
        Ok((process, ports))
    }

    /// Show what ports a PID is listening on
    fn show_ports_for_pid(&self, pid: u32) -> Result<()> {
        let (process, ports) = self.lookup_pid(pid)?;

        if self.json {
            let printer = Printer::from_flags(true, self.verbose);
            let output = PortLookupOutput {
                action: "on",
                query_type: "process_to_ports",
                success: true,
                port: None,
                protocol: None,
                address: None,
                process: Some(&process),
                ports: Some(&ports),
            };
            printer.print_json(&output);
        } else {
            self.print_ports_for_process(&process, &ports);
        }

        Ok(())
    }

    /// Find processes by name and their listening ports, applying --in/--by
    fn lookup_name(&self, name: &str) -> Result<Vec<(Process, Vec<PortInfo>)>> {
        let mut processes = resolve_target(name)?;

        if processes.is_empty() {
            return Err(ProcError::ProcessNotFound(name.to_string()));
        }

        // Apply --in and --by filters if present
        if self.in_dir.is_some() || self.by_name.is_some() {
            processes.retain(|p| self.matches_filters(p));
            if processes.is_empty() {
                return Err(ProcError::ProcessNotFound(format!(
                    "'{}' (no matches with specified filters)",
                    name
                )));
            }
        }

        let mut all_results: Vec<(Process, Vec<PortInfo>)> = Vec::new();

        for proc in processes {
            let ports = find_ports_for_pid(proc.pid)?;
            all_results.push((proc, ports));
        }

        Ok(all_results)
    }

    /// Show what ports processes with a given name are listening on
    fn show_ports_for_name(&self, name: &str) -> Result<()> {
        let all_results = self.lookup_name(name)?;

        if self.json {
            let printer = Printer::from_flags(true, self.verbose);
            let results: Vec<_> = all_results
                .iter()
                .map(|(proc, ports)| ProcessPortsJson {
                    process: proc,
                    ports,
                })
                .collect();
            let output = MultiProcessPortsOutput {
                action: "on",
                success: true,
                count: results.len(),
                results: &results,
            };
            printer.print_json(&output);
        } else {
            for (proc, ports) in &all_results {
                self.print_ports_for_process(proc, ports);
            }
        }

        Ok(())
    }

    fn print_process_on_port(&self, port_info: &PortInfo, process: Option<&Process>) {
        println!(
            "{} Port {} is used by:",
            "✓".green().bold(),
            port_info.port.to_string().cyan().bold()
        );
        println!();

        println!(
            "  {} {} (PID {})",
            "Process:".bright_black(),
            port_info.process_name.white().bold(),
            port_info.pid.to_string().cyan()
        );

        if let Some(proc) = process {
            if let Some(ref cwd) = proc.cwd {
                println!("  {} {}", "Directory:".bright_black(), cwd);
            }
            if let Some(ref path) = proc.exe_path {
                println!("  {} {}", "Path:".bright_black(), path.bright_black());
            }
        }

        let addr = port_info.address.as_deref().unwrap_or("*");
        println!(
            "  {} {} on {}",
            "Listening:".bright_black(),
            format!("{:?}", port_info.protocol).to_uppercase(),
            addr
        );

        if let Some(proc) = process {
            println!(
                "  {} {:.1}% CPU, {}",
                "Resources:".bright_black(),
                proc.cpu_percent,
                format_memory(proc.memory_mb)
            );

            if let Some(start_time) = proc.start_time {
                let uptime = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs().saturating_sub(start_time))
                    .unwrap_or(0);
                println!("  {} {}", "Uptime:".bright_black(), format_duration(uptime));
            }

            if self.verbose {
                if let Some(ref cmd) = proc.command {
                    println!("  {} {}", "Command:".bright_black(), cmd.bright_black());
                }
            }
        }

        println!();
    }

    fn print_ports_for_process(&self, process: &Process, ports: &[PortInfo]) {
        println!(
            "{} {} (PID {}) is listening on:",
            "✓".green().bold(),
            process.name.white().bold(),
            process.pid.to_string().cyan().bold()
        );
        println!();

        if ports.is_empty() {
            println!("  {} No listening ports", "ℹ".blue());
        } else {
            for port_info in ports {
                let addr = port_info.address.as_deref().unwrap_or("*");
                println!(
                    "  {} :{} ({} on {})",
                    "→".bright_black(),
                    port_info.port.to_string().cyan(),
                    format!("{:?}", port_info.protocol).to_uppercase(),
                    addr
                );
            }
        }

        if let Some(ref cwd) = process.cwd {
            println!();
            println!("  {} {}", "Directory:".bright_black(), cwd);
        }

        if self.verbose {
            if let Some(ref path) = process.exe_path {
                println!("  {} {}", "Path:".bright_black(), path.bright_black());
            }
            if let Some(ref cmd) = process.command {
                println!("  {} {}", "Command:".bright_black(), cmd.bright_black());
            }
        }

        println!();
    }
}

#[derive(Serialize)]
struct PortLookupOutput<'a> {
    action: &'static str,
    query_type: &'static str,
    success: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    port: Option<u16>,
    #[serde(skip_serializing_if = "Option::is_none")]
    protocol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    process: Option<&'a Process>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ports: Option<&'a [PortInfo]>,
}

#[derive(Serialize)]
struct ProcessPortsJson<'a> {
    process: &'a Process,
    ports: &'a [PortInfo],
}

#[derive(Serialize)]
struct TargetResult {
    target: String,
    process: Process,
    ports: Vec<PortInfo>,
}

#[derive(Serialize)]
struct MultiTargetOutput {
    action: &'static str,
    success: bool,
    count: usize,
    results: Vec<TargetResult>,
    not_found: Vec<String>,
}

#[derive(Serialize)]
struct MultiProcessPortsOutput<'a> {
    action: &'static str,
    success: bool,
    count: usize,
    results: &'a Vec<ProcessPortsJson<'a>>,
}