proc-cli 2.0.1

Semantic CLI tool for process management. Target by port, PID, name or path.
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
//! Error types for proc CLI
//!
//! Provides structured error handling with helpful suggestions for users.

use crate::core::Process;
use thiserror::Error;

/// Main error type for proc operations
#[derive(Error, Debug)]
pub enum ProcError {
    /// No process found matching the given target
    #[error("No process found matching '{0}'\n  Try: proc list to list all processes")]
    ProcessNotFound(String),

    /// No process has this name, but some have it in their command line, which
    /// `--cmd` would match
    #[error("No process found matching '{name}'\n  {}\n  Try: proc list to list all processes", command_line_hint(.name, *.in_command_line))]
    NameNotFound {
        /// The name that was looked for
        name: String,
        /// How many processes have it in their command line (at least one)
        in_command_line: usize,
    },

    /// A target exists but `--in` or `--by` ruled out everything it matched.
    /// The target sits in the quotes and the reason follows them.
    #[error(
        "No process found matching '{target}' ({reason})\n  Try: proc list to list all processes"
    )]
    FilteredOut {
        /// The target as typed (`node`, `:3000`, `1234`)
        target: String,
        /// Which filter ruled it out
        reason: String,
    },

    /// No process is listening on the specified port
    #[error("No process listening on port {0}\n  Try: proc ports")]
    PortNotFound(u16),

    /// Insufficient permissions to operate on the process
    #[error("Permission denied for PID {0}\n  Try: sudo proc <command>")]
    PermissionDenied(u32),

    /// User provided invalid input or arguments
    #[error("Invalid input: {0}")]
    InvalidInput(String),

    /// A command that changes processes was run without `--yes` where nobody
    /// can be asked (`--json`, or no terminal). Carries the processes it would
    /// have changed so `--json` callers can see them in the error.
    #[error("Invalid input: {message}")]
    ConfirmationRequired {
        /// What to pass to proceed
        message: String,
        /// The processes the command would have changed
        processes: Vec<Process>,
        /// The targets that matched nothing, for a command that takes targets
        /// (`None` for one that finds its own processes)
        not_found: Option<Vec<String>>,
    },

    /// An underlying system call failed
    #[error("System error: {0}")]
    SystemError(String),

    /// The operation exceeded the allowed time limit
    #[error("Operation timed out: {0}")]
    Timeout(String),

    /// Failed to parse input or system output
    #[error("Failed to parse: {0}")]
    ParseError(String),

    /// Feature is not available on the current platform
    #[error("Not supported on this platform: {0}")]
    NotSupported(String),

    /// The target process terminated during the operation
    #[error("Process {0} is no longer running")]
    ProcessGone(u32),

    /// Failed to send a signal to the process
    #[error("Signal failed: {0}")]
    SignalError(String),

    /// The command already printed its result, but the operation did not fully
    /// succeed (some processes failed, a port stayed busy, a wait timed out).
    /// `main` exits with `exit_code` without printing anything further.
    #[error("{message}")]
    Reported {
        /// Human-readable summary of what did not succeed
        message: String,
        /// Exit code to return
        exit_code: ExitCode,
    },
}

/// The `reason` of an exit-4 JSON error caused by bad flags, values or
/// arguments, including clap's own usage errors
pub const REASON_INVALID_INPUT: &str = "invalid_input";

/// The `reason` of an exit-4 JSON error for a command that changes processes
/// and was not given `--yes`
pub const REASON_NEEDS_CONFIRMATION: &str = "needs_confirmation";

/// The `reason` of an exit-4 JSON error for a command this OS does not support
pub const REASON_NOT_SUPPORTED: &str = "not_supported";

/// The hint for a name that matched nothing by name but is in some command lines
pub fn command_line_hint(name: &str, count: usize) -> String {
    let (who, has, its) = if count == 1 {
        ("process", "has", "its")
    } else {
        ("processes", "have", "their")
    };
    format!("{count} {who} {has} '{name}' in {its} command line (add --cmd to match those)")
}

impl ProcError {
    /// The `--cmd` hint, when this error carries one
    pub fn command_line_hint(&self) -> Option<String> {
        match self {
            ProcError::NameNotFound {
                name,
                in_command_line,
            } => Some(command_line_hint(name, *in_command_line)),
            _ => None,
        }
    }

    /// Why this error is exit 4 (nothing was done), as the `reason` of the JSON
    /// error. `None` for every error with another exit code.
    pub fn reason(&self) -> Option<&'static str> {
        match self {
            ProcError::InvalidInput(_) => Some(REASON_INVALID_INPUT),
            ProcError::ConfirmationRequired { .. } => Some(REASON_NEEDS_CONFIRMATION),
            ProcError::NotSupported(_) => Some(REASON_NOT_SUPPORTED),
            _ => None,
        }
    }

    /// Creates a [`ProcError::Reported`] for a result that has already been printed.
    pub fn reported(exit_code: ExitCode, message: impl Into<String>) -> Self {
        ProcError::Reported {
            message: message.into(),
            exit_code,
        }
    }
}

impl From<std::io::Error> for ProcError {
    fn from(err: std::io::Error) -> Self {
        match err.kind() {
            std::io::ErrorKind::PermissionDenied => ProcError::PermissionDenied(0),
            std::io::ErrorKind::NotFound => ProcError::ProcessNotFound("unknown".to_string()),
            _ => ProcError::SystemError(err.to_string()),
        }
    }
}

impl From<serde_json::Error> for ProcError {
    fn from(err: serde_json::Error) -> Self {
        ProcError::ParseError(err.to_string())
    }
}

impl From<regex::Error> for ProcError {
    fn from(err: regex::Error) -> Self {
        ProcError::InvalidInput(format!("Invalid pattern: {}", err))
    }
}

impl From<dialoguer::Error> for ProcError {
    fn from(err: dialoguer::Error) -> Self {
        ProcError::SystemError(format!("Dialog error: {}", err))
    }
}

/// Result type alias for proc operations
pub type Result<T> = std::result::Result<T, ProcError>;

/// Exit codes for CLI
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitCode {
    /// Operation completed successfully
    Success = 0,
    /// A general error occurred
    GeneralError = 1,
    /// The requested process or port was not found
    NotFound = 2,
    /// Operation requires elevated privileges
    PermissionDenied = 3,
    /// Invalid arguments or input provided
    InvalidInput = 4,
}

impl From<&ProcError> for ExitCode {
    fn from(err: &ProcError) -> Self {
        match err {
            ProcError::ProcessNotFound(_)
            | ProcError::NameNotFound { .. }
            | ProcError::FilteredOut { .. }
            | ProcError::PortNotFound(_) => ExitCode::NotFound,
            ProcError::PermissionDenied(_) => ExitCode::PermissionDenied,
            ProcError::InvalidInput(_)
            | ProcError::NotSupported(_)
            | ProcError::ConfirmationRequired { .. } => ExitCode::InvalidInput,
            ProcError::Reported { exit_code, .. } => *exit_code,
            _ => ExitCode::GeneralError,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn not_supported_on_this_os_is_invalid_input() {
        // "Can't do this here" has one exit code, the same as an unusable
        // flag value such as `stop --signal` on Windows
        let err = ProcError::NotSupported("freeze".to_string());
        assert_eq!(ExitCode::from(&err) as i32, 4);
    }

    fn exit_code(err: ProcError) -> i32 {
        ExitCode::from(&err) as i32
    }

    #[test]
    fn every_error_has_its_message_and_exit_code() {
        let confirmation = ProcError::ConfirmationRequired {
            message: "Pass --yes".to_string(),
            processes: Vec::new(),
            not_found: None,
        };
        let cases: Vec<(ProcError, &str, i32)> = vec![
            (
                ProcError::ProcessNotFound("node".to_string()),
                "No process found matching 'node'\n  Try: proc list to list all processes",
                2,
            ),
            (
                ProcError::NameNotFound {
                    name: "serve".to_string(),
                    in_command_line: 2,
                },
                "No process found matching 'serve'\n  2 processes have 'serve' in their command line (add --cmd to match those)\n  Try: proc list to list all processes",
                2,
            ),
            (
                ProcError::FilteredOut {
                    target: "node".to_string(),
                    reason: "no matches with specified filters".to_string(),
                },
                "No process found matching 'node' (no matches with specified filters)\n  Try: proc list to list all processes",
                2,
            ),
            (
                ProcError::PortNotFound(3000),
                "No process listening on port 3000\n  Try: proc ports",
                2,
            ),
            (
                ProcError::PermissionDenied(42),
                "Permission denied for PID 42\n  Try: sudo proc <command>",
                3,
            ),
            (
                ProcError::InvalidInput("bad".to_string()),
                "Invalid input: bad",
                4,
            ),
            (confirmation, "Invalid input: Pass --yes", 4),
            (
                ProcError::SystemError("boom".to_string()),
                "System error: boom",
                1,
            ),
            (
                ProcError::Timeout("10s".to_string()),
                "Operation timed out: 10s",
                1,
            ),
            (
                ProcError::ParseError("x".to_string()),
                "Failed to parse: x",
                1,
            ),
            (
                ProcError::NotSupported("freeze".to_string()),
                "Not supported on this platform: freeze",
                4,
            ),
            (
                ProcError::ProcessGone(7),
                "Process 7 is no longer running",
                1,
            ),
            (
                ProcError::SignalError("EPERM".to_string()),
                "Signal failed: EPERM",
                1,
            ),
            (
                ProcError::reported(ExitCode::NotFound, "nothing matched"),
                "nothing matched",
                2,
            ),
        ];
        assert_eq!(ExitCode::Success as i32, 0);
        for (err, message, code) in cases {
            assert_eq!(err.to_string(), message);
            // exit 4 always says why, and no other exit code does
            assert_eq!(err.reason().is_some(), code == 4, "{message}");
            assert_eq!(exit_code(err), code, "{message}");
        }
    }

    #[test]
    fn each_exit_4_error_has_its_own_reason() {
        let confirmation = ProcError::ConfirmationRequired {
            message: "Pass --yes".to_string(),
            processes: Vec::new(),
            not_found: None,
        };
        assert_eq!(
            ProcError::InvalidInput("bad".to_string()).reason(),
            Some("invalid_input")
        );
        assert_eq!(confirmation.reason(), Some("needs_confirmation"));
        assert_eq!(
            ProcError::NotSupported("freeze".to_string()).reason(),
            Some("not_supported")
        );
        // the constants are what clap's usage errors use too
        assert_eq!(REASON_INVALID_INPUT, "invalid_input");
        assert_eq!(REASON_NEEDS_CONFIRMATION, "needs_confirmation");
        assert_eq!(REASON_NOT_SUPPORTED, "not_supported");
    }

    #[test]
    fn only_a_name_that_is_in_command_lines_carries_the_cmd_hint() {
        let one = ProcError::NameNotFound {
            name: "serve".to_string(),
            in_command_line: 1,
        };
        assert_eq!(
            one.command_line_hint().unwrap(),
            "1 process has 'serve' in its command line (add --cmd to match those)"
        );
        let many = ProcError::NameNotFound {
            name: "serve".to_string(),
            in_command_line: 3,
        };
        assert_eq!(
            many.command_line_hint().unwrap(),
            "3 processes have 'serve' in their command line (add --cmd to match those)"
        );
        assert_eq!(
            ProcError::ProcessNotFound("serve".to_string()).command_line_hint(),
            None
        );
    }

    #[test]
    fn a_reported_error_keeps_the_exit_code_it_was_given() {
        for code in [
            ExitCode::Success,
            ExitCode::GeneralError,
            ExitCode::NotFound,
            ExitCode::PermissionDenied,
            ExitCode::InvalidInput,
        ] {
            let err = ProcError::reported(code, "done");
            assert_eq!(ExitCode::from(&err), code);
        }
    }

    #[test]
    fn an_io_error_becomes_the_matching_proc_error() {
        use std::io::{Error, ErrorKind};
        let denied = ProcError::from(Error::from(ErrorKind::PermissionDenied));
        assert!(
            matches!(denied, ProcError::PermissionDenied(0)),
            "{denied:?}"
        );
        let missing = ProcError::from(Error::from(ErrorKind::NotFound));
        assert!(
            matches!(&missing, ProcError::ProcessNotFound(t) if t == "unknown"),
            "{missing:?}"
        );
        let other = ProcError::from(Error::new(ErrorKind::BrokenPipe, "pipe closed"));
        assert!(
            matches!(&other, ProcError::SystemError(m) if m == "pipe closed"),
            "{other:?}"
        );
    }

    #[test]
    fn a_json_error_becomes_a_parse_error() {
        let source = serde_json::from_str::<serde_json::Value>("{").unwrap_err();
        let expected = source.to_string();
        let err = ProcError::from(source);
        assert!(
            matches!(&err, ProcError::ParseError(m) if *m == expected),
            "{err:?}"
        );
    }

    #[test]
    fn a_bad_regex_becomes_invalid_input() {
        // Built at run time: clippy rejects a literal that is not a valid regex
        let pattern = String::from("(");
        let source = regex::Regex::new(&pattern).unwrap_err();
        let err = ProcError::from(source);
        assert!(
            matches!(&err, ProcError::InvalidInput(m) if m.starts_with("Invalid pattern: ")),
            "{err:?}"
        );
        assert_eq!(exit_code(err), 4);
    }

    #[test]
    fn a_dialog_error_becomes_a_system_error() {
        let source = dialoguer::Error::IO(std::io::Error::other("no terminal"));
        let err = ProcError::from(source);
        assert!(
            matches!(&err, ProcError::SystemError(m) if m == "Dialog error: IO error: no terminal"),
            "{err:?}"
        );
    }
}