arf-console 0.4.0

A cross-platform R console 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
//! Session information display.

use super::{PagerAction, PagerConfig, PagerContent, copy_to_clipboard, run};
use crate::config::{ConfigStatus, RSourceStatus, mask_home_path};
use crate::editor::prompt::get_r_version;
use crate::external::{formatter, rig};
use crate::repl::state::PromptRuntimeConfig;

use crossterm::event::{KeyCode, KeyModifiers};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use std::path::PathBuf;

/// Display session information for the :info command in a pager.
pub fn display_session_info(
    prompt_config: &PromptRuntimeConfig,
    config_path: &Option<PathBuf>,
    config_status: ConfigStatus,
    r_history_path: &Option<PathBuf>,
    shell_history_path: &Option<PathBuf>,
    r_source_status: &RSourceStatus,
) {
    let lines = generate_info_lines(
        prompt_config,
        config_path,
        config_status,
        r_history_path,
        shell_history_path,
        r_source_status,
    );

    let mut content = SessionInfoContent::new(lines);

    let config = PagerConfig {
        title: "Session Info",
        footer_hint: "↑↓/jk scroll │ c copy │ q exit",
        manage_alternate_screen: true,
    };

    if let Err(e) = run(&mut content, &config) {
        eprintln!("Pager error: {}", e);
    }
}

/// Generate the session information as a vector of lines.
fn generate_info_lines(
    prompt_config: &PromptRuntimeConfig,
    config_path: &Option<PathBuf>,
    config_status: ConfigStatus,
    r_history_path: &Option<PathBuf>,
    shell_history_path: &Option<PathBuf>,
    r_source_status: &RSourceStatus,
) -> Vec<String> {
    let mut lines = Vec::new();

    lines.push("# Session Information".to_string());
    lines.push(String::new());

    // arf version
    lines.push(format!("arf version:    {}", env!("CARGO_PKG_VERSION")));

    // OS information
    lines.push(format!(
        "OS:             {} ({})",
        std::env::consts::OS,
        std::env::consts::ARCH
    ));

    // Config file path
    if let Some(path) = config_path {
        if path.exists() {
            match config_status {
                ConfigStatus::Ok => {
                    lines.push(format!("Config file:    {}", mask_home_path(path)));
                }
                ConfigStatus::ParseError => {
                    lines.push(format!(
                        "Config file:    {} (parse error, using defaults)",
                        mask_home_path(path)
                    ));
                }
                ConfigStatus::ReadError => {
                    lines.push(format!(
                        "Config file:    {} (read error, using defaults)",
                        mask_home_path(path)
                    ));
                }
            }
        } else {
            lines.push(format!(
                "Config file:    {} (not found, using defaults)",
                mask_home_path(path)
            ));
        }
    } else {
        lines.push("Config file:    (using defaults)".to_string());
    }

    // R version
    let r_version = get_r_version();
    if r_version.is_empty() {
        lines.push("R version:      (not available)".to_string());
    } else {
        lines.push(format!("R version:      {}", r_version));
    }

    // R_HOME
    if let Ok(r_home) = std::env::var("R_HOME") {
        let r_home_path = std::path::Path::new(&r_home);
        lines.push(format!("R_HOME:         {}", mask_home_path(r_home_path)));
    }

    // R source (how R was resolved at startup)
    lines.push(format!("R source:       {}", r_source_status.display()));

    lines.push(String::new());

    // rig status
    if rig::rig_available() {
        let mut rig_line = "rig:            installed".to_string();
        if let Ok(versions) = rig::list_versions()
            && !versions.is_empty()
        {
            let version_list: Vec<_> = versions
                .iter()
                .map(|v| {
                    if v.default {
                        format!("{}*", v.name)
                    } else {
                        v.name.clone()
                    }
                })
                .collect();
            rig_line.push_str(&format!(" ({})", version_list.join(", ")));
        }
        lines.push(rig_line);
    } else {
        lines.push("rig:            not installed".to_string());
    }

    // Air (formatter) status
    if formatter::is_formatter_available() {
        lines.push("air:            installed".to_string());
    } else {
        lines.push("air:            not installed".to_string());
    }

    lines.push(String::new());

    // Current mode
    let mode = if prompt_config.is_shell_enabled() {
        "Shell"
    } else if prompt_config.is_reprex_enabled() {
        "R (reprex)"
    } else {
        "R"
    };
    lines.push(format!("Current mode:   {}", mode));

    // Autoformat status (only relevant in reprex mode)
    if prompt_config.is_reprex_enabled() {
        let autoformat = if prompt_config.is_autoformat_enabled() {
            "enabled"
        } else {
            "disabled"
        };
        lines.push(format!("Auto-format:    {}", autoformat));
    }

    lines.push(String::new());

    // History paths
    if let Some(path) = r_history_path {
        lines.push(format!("R history:      {}", mask_home_path(path)));
    }
    if let Some(path) = shell_history_path {
        lines.push(format!("Shell history:  {}", mask_home_path(path)));
    }

    lines.push(String::new());

    // R-related environment variables
    // Format: "VAR_NAME:       value" with aligned colons
    let env_vars = [
        ("ARF_HISTORY_DIR", "ARF_HISTORY_DIR: "),
        ("R_LIBS", "R_LIBS:          "),
        ("R_LIBS_USER", "R_LIBS_USER:     "),
        ("R_LIBS_SITE", "R_LIBS_SITE:     "),
        ("R_PROFILE", "R_PROFILE:       "),
        ("R_ENVIRON", "R_ENVIRON:       "),
    ];
    let mut has_env = false;
    for (var, label) in &env_vars {
        if let Ok(value) = std::env::var(var) {
            if !has_env {
                lines.push("## Environment Variables".to_string());
                lines.push(String::new());
                has_env = true;
            }
            // Mask paths in environment variables too
            let masked_value = mask_env_value(&value);
            lines.push(format!("{}{}", label, masked_value));
        }
    }

    lines
}

/// Mask home directory in environment variable value.
///
/// Handles path-like values which may contain multiple paths separated by
/// the platform's path list separator (`:` on Unix, `;` on Windows).
/// Each path segment is individually checked and masked if it starts with
/// the home directory.
fn mask_env_value(value: &str) -> String {
    let separator = if cfg!(windows) { ';' } else { ':' };

    let masked_parts: Vec<String> = value
        .split(separator)
        .map(|part| {
            let path = std::path::Path::new(part);
            mask_home_path(path)
        })
        .collect();

    masked_parts.join(&separator.to_string())
}

/// Content wrapper for displaying session info in the pager.
struct SessionInfoContent {
    /// Raw info lines.
    lines: Vec<String>,
    /// Feedback message for user actions.
    feedback_message: Option<String>,
}

impl SessionInfoContent {
    fn new(lines: Vec<String>) -> Self {
        Self {
            lines,
            feedback_message: None,
        }
    }

    /// Get all content as plain text for copying.
    fn as_plain_text(&self) -> String {
        self.lines.join("\n")
    }
}

impl PagerContent for SessionInfoContent {
    fn line_count(&self) -> usize {
        self.lines.len()
    }

    fn render_line(&self, index: usize, _width: usize) -> Line<'static> {
        let line = &self.lines[index];
        style_info_line(line)
    }

    fn handle_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> Option<PagerAction> {
        // Copy all content to clipboard
        if code == KeyCode::Char('c') && modifiers == KeyModifiers::NONE {
            let text = self.as_plain_text();
            if copy_to_clipboard(&text).is_ok() {
                self.feedback_message = Some("Copied session info to clipboard".to_string());
            } else {
                self.feedback_message = Some("Failed to copy".to_string());
            }
            return None; // Don't exit, just show feedback
        }
        None
    }

    fn feedback_message(&self) -> Option<&str> {
        self.feedback_message.as_deref()
    }

    fn clear_feedback(&mut self) {
        self.feedback_message = None;
    }
}

/// Apply styling to an info line, returning a ratatui `Line`.
fn style_info_line(line: &str) -> Line<'static> {
    // Headings (# and ##)
    if line.starts_with("# ") || line.starts_with("## ") {
        return Line::from(Span::styled(
            line.to_string(),
            Style::default().add_modifier(Modifier::BOLD),
        ));
    }

    // Key-value pairs (including environment variables)
    if let Some(colon_idx) = line.find(':')
        && !line.starts_with(' ')
    {
        let (key, value) = line.split_at(colon_idx);
        return Line::from(vec![
            Span::styled(key.to_string(), Style::default().fg(Color::Cyan)),
            Span::raw(value.to_string()),
        ]);
    }

    Line::from(line.to_string())
}

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

    #[test]
    fn test_mask_env_value_with_home() {
        if let Some(home) = dirs::home_dir() {
            let home_str = home.display().to_string();
            let sep = std::path::MAIN_SEPARATOR;
            let test_value = format!("{}{}R{}library", home_str, sep, sep);
            let masked = mask_env_value(&test_value);
            assert!(masked.starts_with("~"), "Should mask home dir: {}", masked);
            // Check that "R" and "library" are in the path (separator-agnostic)
            assert!(masked.contains("R"), "Should contain R: {}", masked);
            assert!(
                masked.contains("library"),
                "Should contain library: {}",
                masked
            );
        }
    }

    #[test]
    fn test_mask_env_value_without_home() {
        let test_value = "/opt/R/library";
        // mask_env_value round-trips through Path::display() which may normalize separators
        let expected = std::path::Path::new(test_value).display().to_string();
        let masked = mask_env_value(test_value);
        assert_eq!(masked, expected, "Should not change non-home paths");
    }

    #[test]
    fn test_mask_env_value_multiple_paths() {
        if let Some(home) = dirs::home_dir() {
            let home_str = home.display().to_string();
            let path_sep = std::path::MAIN_SEPARATOR;
            let list_sep = if cfg!(windows) { ';' } else { ':' };
            // Platform-appropriate path list
            let test_value = format!(
                "{}{}.R{}library{}{}{}other",
                home_str, path_sep, path_sep, list_sep, home_str, path_sep
            );
            let masked = mask_env_value(&test_value);
            // Both occurrences should be masked
            assert!(
                !masked.contains(&home_str),
                "All home dirs should be masked: {}",
                masked
            );
            // Check that masked output contains ~ prefix
            assert!(masked.starts_with("~"), "Should start with ~: {}", masked);
        }
    }

    #[test]
    fn test_style_info_line_heading() {
        let styled = style_info_line("# Session Information");
        // Should have bold modifier
        assert!(
            styled.spans[0].style.add_modifier.contains(Modifier::BOLD),
            "Heading should be bold"
        );
    }

    #[test]
    fn test_style_info_line_h2_heading() {
        let styled = style_info_line("## Environment Variables");
        assert!(
            styled.spans[0].style.add_modifier.contains(Modifier::BOLD),
            "H2 heading should be bold"
        );
    }

    #[test]
    fn test_style_info_line_key_value() {
        let styled = style_info_line("arf version:    0.2.1");
        // Key part should be cyan
        assert_eq!(styled.spans[0].style.fg, Some(Color::Cyan));
        assert_eq!(styled.spans[0].content, "arf version");
        // Value part should be unstyled
        assert_eq!(styled.spans[1].content, ":    0.2.1");
    }

    #[test]
    fn test_style_info_line_env_var() {
        let styled = style_info_line("R_LIBS:         /path/to/libs");
        assert_eq!(styled.spans[0].style.fg, Some(Color::Cyan));
        assert_eq!(styled.spans[0].content, "R_LIBS");
    }

    #[test]
    fn test_style_info_line_empty() {
        let styled = style_info_line("");
        // Empty string produces a Line with no spans
        assert!(styled.spans.is_empty() || styled.spans[0].content.is_empty());
    }

    #[test]
    fn test_style_info_line_plain() {
        let styled = style_info_line("Some plain text without special formatting");
        assert_eq!(styled.spans.len(), 1);
        assert_eq!(
            styled.spans[0].content,
            "Some plain text without special formatting"
        );
        assert_eq!(styled.spans[0].style, Style::default());
    }

    #[test]
    fn test_session_info_content_as_plain_text() {
        let lines = vec![
            "# Test".to_string(),
            "key: value".to_string(),
            "".to_string(),
        ];
        let content = SessionInfoContent::new(lines);
        let plain = content.as_plain_text();
        assert_eq!(plain, "# Test\nkey: value\n");
    }

    #[test]
    fn test_session_info_content_line_count() {
        let lines = vec!["line1".to_string(), "line2".to_string()];
        let content = SessionInfoContent::new(lines);
        assert_eq!(content.line_count(), 2);
    }

    // --- generate_info_lines config_path tests ---

    use crate::editor::prompt::PromptFormatter;
    use crate::repl::state::PromptRuntimeConfig;

    fn default_prompt_config() -> PromptRuntimeConfig {
        PromptRuntimeConfig::builder(PromptFormatter::default(), "r> ", "+  ", "[bash] $ ").build()
    }

    #[test]
    fn test_generate_info_lines_config_path_none() {
        let config = default_prompt_config();
        let lines = generate_info_lines(
            &config,
            &None,
            ConfigStatus::Ok,
            &None,
            &None,
            &RSourceStatus::Path,
        );
        let config_line = lines
            .iter()
            .find(|l| l.starts_with("Config file:"))
            .unwrap();
        assert!(
            config_line.contains("using defaults"),
            "None path should show defaults: {}",
            config_line
        );
    }

    #[test]
    fn test_generate_info_lines_config_path_existing() {
        let config = default_prompt_config();
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_path_buf();
        let masked = mask_home_path(&path);
        let lines = generate_info_lines(
            &config,
            &Some(path),
            ConfigStatus::Ok,
            &None,
            &None,
            &RSourceStatus::Path,
        );
        let config_line = lines
            .iter()
            .find(|l| l.starts_with("Config file:"))
            .unwrap();
        assert!(
            config_line.contains(&masked),
            "Existing path should contain the file path: {}",
            config_line
        );
        assert!(
            !config_line.contains("not found"),
            "Existing path should not say 'not found': {}",
            config_line
        );
        assert!(
            !config_line.contains("using defaults"),
            "Existing path should not say 'using defaults': {}",
            config_line
        );
    }

    #[test]
    fn test_generate_info_lines_config_path_nonexistent() {
        let config = default_prompt_config();
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("nonexistent_config.toml");
        let lines = generate_info_lines(
            &config,
            &Some(path),
            ConfigStatus::Ok,
            &None,
            &None,
            &RSourceStatus::Path,
        );
        let config_line = lines
            .iter()
            .find(|l| l.starts_with("Config file:"))
            .unwrap();
        assert!(
            config_line.contains("not found"),
            "Non-existing path should say 'not found': {}",
            config_line
        );
    }

    #[test]
    fn test_generate_info_lines_config_parse_error() {
        let config = default_prompt_config();
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_path_buf();
        let lines = generate_info_lines(
            &config,
            &Some(path),
            ConfigStatus::ParseError,
            &None,
            &None,
            &RSourceStatus::Path,
        );
        let config_line = lines
            .iter()
            .find(|l| l.starts_with("Config file:"))
            .unwrap();
        assert!(
            config_line.contains("parse error"),
            "Parse error should be shown: {}",
            config_line
        );
    }

    #[test]
    fn test_generate_info_lines_config_read_error() {
        let config = default_prompt_config();
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let path = temp_file.path().to_path_buf();
        let lines = generate_info_lines(
            &config,
            &Some(path),
            ConfigStatus::ReadError,
            &None,
            &None,
            &RSourceStatus::Path,
        );
        let config_line = lines
            .iter()
            .find(|l| l.starts_with("Config file:"))
            .unwrap();
        assert!(
            config_line.contains("read error"),
            "Read error should be shown: {}",
            config_line
        );
    }
}