croft-software 0.2.132

VSCode-style TUI written in Rust
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Discovery of attachable Python processes.
//!
//! The enumeration itself is impure (it snapshots the process table via
//! `sysinfo` and runs each candidate interpreter with `--version`), but it is
//! built entirely from the pure, tested helpers in
//! [`super::remote_attach`]. Only processes running CPython >= 3.14 (those with
//! `sys.remote_exec`) are returned, so the picker never offers a target that
//! would fail to attach.

use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;

use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};

use super::remote_attach::{PyVersion, is_python_process};

/// `--version` flag, understood by every CPython.
const VERSION_FLAG: &str = "--version";
/// Cap on the command-line summary shown in the picker so one long argv can't
/// blow out the row width. The picker cuts it again to fit its popup.
const CMD_SUMMARY_MAX: usize = 160;

/// A running CPython process that can be attached to (>= 3.14).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PyTarget {
    pub pid: u32,
    pub version: PyVersion,
    /// The interpreter binary, reused as the pdb *client* (`-m pdb -p`).
    pub exe: PathBuf,
    /// One-line, picker-ready label.
    pub label: String,
}

/// Enumerate attachable CPython processes, newest-looking first by pid.
///
/// Skips croft's own process, anything that is not a CPython interpreter, a
/// `-m pdb -p` attach client (croft's own, from an earlier attach), any
/// process whose interpreter version cannot be resolved, and any interpreter
/// older than 3.14.
pub fn attachable_python_targets() -> Vec<PyTarget> {
    let mut sys = System::new();
    // The plain `refresh_processes` reads no argv, so every row's command
    // line was empty (#868). Threads are left out: on Linux each would be
    // listed as a process of its own, one row per thread.
    sys.refresh_processes_specifics(
        ProcessesToUpdate::All,
        true,
        ProcessRefreshKind::nothing()
            .without_tasks()
            .with_exe(UpdateKind::OnlyIfNotSet)
            .with_cmd(UpdateKind::OnlyIfNotSet),
    );
    let self_pid = std::process::id();

    let rows: Vec<(u32, PyVersion, PathBuf, String)> = sys
        .processes()
        .iter()
        .filter_map(|(pid, proc_)| {
            let pid = pid.as_u32();
            if pid == self_pid {
                return None;
            }
            let name = proc_.name().to_string_lossy();
            let exe = proc_.exe();
            if !is_python_process(&name, exe) {
                return None;
            }
            let exe = exe?;
            if is_pdb_attach_client(proc_.cmd()) {
                return None;
            }
            let version = interpreter_version(exe)?;
            if !version.supports_remote_attach() {
                return None;
            }
            Some((pid, version, exe.to_path_buf(), summarize_cmd(proc_.cmd())))
        })
        .collect();
    labelled_targets(rows)
}

/// The picker's targets for `(pid, version, exe, command line)` rows, by
/// pid, each label's PID column padded to the widest PID listed (#868): 4-
/// and 5-digit PIDs in one list otherwise push the version and command line
/// out of line from row to row.
fn labelled_targets(mut rows: Vec<(u32, PyVersion, PathBuf, String)>) -> Vec<PyTarget> {
    rows.sort_by_key(|(pid, ..)| *pid);
    let pid_width = rows
        .iter()
        .map(|(pid, ..)| pid.to_string().len())
        .max()
        .unwrap_or(0);
    rows.into_iter()
        .map(|(pid, version, exe, summary)| PyTarget {
            pid,
            version,
            exe,
            label: target_label(pid, pid_width, version, &summary),
        })
        .collect()
}

/// Run `<exe> --version` and parse the reported CPython version. Older
/// interpreters print to stderr, newer ones to stdout, so both are consulted.
/// Returns `None` if the process cannot be run or the output is unparseable.
fn interpreter_version(exe: &Path) -> Option<PyVersion> {
    let out = Command::new(exe).arg(VERSION_FLAG).output().ok()?;
    PyVersion::parse(&String::from_utf8_lossy(&out.stdout))
        .or_else(|| PyVersion::parse(&String::from_utf8_lossy(&out.stderr)))
}

/// Collapse a process argv into a single bounded line for display.
///
/// The interpreter shows by its file name (#1283): a uv, pyenv or venv path
/// filled the whole line, so every row read ".../bin/python" and the
/// arguments that tell processes apart never showed. The row's version
/// column says which interpreter it is, and [`PyTarget::exe`] keeps the full
/// path. A line still over the cap loses its middle, marked with `…`, so
/// the script and its arguments at the end stay.
fn summarize_cmd(cmd: &[OsString]) -> String {
    let joined = cmd
        .iter()
        .enumerate()
        .map(|(i, s)| match Path::new(s).file_name() {
            Some(name) if i == 0 => name.to_string_lossy(),
            _ => s.to_string_lossy(),
        })
        .collect::<Vec<_>>()
        .join(" ");
    elide_middle(&joined, CMD_SUMMARY_MAX)
}

/// `s` cut to at most `max` chars by dropping its middle for one `…`,
/// keeping a third of what fits from the start and the rest from the end.
pub fn elide_middle(s: &str, max: usize) -> String {
    let chars: Vec<char> = s.chars().collect();
    if chars.len() <= max {
        return s.to_string();
    }
    let keep = max.saturating_sub(1);
    let head = keep / 3;
    let tail = keep - head;
    let mut out: String = chars[..head].iter().collect();
    out.push('…');
    out.extend(&chars[chars.len() - tail..]);
    out
}

/// Whether `cmd` is a `python -m pdb -p <pid>` attach client, the process an
/// earlier attach left running (#868). It is a debugger, not a program to
/// debug, and listing it beside its target offered to attach to itself.
fn is_pdb_attach_client(cmd: &[OsString]) -> bool {
    let args: Vec<_> = cmd.iter().skip(1).map(|a| a.to_string_lossy()).collect();
    let Some(module_at) = pdb_arguments_at(&args) else {
        return false;
    };
    // pdb's own options, up to the script it debugs: a `-p` after that is
    // the script's argument, and `python -m pdb app.py` is a real target.
    let mut rest = args[module_at..].iter();
    while let Some(a) = rest.next() {
        match a.as_ref() {
            "-p" | "--pid" => return true,
            a if a.starts_with("--pid=") => return true,
            "-c" | "--command" => {
                rest.next();
            }
            a if a.starts_with('-') => {}
            _ => return false,
        }
    }
    false
}

/// Where pdb's own arguments start in `args` (an interpreter's argv without
/// argv[0]) when it runs `-m pdb`, else None (#868). Only the interpreter's
/// options are read, the way CPython reads them: they end at the script (the
/// first non-option, or `-` for stdin, or whatever follows `--`), at `-c`,
/// whose code and everything after it are the program's, and at `-m`, whose
/// module decides. Short options combine (`-um pdb`), and `-W`, `-X` and
/// `--check-hash-based-pycs` take a value, from the rest of their group or
/// the next argument, which is never the script.
fn pdb_arguments_at(args: &[std::borrow::Cow<'_, str>]) -> Option<usize> {
    let mut next = 0;
    while let Some(arg) = args.get(next) {
        next += 1;
        if let Some(long) = arg.strip_prefix("--") {
            match long {
                "" => return None,
                "check-hash-based-pycs" => next += 1,
                _ => {}
            }
            continue;
        }
        // Not an option: the script (`-` is stdin's), where options end.
        let group = arg.strip_prefix('-').filter(|g| !g.is_empty())?;
        for (at, flag) in group.char_indices() {
            let value = &group[at + flag.len_utf8()..];
            match flag {
                'c' => return None,
                'm' => {
                    let module = if value.is_empty() {
                        next += 1;
                        args.get(next - 1)?.as_ref()
                    } else {
                        value
                    };
                    return (module == "pdb").then_some(next);
                }
                'W' | 'X' => {
                    if value.is_empty() {
                        next += 1;
                    }
                    break;
                }
                _ => {}
            }
        }
    }
    None
}

/// Build the picker row label: pid (left-aligned in `pid_width` columns),
/// interpreter version, then the command line.
fn target_label(pid: u32, pid_width: usize, version: PyVersion, cmd_summary: &str) -> String {
    format!(
        "PID {pid:<pid_width$}  ·  Python {}.{}.{}  ·  {cmd_summary}",
        version.major, version.minor, version.patch
    )
}

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

    fn v(major: u32, minor: u32, patch: u32) -> PyVersion {
        PyVersion {
            major,
            minor,
            patch,
        }
    }

    #[test]
    fn label_includes_pid_version_and_command() {
        let label = target_label(4321, 4, v(3, 14, 2), "app.py --serve");
        assert!(label.contains("PID 4321"));
        assert!(label.contains("3.14.2"));
        assert!(label.contains("app.py --serve"));
    }

    #[test]
    fn summarize_joins_argv_with_spaces() {
        let cmd = vec![
            OsString::from("python3.14"),
            OsString::from("app.py"),
            OsString::from("--port=8000"),
        ];
        assert_eq!(summarize_cmd(&cmd), "python3.14 app.py --port=8000");
    }

    /// #1283: a uv, pyenv or venv interpreter path alone filled the whole
    /// summary, so every row read ".../bin/python" and nothing after. The
    /// interpreter shows by its file name (the version column already says
    /// which one it is) and the arguments that tell processes apart show.
    #[test]
    fn summarize_names_the_interpreter_by_file_name_and_keeps_the_arguments() {
        let cmd = argv(&[
            "/root/.local/share/uv/python/cpython-3.14.0-linux-x86_64-gnu/bin/python3.14",
            "-m",
            "http.server",
            "8766",
        ]);
        assert_eq!(summarize_cmd(&cmd), "python3.14 -m http.server 8766");
    }

    /// #1283: an argv still too long for the cap loses its middle, marked
    /// with an ellipsis, and keeps its end, where the script and its
    /// arguments are.
    #[test]
    fn summarize_cuts_an_overlong_argv_in_the_middle_and_keeps_its_end() {
        let long = "x".repeat(300);
        let cmd = argv(&["python3", "worker.py", &long, "--queue", "emails"]);
        let out = summarize_cmd(&cmd);
        assert_eq!(out.chars().count(), CMD_SUMMARY_MAX);
        assert!(out.starts_with("python3 worker.py x"), "{out}");
        assert!(out.ends_with("x --queue emails"), "{out}");
        assert_eq!(out.matches('…').count(), 1, "{out}");
    }

    /// #1283 negative: a short command shows unchanged, with no ellipsis,
    /// and a bare interpreter name is left alone.
    #[test]
    fn summarize_leaves_a_short_command_whole() {
        let cmd = argv(&["python3", "manage.py", "runserver"]);
        assert_eq!(summarize_cmd(&cmd), "python3 manage.py runserver");
        assert_eq!(summarize_cmd(&argv(&["python3.14"])), "python3.14");
    }

    #[test]
    fn summarize_empty_argv_is_empty() {
        assert_eq!(summarize_cmd(&[]), "");
    }

    fn argv(args: &[&str]) -> Vec<OsString> {
        args.iter().map(OsString::from).collect()
    }

    /// #868: an attach client (croft's `python -m pdb -p <pid>`) is not a
    /// target; a program merely run under pdb, or taking a `-p` of its own,
    /// still is.
    #[test]
    fn a_pdb_attach_client_is_not_offered_as_a_target() {
        for client in [
            &["/usr/bin/python3.14", "-m", "pdb", "-p", "4321"][..],
            &["python3", "-mpdb", "--pid=4321"],
            &["python3", "-m", "pdb", "-c", "continue", "--pid", "9"],
        ] {
            assert!(is_pdb_attach_client(&argv(client)), "{client:?}");
        }
        for target in [
            &["python3", "-m", "pdb", "app.py", "-p", "80"][..],
            &["python3", "serve.py", "-p", "8000"],
            &["python3", "-m", "http.server", "-p"],
            &["python3"],
        ] {
            assert!(!is_pdb_attach_client(&argv(target)), "{target:?}");
        }
    }

    /// #868: only the interpreter's own options are read for `-m pdb`.
    /// What follows the script, or `-c code`, is the program's own argv, so
    /// `python3 tool.py -m pdb -p 80` is a program to debug, not pdb.
    #[test]
    fn a_programs_own_dash_m_pdb_arguments_are_not_an_attach_client() {
        let hidden = [
            &["python3", "tool.py", "-m", "pdb", "-p", "80"][..],
            &["python3", "-c", "code", "-m", "pdb", "-p", "5"],
            &["python3", "-X", "dev", "tool.py", "-m", "pdb", "-p", "1"],
            &["python3", "-", "-m", "pdb", "-p", "1"],
            &["python3", "--", "tool.py", "-m", "pdb", "-p", "1"],
        ]
        .into_iter()
        .filter(|target| is_pdb_attach_client(&argv(target)))
        .collect::<Vec<_>>();
        assert!(hidden.is_empty(), "taken for pdb clients: {hidden:?}");
    }

    /// #868 guard: interpreter options before `-m pdb` are read through,
    /// the ones that take a value included, whose value (`dev`, `ignore`,
    /// `never`) is never taken for the script. A script after such an option
    /// is still a script.
    #[test]
    fn interpreter_options_before_dash_m_pdb_are_read_through() {
        for client in [
            &["python3", "-m", "pdb", "-p", "123"][..],
            &["python3", "-X", "dev", "-m", "pdb", "-p", "123"],
            &[
                "python3", "-Xdev", "-W", "ignore", "-u", "-m", "pdb", "--pid", "1",
            ],
            &[
                "python3",
                "--check-hash-based-pycs",
                "never",
                "-m",
                "pdb",
                "-p",
                "1",
            ],
        ] {
            assert!(is_pdb_attach_client(&argv(client)), "{client:?}");
        }
        for target in [
            &["python3", "-W", "ignore", "tool.py"][..],
            &["python3", "-W", "ignore", "tool.py", "-p", "1"],
        ] {
            assert!(!is_pdb_attach_client(&argv(target)), "{target:?}");
        }
    }

    /// #868: short options combine as CPython reads them, the last of a
    /// group taking its value from the next argument: `-um pdb` runs pdb,
    /// `-uX dev` sets `-X dev`, and `-uc code` ends the options there.
    #[test]
    fn combined_short_options_are_read_as_cpython_reads_them() {
        for client in [
            &["python3", "-IB", "-um", "pdb", "-p", "1"][..],
            &["python3", "-uX", "dev", "-mpdb", "-p", "1"],
        ] {
            assert!(is_pdb_attach_client(&argv(client)), "{client:?}");
        }
        let code_then_args = ["python3", "-uc", "import pdb", "-m", "pdb", "-p", "1"];
        assert!(!is_pdb_attach_client(&argv(&code_then_args)));
    }

    /// #868 guard: only pdb itself is an attach client. A module that merely
    /// starts with `pdb`, or pdb with no `-p`, is left in the list.
    #[test]
    fn a_module_only_named_like_pdb_is_still_a_target() {
        for target in [
            &["python3", "-m", "pdbpp", "-p", "1"][..],
            &["python3", "-mpdbx", "--pid=1"],
            &["python3", "-m", "pdb"],
            &["python3", "-m", "pdb", "-c", "continue"],
        ] {
            assert!(!is_pdb_attach_client(&argv(target)), "{target:?}");
        }
    }

    /// #868 guard: the refresh that reads argv leaves threads out. A 3.14
    /// process running several threads is one row, not one per thread.
    #[test]
    fn a_threaded_target_is_listed_once() {
        let Some(python) = python_314() else {
            eprintln!("skipping: no CPython 3.14+ found");
            return;
        };
        // The marker leads the command line, inside the label's cap.
        let marker = format!("threaded{}", std::process::id());
        let script = format!(
            "{marker} = 1\n\
             import threading, time\n\
             for _ in range(3): threading.Thread(target=time.sleep, args=(30,), daemon=True).start()\n\
             time.sleep(30)\n"
        );
        let target = Reap(
            Command::new(&python)
                .args(["-c", &script])
                .spawn()
                .expect("spawn the target"),
        );
        let pid = target.0.id();
        let listed = || -> Vec<u32> {
            attachable_python_targets()
                .into_iter()
                .filter(|t| t.label.contains(&marker))
                .map(|t| t.pid)
                .collect()
        };
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(500),
            "the threaded python to be listed",
            || !listed().is_empty(),
        );
        // Give the threads time to start, then look again.
        std::thread::sleep(std::time::Duration::from_millis(300));
        assert_eq!(listed(), vec![pid]);
    }

    /// A CPython 3.14+ to run a target under, or None: attaching needs one,
    /// so the listing test skips without it.
    fn python_314() -> Option<PathBuf> {
        let mut candidates: Vec<PathBuf> = ["python3.14", "python3.15", "python3"]
            .into_iter()
            .map(PathBuf::from)
            .collect();
        if let Some(home) = std::env::var_os("HOME") {
            candidates.push(PathBuf::from(home).join(".croft/debug-venv/bin/python"));
        }
        if let Ok(out) = Command::new("uv").args(["python", "find", "3.14"]).output() {
            let found = String::from_utf8_lossy(&out.stdout).trim().to_string();
            if !found.is_empty() {
                candidates.push(PathBuf::from(found));
            }
        }
        candidates
            .into_iter()
            .find(|p| interpreter_version(p).is_some_and(|v| v.supports_remote_attach()))
    }

    /// Kills the spawned target however the test ends.
    struct Reap(std::process::Child);

    impl Drop for Reap {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }

    /// #868: every row read `PID n · Python 3.14.7 ·` with nothing after,
    /// because the process refresh never read argv. A real 3.14 process is
    /// listed with its command line.
    #[test]
    fn a_listed_target_shows_its_command_line() {
        let Some(python) = python_314() else {
            eprintln!("skipping: no CPython 3.14+ found");
            return;
        };
        let target = Reap(
            Command::new(&python)
                .args(["-c", "import time; time.sleep(30)"])
                .spawn()
                .expect("spawn the target"),
        );
        let pid = target.0.id();
        let mut label = None;
        crate::test_budget::await_spawned(
            std::time::Duration::from_millis(500),
            "the sleeping python to be listed",
            || {
                label = attachable_python_targets()
                    .into_iter()
                    .find(|t| t.pid == pid)
                    .map(|t| t.label);
                label.is_some()
            },
        );
        let label = label.unwrap();
        assert!(
            label.contains("-c import time"),
            "the row names the command line: {label}"
        );
    }

    /// Where a label's version column starts, in characters.
    fn version_column(label: &str) -> usize {
        label[..label.find("Python").expect("a version")]
            .chars()
            .count()
    }

    /// #868: the issue's screenshot has 4- and 5-digit PIDs in one list,
    /// pushing the columns after them out of line. The PID column is padded
    /// to the widest PID listed, so every row's version and command line
    /// start at one column. Rows come out by PID.
    #[test]
    fn the_pid_column_is_padded_to_the_widest_pid() {
        let exe = PathBuf::from("/usr/bin/python3.14");
        let rows = labelled_targets(vec![
            (
                51234,
                v(3, 14, 2),
                exe.clone(),
                String::from("python3.14 worker.py"),
            ),
            (
                812,
                v(3, 14, 2),
                exe.clone(),
                String::from("python3.14 a.py"),
            ),
            (
                4321,
                v(3, 14, 2),
                exe.clone(),
                String::from("python3.14 -m app"),
            ),
        ]);
        assert_eq!(
            rows.iter().map(|t| t.pid).collect::<Vec<_>>(),
            vec![812, 4321, 51234]
        );
        let columns: Vec<usize> = rows.iter().map(|t| version_column(&t.label)).collect();
        assert!(columns.iter().all(|c| *c == columns[0]), "{rows:#?}");
        assert!(
            rows[0].label.starts_with("PID 812    ·"),
            "{}",
            rows[0].label
        );
        assert!(
            rows[2].label.ends_with("·  python3.14 worker.py"),
            "{}",
            rows[2].label
        );
    }

    /// #868 guard: padding is to the widest PID present, not a fixed width.
    /// A lone target, or PIDs all as wide, read exactly as before, and an
    /// empty list stays empty.
    #[test]
    fn same_width_pids_are_not_padded() {
        let exe = PathBuf::from("/usr/bin/python3.14");
        let one = labelled_targets(vec![(
            4321,
            v(3, 14, 2),
            exe.clone(),
            String::from("app.py --serve"),
        )]);
        assert_eq!(
            one[0].label,
            "PID 4321  ·  Python 3.14.2  ·  app.py --serve"
        );
        let same = labelled_targets(vec![
            (4321, v(3, 14, 2), exe.clone(), String::from("a.py")),
            (1234, v(3, 14, 2), exe.clone(), String::from("b.py")),
        ]);
        assert!(
            same.iter()
                .all(|t| t.label.starts_with("PID ") && !t.label.contains("   ·"))
        );
        assert!(labelled_targets(Vec::new()).is_empty());
    }
}