croft-software 0.2.32

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
//! `croft demo` (#377): a guided first tour, played in a throwaway sample
//! project so it never touches the user's own work.
//!
//! The script is data, `assets/tour/tour.json`: a list of steps, each an
//! action and the caption shown while it is on screen. Contributors extend
//! it, and a platform can ship its own (a Termux tour driven by the
//! on-screen keyboard, say) without touching this code.
//!
//! A caption writes the command modifier as `{mod}` (`{mod}+P`), and the
//! tour spells it as this platform's: `Cmd` on macOS, `Ctrl` elsewhere
//! (#863). A literal `Cmd+P` told a Linux user to press a key that does
//! nothing there.

use std::path::{Path, PathBuf};

/// The built-in tour.
pub const TOUR_JSON: &str = include_str!("../assets/tour/tour.json");

/// The file that marks a folder as croft's own demo scratch space. Removal
/// refuses any folder without it, so a bug can never delete a workspace.
pub const SCRATCH_MARKER: &str = ".croft-demo";

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TourAction {
    /// Open a file, relative to the sample project.
    Open(String),
    QuickOpen,
    /// Quick Open with this query already typed, so Enter alone opens its
    /// match: an empty finder's first row is whatever sorts first.
    FindFile(String),
    SplitEditor,
    Terminal,
    /// Type a command into the terminal and run it.
    Run(String),
    /// Open the first error the terminal shows.
    JumpToError,
    CommandPalette,
    /// The command palette with this query already typed, so Enter alone
    /// runs the command it names rather than whichever sorts first (an edit
    /// such as Move Line Up, into the sample).
    Palette(String),
    ThemePicker,
    Done,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct TourStep {
    pub action: TourAction,
    pub caption: String,
}

impl TourStep {
    /// The caption as shown: `{mod}` spelled as this platform's command
    /// modifier.
    pub fn caption_text(&self) -> String {
        expand_caption(&self.caption, crate::keymap::mod_key_name())
    }
}

/// `caption` with every `{mod}` spelled `modifier`. Takes the name rather
/// than asking for it so a test can expand for a platform it is not on.
pub fn expand_caption(caption: &str, modifier: &str) -> String {
    caption.replace("{mod}", modifier)
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub struct Tour {
    pub steps: Vec<TourStep>,
    /// The step on screen.
    #[serde(skip)]
    pub index: usize,
}

impl Tour {
    pub fn parse(json: &str) -> Result<Tour, String> {
        let tour: Tour = serde_json::from_str(json).map_err(|e| format!("tour.json: {e}"))?;
        if tour.steps.is_empty() {
            return Err(String::from("tour.json has no steps"));
        }
        Ok(tour)
    }

    pub fn current(&self) -> Option<&TourStep> {
        self.steps.get(self.index)
    }

    /// Move to the next step; `None` once the tour has run out.
    pub fn advance(&mut self) -> Option<&TourStep> {
        self.index = (self.index + 1).min(self.steps.len());
        self.current()
    }

    /// `3/9`, for the caption chip.
    pub fn progress(&self) -> String {
        format!(
            "{}/{}",
            (self.index + 1).min(self.steps.len()),
            self.steps.len()
        )
    }
}

static CUSTOM_TOUR: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);

/// `croft demo --tour <file>`: run this tour instead of the built-in one,
/// in the same sample project. Checked with [`Tour::parse`] before the app
/// starts, so a bad file is refused at the command line.
pub fn set_custom_tour(json: String) {
    if let Ok(mut slot) = CUSTOM_TOUR.lock() {
        *slot = Some(json);
    }
}

/// The tour to run: the one `--tour` named for this session, else the
/// built-in one.
pub fn tour_source() -> String {
    CUSTOM_TOUR
        .lock()
        .ok()
        .and_then(|slot| slot.clone())
        .unwrap_or_else(|| TOUR_JSON.to_string())
}

static STARTUP_DEMO: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// `croft demo` asks for the tour here before the app starts.
pub fn request_startup_demo() {
    STARTUP_DEMO.store(true, std::sync::atomic::Ordering::SeqCst);
}

/// The app takes the request once, after its first frame.
pub fn take_startup_demo() -> bool {
    STARTUP_DEMO.swap(false, std::sync::atomic::Ordering::SeqCst)
}

/// The sample project: a few languages, a build that fails on purpose so
/// the tour can show jumping to an error.
pub fn sample_files() -> Vec<(&'static str, &'static str)> {
    vec![
        (
            "README.md",
            "# croft tour\n\nA throwaway sample project. It is deleted when the tour ends.\n",
        ),
        (
            "src/main.rs",
            "fn main() {\n    let who = \"croft\";\n    println!(\"hello from {who}\");\n}\n",
        ),
        (
            "app.py",
            "def greet(name):\n    return f\"hello, {name}\"\n\nprint(greet(\"croft\")\n",
        ),
        (
            "web/index.html",
            "<!doctype html>\n<title>croft tour</title>\n<p>Hello from the sample project.</p>\n",
        ),
    ]
}

/// Create the sample project in a fresh folder under `parent`.
pub fn create_scratch(parent: &Path) -> std::io::Result<PathBuf> {
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let dir = parent.join(format!("croft-demo-{}-{stamp}", std::process::id()));
    std::fs::create_dir_all(&dir)?;
    std::fs::write(
        dir.join(SCRATCH_MARKER),
        "croft demo scratch; safe to delete\n",
    )?;
    for (rel, text) in sample_files() {
        let path = dir.join(rel);
        if let Some(p) = path.parent() {
            std::fs::create_dir_all(p)?;
        }
        std::fs::write(path, text)?;
    }
    Ok(dir)
}

/// Delete the scratch folders under `parent` that a tour ended by killing
/// croft left behind (#863): closing the terminal mid-tour never reaches
/// [`remove_scratch`], and the next `croft demo` made a folder of its own
/// beside the old one. A folder goes only when its name is
/// `croft-demo-<pid>-<stamp>`, `<pid>` is neither this process nor one
/// `is_alive` says still runs, it is a real directory (not a link to one),
/// and it carries [`SCRATCH_MARKER`]; anything else under `parent` stays.
/// Returns how many were removed.
pub fn sweep_dead_scratch(parent: &Path, is_alive: impl Fn(u32) -> bool) -> usize {
    let Ok(entries) = std::fs::read_dir(parent) else {
        return 0;
    };
    let me = std::process::id();
    let mut removed = 0;
    for entry in entries.flatten() {
        let Some(pid) = entry.file_name().to_str().and_then(scratch_pid) else {
            continue;
        };
        if pid == me || is_alive(pid) || !entry.file_type().is_ok_and(|t| t.is_dir()) {
            continue;
        }
        if remove_scratch(&entry.path()).is_ok() {
            removed += 1;
        }
    }
    removed
}

/// The `<pid>` in a scratch folder's `croft-demo-<pid>-<stamp>` name.
fn scratch_pid(name: &str) -> Option<u32> {
    let (pid, stamp) = name.strip_prefix("croft-demo-")?.split_once('-')?;
    if stamp.is_empty() || !stamp.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    pid.parse().ok()
}

/// Delete a scratch folder, but only one that carries [`SCRATCH_MARKER`].
pub fn remove_scratch(dir: &Path) -> Result<(), String> {
    if !dir.join(SCRATCH_MARKER).is_file() {
        return Err(format!(
            "{} is not a croft demo folder (no {SCRATCH_MARKER}); not deleting it",
            dir.display()
        ));
    }
    std::fs::remove_dir_all(dir).map_err(|e| e.to_string())
}

/// The first `file` and 1-based `line` an error names in terminal text:
/// Python's `File "app.py", line 3`, and the `path:line[:col]` form rustc,
/// gcc and most tools print.
pub fn first_error_ref(lines: &[String]) -> Option<(String, usize)> {
    for line in lines {
        // Python: File "app.py", line 3
        if let Some(rest) = line.split("File \"").nth(1)
            && let Some((file, tail)) = rest.split_once("\", line ")
            && let Some(n) = tail
                .split(|c: char| !c.is_ascii_digit())
                .next()
                .and_then(|d| d.parse().ok())
        {
            return Some((file.to_string(), n));
        }
        // path:line[:col], as rustc (after `-->`), gcc and most tools print.
        for token in line.split_whitespace() {
            let mut parts = token.split(':');
            let (Some(file), Some(n)) = (parts.next(), parts.next()) else {
                continue;
            };
            if file.contains('.')
                && !file.contains("//")
                && let Ok(n) = n.parse::<usize>()
            {
                return Some((file.to_string(), n));
            }
        }
    }
    None
}

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

    #[test]
    fn the_built_in_tour_parses_and_covers_the_issue_s_sequence() {
        let tour = Tour::parse(TOUR_JSON).unwrap();
        let actions: Vec<&TourAction> = tour.steps.iter().map(|s| &s.action).collect();
        assert_eq!(actions[0], &TourAction::Open("src/main.rs".into()));
        for want in [
            TourAction::FindFile("app".into()),
            TourAction::SplitEditor,
            TourAction::Terminal,
            TourAction::JumpToError,
            // The palette leads into the theme picker, the issue's last two
            // stops, through the command typed into it.
            TourAction::Palette("color theme".into()),
        ] {
            assert!(actions.contains(&&want), "{want:?} in the tour");
        }
        assert_eq!(actions.last(), Some(&&TourAction::Done));
        assert!(tour.steps.iter().all(|s| !s.caption.is_empty()));
        // #863: a chord is written with the placeholder, never one
        // platform's own modifier, and nothing unexpanded reaches the screen.
        for s in &tour.steps {
            assert!(
                !s.caption.contains("Cmd"),
                "spell the modifier {{mod}}: {}",
                s.caption
            );
            assert!(!s.caption_text().contains('{'), "{}", s.caption_text());
        }
        // Every file the tour opens exists in the sample project.
        let files: Vec<&str> = sample_files().iter().map(|(p, _)| *p).collect();
        for s in &tour.steps {
            if let TourAction::Open(p) = &s.action {
                assert!(files.contains(&p.as_str()), "{p} is in the sample");
            }
        }
    }

    #[test]
    fn captions_name_the_platform_s_command_modifier() {
        // #863: `{mod}` is Cmd on macOS and Ctrl elsewhere, as `mod` is in
        // keybindings.json.
        assert_eq!(expand_caption("{mod}+P finds", "Cmd"), "Cmd+P finds");
        assert_eq!(
            expand_caption("{mod}+Shift+P, or {mod}+click", "Ctrl"),
            "Ctrl+Shift+P, or Ctrl+click"
        );
        let want = if cfg!(target_os = "macos") {
            "Cmd+P"
        } else {
            "Ctrl+P"
        };
        let step = TourStep {
            action: TourAction::QuickOpen,
            caption: String::from("{mod}+P"),
        };
        assert_eq!(step.caption_text(), want);
        let tour = Tour::parse(TOUR_JSON).unwrap();
        assert!(
            tour.steps
                .iter()
                .any(|s| s.caption_text().contains(&format!("{want} "))),
            "the built-in tour teaches {want}"
        );
    }

    /// #863 negative: only the exact `{mod}` placeholder is spelled out; a
    /// caption that names a fixed key (`Ctrl+J` is Ctrl on every platform)
    /// or braces anything else is shown as written.
    #[test]
    fn a_caption_without_the_placeholder_is_left_as_written() {
        for caption in [
            "Ctrl+J opens a real terminal inside croft.",
            "{modifier} and {MOD} are not the placeholder",
            "",
        ] {
            assert_eq!(expand_caption(caption, "Cmd"), caption);
        }
        assert_eq!(expand_caption("{mod}{mod}", "Ctrl"), "CtrlCtrl");
    }

    /// A scratch-shaped folder named `name` under `parent`, with the marker
    /// when `marked`.
    fn scratch_like(parent: &Path, name: &str, marked: bool) -> PathBuf {
        let dir = parent.join(name);
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/main.rs"), "fn main() {}\n").unwrap();
        if marked {
            std::fs::write(dir.join(SCRATCH_MARKER), "croft demo scratch\n").unwrap();
        }
        dir
    }

    /// #863: a marked scratch folder whose croft has exited is swept.
    #[test]
    fn a_dead_tour_s_marked_scratch_folder_is_swept() {
        let parent = tempfile::tempdir().unwrap();
        let dead = scratch_like(parent.path(), "croft-demo-585-1790000000000", true);
        assert_eq!(sweep_dead_scratch(parent.path(), |_| false), 1);
        assert!(!dead.exists());
    }

    /// #863 negative: the sweep leaves this process's folder, a live pid's
    /// folder, an unmarked folder of a dead pid, a link to a marked folder,
    /// and any name not of the scratch shape.
    #[cfg(unix)]
    #[test]
    fn the_sweep_keeps_live_unmarked_and_foreign_folders() {
        let parent = tempfile::tempdir().unwrap();
        let p = parent.path();
        let me = std::process::id();
        let mine = scratch_like(p, &format!("croft-demo-{me}-1"), true);
        let live = scratch_like(p, "croft-demo-4242-1", true);
        let unmarked = scratch_like(p, "croft-demo-585-2", false);
        let foreign = [
            scratch_like(p, "croft-demo-585", true),
            scratch_like(p, "croft-demo-585-x1", true),
            scratch_like(p, "croft-demo-pid-1", true),
            scratch_like(p, "my-project", true),
        ];
        let elsewhere = tempfile::tempdir().unwrap();
        let target = scratch_like(elsewhere.path(), "real", true);
        std::os::unix::fs::symlink(&target, p.join("croft-demo-586-1")).unwrap();
        // Everyone but 4242 reads as dead, this process included.
        let removed = sweep_dead_scratch(p, |pid| pid == 4242);
        assert_eq!(removed, 0);
        for dir in [&mine, &live, &unmarked] {
            assert!(dir.is_dir(), "{} kept", dir.display());
        }
        for dir in &foreign {
            assert!(dir.is_dir(), "{} kept", dir.display());
        }
        assert!(
            target.join(SCRATCH_MARKER).is_file(),
            "a link's target kept"
        );
        assert_eq!(sweep_dead_scratch(&p.join("missing"), |_| false), 0);
    }

    #[test]
    fn the_startup_demo_request_is_taken_once() {
        request_startup_demo();
        assert!(take_startup_demo());
        assert!(!take_startup_demo());
    }

    #[test]
    fn a_tour_steps_forward_and_ends() {
        let mut t = Tour::parse(
            r#"{"steps":[{"action":"quick_open","caption":"a"},{"action":"done","caption":"b"}]}"#,
        )
        .unwrap();
        assert_eq!(t.current().unwrap().caption, "a");
        assert_eq!(t.progress(), "1/2");
        assert_eq!(t.advance().unwrap().caption, "b");
        assert_eq!(t.progress(), "2/2");
        assert!(t.advance().is_none());
        assert!(t.current().is_none(), "past the end");
    }

    #[test]
    fn a_malformed_tour_is_an_error() {
        assert!(Tour::parse("{}").is_err());
        assert!(Tour::parse(r#"{"steps":[{"action":"fly","caption":"x"}]}"#).is_err());
        assert!(
            Tour::parse(r#"{"steps":[]}"#).is_err(),
            "an empty tour is not a tour"
        );
    }

    #[test]
    fn scratch_is_created_marked_and_only_marked_folders_are_removed() {
        let parent = tempfile::tempdir().unwrap();
        let dir = create_scratch(parent.path()).unwrap();
        assert!(dir.join(SCRATCH_MARKER).is_file());
        for (p, _) in sample_files() {
            assert!(dir.join(p).is_file(), "{p} written");
        }
        remove_scratch(&dir).unwrap();
        assert!(!dir.exists());

        let real = tempfile::tempdir().unwrap();
        std::fs::write(real.path().join("important.txt"), "keep").unwrap();
        assert!(remove_scratch(real.path()).is_err(), "unmarked: refused");
        assert!(
            real.path().join("important.txt").exists(),
            "nothing deleted"
        );
    }

    #[test]
    fn the_sample_build_fails_and_the_tour_can_find_the_line() {
        // The tour's run step is `python3 -m py_compile app.py`; it has to
        // fail, and its output has to lead `first_error_ref` to app.py.
        let parent = tempfile::tempdir().unwrap();
        let dir = create_scratch(parent.path()).unwrap();
        let out = std::process::Command::new("python3")
            .args(["-m", "py_compile", "app.py"])
            .current_dir(&dir)
            .output()
            .expect("python3 is available");
        assert!(!out.status.success(), "the sample build fails on purpose");
        let text = String::from_utf8_lossy(&out.stderr);
        let lines: Vec<String> = text.lines().map(str::to_string).collect();
        let (file, line) = first_error_ref(&lines).expect("an error location");
        assert!(file.ends_with("app.py"), "{file}");
        assert!(line >= 1);
    }

    #[test]
    fn errors_are_found_in_python_and_path_line_forms() {
        let py = vec![
            "$ python3 -m py_compile app.py".to_string(),
            "  File \"app.py\", line 3".to_string(),
            "    print(\"hello\"".to_string(),
        ];
        assert_eq!(first_error_ref(&py), Some(("app.py".into(), 3)));
        let rust = vec![
            "error[E0425]: nope".to_string(),
            "  --> src/main.rs:12:5".to_string(),
        ];
        assert_eq!(first_error_ref(&rust), Some(("src/main.rs".into(), 12)));
        let gcc = vec!["main.c:7:3: error: expected ';'".to_string()];
        assert_eq!(first_error_ref(&gcc), Some(("main.c".into(), 7)));
        assert_eq!(first_error_ref(&["all good".to_string()]), None);
    }
}