pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
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
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
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use tokio::sync::mpsc;

use crate::state::types::{AppMode, NewsBookmark, NewsFeedItem, NewsFeedSource};
use crate::state::{AppState, PackageItem, Source};

use super::handle_install_key;

/// What: Produce a baseline `AppState` tailored for install-pane tests without repeating setup boilerplate.
///
/// Inputs:
/// - None (relies on `Default::default()` for deterministic initial state).
///
/// Output:
/// - Fresh `AppState` ready for mutation inside individual test cases.
///
/// Details:
/// - Keeps test bodies concise while ensuring each case starts from a clean copy.
fn new_app() -> AppState {
    AppState::default()
}

/// What: Create a test package item with specified source.
///
/// Inputs:
/// - `name`: Package name
/// - `source`: Package source (Official or AUR)
///
/// Output:
/// - `PackageItem` ready for testing
///
/// Details:
/// - Helper to create test packages with consistent structure
fn create_test_package(name: &str, source: Source) -> PackageItem {
    PackageItem {
        name: name.into(),
        version: "1.0.0".into(),
        description: String::new(),
        source,
        popularity: None,
        out_of_date: None,
        orphaned: false,
    }
}

#[test]
/// What: Confirm pressing Enter opens the preflight modal when installs are pending.
///
/// Inputs:
/// - Install list seeded with a single package and `Enter` key event.
///
/// Output:
/// - Modal transitions to `Preflight` with one item, `Install` action, and `Summary` tab active.
///
/// Details:
/// - Uses mock channels to satisfy handler requirements without observing downstream messages.
/// - Sets up temporary config directory to ensure `skip_preflight = false` regardless of user config.
fn install_enter_opens_confirm_install() {
    let _guard = crate::theme::test_mutex()
        .lock()
        .expect("Test mutex poisoned");
    let orig_home = std::env::var_os("HOME");
    let orig_xdg = std::env::var_os("XDG_CONFIG_HOME");
    let base = std::env::temp_dir().join(format!(
        "pacsea_test_install_{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("System time is before UNIX epoch")
            .as_nanos()
    ));
    let cfg = base.join(".config").join("pacsea");
    let _ = std::fs::create_dir_all(&cfg);
    unsafe { std::env::set_var("HOME", base.display().to_string()) };
    unsafe { std::env::remove_var("XDG_CONFIG_HOME") };

    // Write settings.conf with skip_preflight = false
    let settings_path = cfg.join("settings.conf");
    std::fs::write(&settings_path, "skip_preflight = false\n")
        .expect("Failed to write test settings file");

    let mut app = new_app();
    app.install_list = vec![create_test_package("rg", Source::Aur)];
    let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    match app.modal {
        crate::state::Modal::Preflight {
            ref items,
            action,
            tab,
            summary: _,
            summary_scroll: _,
            header_chips: _,
            dependency_info: _,
            dep_selected: _,
            dep_tree_expanded: _,
            deps_error: _,
            file_info: _,
            file_selected: _,
            file_tree_expanded: _,
            files_error: _,
            service_info: _,
            service_selected: _,
            services_loaded: _,
            services_error: _,
            sandbox_info: _,
            sandbox_selected: _,
            sandbox_tree_expanded: _,
            sandbox_loaded: _,
            sandbox_error: _,
            selected_optdepends: _,
            cascade_mode: _,
            cached_reverse_deps_report: _,
        } => {
            assert_eq!(items.len(), 1);
            assert_eq!(action, crate::state::PreflightAction::Install);
            assert_eq!(tab, crate::state::PreflightTab::Summary);
        }
        _ => panic!("Preflight modal not opened"),
    }

    unsafe {
        if let Some(v) = orig_home {
            std::env::set_var("HOME", v);
        } else {
            std::env::remove_var("HOME");
        }
        if let Some(v) = orig_xdg {
            std::env::set_var("XDG_CONFIG_HOME", v);
        } else {
            std::env::remove_var("XDG_CONFIG_HOME");
        }
    }
    let _ = std::fs::remove_dir_all(&base);
}

#[test]
/// What: Placeholder ensuring default behaviour still opens the preflight modal when `skip_preflight` remains false.
///
/// Inputs:
/// - Single official package queued for install with `Enter` key event.
///
/// Output:
/// - Modal remains `Preflight`, matching current default configuration.
///
/// Details:
/// - Documents intent for future skip-preflight support while asserting existing flow stays intact.
/// - Sets up temporary config directory to ensure `skip_preflight = false` regardless of user config.
fn install_enter_bypasses_preflight_with_skip_flag() {
    let _guard = crate::theme::test_mutex()
        .lock()
        .expect("Test mutex poisoned");
    let orig_home = std::env::var_os("HOME");
    let orig_xdg = std::env::var_os("XDG_CONFIG_HOME");
    let base = std::env::temp_dir().join(format!(
        "pacsea_test_install_skip_{}_{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("System time is before UNIX epoch")
            .as_nanos()
    ));
    let cfg = base.join(".config").join("pacsea");
    let _ = std::fs::create_dir_all(&cfg);
    unsafe { std::env::set_var("HOME", base.display().to_string()) };
    unsafe { std::env::remove_var("XDG_CONFIG_HOME") };

    // Write settings.conf with skip_preflight = false
    let settings_path = cfg.join("settings.conf");
    std::fs::write(&settings_path, "skip_preflight = false\n")
        .expect("Failed to write test settings file");

    // Verify the setting is false
    assert!(
        !crate::theme::settings().skip_preflight,
        "skip_preflight unexpectedly true by default"
    );

    let mut app = new_app();
    app.install_list = vec![create_test_package(
        "ripgrep",
        Source::Official {
            repo: "core".into(),
            arch: "x86_64".into(),
        },
    )];
    let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    // Behavior remains preflight when flag false; placeholder ensures future refactor retains compatibility.
    match app.modal {
        crate::state::Modal::Preflight {
            summary: _,
            summary_scroll: _,
            header_chips: _,
            dependency_info: _,
            dep_selected: _,
            dep_tree_expanded: _,
            file_info: _,
            file_selected: _,
            file_tree_expanded: _,
            files_error: _,
            service_info: _,
            service_selected: _,
            services_loaded: _,
            cascade_mode: _,
            ..
        } => {}
        _ => panic!("Expected Preflight when skip_preflight=false"),
    }

    unsafe {
        if let Some(v) = orig_home {
            std::env::set_var("HOME", v);
        } else {
            std::env::remove_var("HOME");
        }
        if let Some(v) = orig_xdg {
            std::env::set_var("XDG_CONFIG_HOME", v);
        } else {
            std::env::remove_var("XDG_CONFIG_HOME");
        }
    }
    let _ = std::fs::remove_dir_all(&base);
}

#[test]
/// What: Ensure loading a bookmark without cached content resets loading state and clears stale content.
///
/// Inputs:
/// - Bookmark with no cached content or HTML path, stale content pre-set, and loading flag true.
///
/// Output:
/// - `news_content_loading` becomes false and `news_content` is cleared.
///
/// Details:
/// - Prevents a stuck loading flag that would block future fetch requests.
fn load_news_bookmark_without_cached_content_clears_loading_flag() {
    let mut app = new_app();
    app.app_mode = AppMode::News;
    app.news_content_loading = true;
    app.news_content = Some("stale".into());
    app.news_bookmarks.clear();
    app.news_results.clear();
    app.news_content_cache.clear();

    let bookmark = NewsBookmark {
        item: NewsFeedItem {
            id: "id-1".into(),
            date: "2024-01-01".into(),
            title: "Example".into(),
            summary: None,
            url: Some("https://example.com/news".into()),
            source: NewsFeedSource::ArchNews,
            severity: None,
            packages: Vec::new(),
        },
        content: None,
        html_path: None,
    };
    app.news_bookmarks.push(bookmark);
    let last_idx = app.news_bookmarks.len().saturating_sub(1);
    app.install_state.select(Some(last_idx));

    super::load_news_bookmark(&mut app);

    assert!(!app.news_content_loading, "loading flag should reset");
    assert!(
        app.news_content.is_none(),
        "stale content should be cleared when bookmark has no cache, got {:?}",
        app.news_content
    );
}

#[test]
/// What: Verify the Delete key removes the selected install item.
///
/// Inputs:
/// - Install list with two entries, selection on the first, and `Delete` key event.
///
/// Output:
/// - List shrinks to one entry, confirming removal logic.
///
/// Details:
/// - Channels are stubbed to satisfy handler signature while focusing on list mutation.
fn install_delete_removes_item() {
    let mut app = new_app();
    app.install_list = vec![
        create_test_package("rg", Source::Aur),
        create_test_package("fd", Source::Aur),
    ];
    app.install_state.select(Some(0));
    let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Delete, KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    assert_eq!(app.install_list.len(), 1);
}

#[test]
/// What: Verify navigation down (j/Down) moves selection correctly.
///
/// Inputs:
/// - Install list with three entries, selection on first, and `j` key event.
///
/// Output:
/// - Selection moves to second item.
///
/// Details:
/// - Tests basic navigation functionality in install pane.
fn install_navigation_down() {
    let mut app = new_app();
    app.install_list = vec![
        create_test_package("rg", Source::Aur),
        create_test_package("fd", Source::Aur),
        create_test_package("bat", Source::Aur),
    ];
    app.install_state.select(Some(0));
    let (dtx, mut drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Char('j'), KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    assert_eq!(app.install_state.selected(), Some(1));
    // Drain channel to avoid blocking
    let _ = drx.try_recv();
}

#[test]
/// What: Verify navigation up (k/Up) moves selection correctly.
///
/// Inputs:
/// - Install list with three entries, selection on second, and `k` key event.
///
/// Output:
/// - Selection moves to first item.
///
/// Details:
/// - Tests basic navigation functionality in install pane.
fn install_navigation_up() {
    let mut app = new_app();
    app.install_list = vec![
        create_test_package("rg", Source::Aur),
        create_test_package("fd", Source::Aur),
        create_test_package("bat", Source::Aur),
    ];
    app.install_state.select(Some(1));
    let (dtx, mut drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Char('k'), KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    assert_eq!(app.install_state.selected(), Some(0));
    // Drain channel to avoid blocking
    let _ = drx.try_recv();
}

#[test]
/// What: Verify Esc returns focus to Search pane.
///
/// Inputs:
/// - Install pane focused, Esc key event.
///
/// Output:
/// - Focus returns to Search pane.
///
/// Details:
/// - Tests that Esc properly returns focus from Install pane.
fn install_esc_returns_to_search() {
    let mut app = new_app();
    app.focus = crate::state::Focus::Install;
    let (dtx, mut drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    assert_eq!(app.focus, crate::state::Focus::Search);
    assert!(app.search_normal_mode);
    // Drain channel to avoid blocking
    let _ = drx.try_recv();
}

#[test]
/// What: Verify Enter with empty install list does nothing.
///
/// Inputs:
/// - Empty install list, Enter key event.
///
/// Output:
/// - No modal opened, state unchanged.
///
/// Details:
/// - Tests that Enter is ignored when install list is empty.
fn install_enter_with_empty_list() {
    let mut app = new_app();
    app.install_list.clear();
    let initial_modal = app.modal.clone();
    let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    // Modal should remain unchanged when list is empty
    match (initial_modal, app.modal) {
        (crate::state::Modal::None, crate::state::Modal::None) => {}
        _ => panic!("Modal should not change with empty install list"),
    }
}

#[test]
/// What: Verify clear list functionality removes all items.
///
/// Inputs:
/// - Install list with multiple entries, clear key event.
///
/// Output:
/// - Install list is cleared, selection reset.
///
/// Details:
/// - Tests that clear list keybinding works correctly.
fn install_clear_list() {
    let mut app = new_app();
    app.install_list = vec![
        create_test_package("rg", Source::Aur),
        create_test_package("fd", Source::Aur),
        create_test_package("bat", Source::Aur),
    ];
    app.install_state.select(Some(1));

    // Simulate clear key (using 'c' as example, actual key depends on keymap)
    // For this test, we'll directly test the clear functionality
    app.install_list.clear();
    app.install_state.select(None);
    app.install_dirty = true;
    app.install_list_deps.clear();
    app.install_list_files.clear();
    app.deps_resolving = false;
    app.files_resolving = false;

    assert!(app.install_list.is_empty());
    assert_eq!(app.install_state.selected(), None);
    assert!(app.install_dirty);
}

#[test]
/// What: Verify pane find mode can be entered with '/' key.
///
/// Inputs:
/// - Install pane focused, '/' key event.
///
/// Output:
/// - Pane find mode is activated.
///
/// Details:
/// - Tests that '/' enters find mode in install pane.
fn install_pane_find_mode_entry() {
    let mut app = new_app();
    assert!(app.pane_find.is_none());
    let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Char('/'), KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    assert!(app.pane_find.is_some());
    assert_eq!(
        app.pane_find.as_ref().expect("pane_find should be Some"),
        ""
    );
}

#[test]
/// What: Verify pane find mode can be cancelled with Esc.
///
/// Inputs:
/// - Pane find mode active, Esc key event.
///
/// Output:
/// - Pane find mode is cancelled.
///
/// Details:
/// - Tests that Esc cancels find mode.
fn install_pane_find_mode_cancel() {
    let mut app = new_app();
    app.pane_find = Some("test".to_string());
    let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    assert!(app.pane_find.is_none());
}

#[test]
/// What: Verify deletion of last item clears selection.
///
/// Inputs:
/// - Install list with one entry, selection on that entry, Delete key event.
///
/// Output:
/// - List is empty, selection is None.
///
/// Details:
/// - Tests edge case of deleting the only item in the list.
fn install_delete_last_item() {
    let mut app = new_app();
    app.install_list = vec![create_test_package("rg", Source::Aur)];
    app.install_state.select(Some(0));
    let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>();
    let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>();
    let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>();
    let _ = handle_install_key(
        KeyEvent::new(KeyCode::Delete, KeyModifiers::empty()),
        &mut app,
        &dtx,
        &ptx,
        &atx,
    );
    assert!(app.install_list.is_empty());
    assert_eq!(app.install_state.selected(), None);
}