arf-console 0.5.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
//! Core R source resolution.

use super::overrides::{OverrideResolution, setup_r_via_overrides};
use super::rig::{ResolvedRSource, resolve_r_home_from_path, setup_r_via_rig};
use crate::config::{
    RSource, RSourceMode, RSourceOverride, RSourceOverrideInfo, RSourceStatus, mask_home_path,
};
use crate::external;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

/// Set up R based on r_source configuration.
///
/// CLI options override config in this order:
/// 1. `cli_r_home` - explicit R_HOME path
/// 2. `cli_version` - rig version specification
/// 3. Experimental directory-level R source overrides
/// 4. Config `r_source` setting
///
/// The state of override resolution for reporting to users and headless clients.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RSourceOverrideState {
    /// An override selected the active R installation.
    Applied,
    /// No R source override providers are configured.
    NotConfigured,
    /// No configured provider matched a file in the current directory.
    NoMatch,
    /// At least one provider was evaluated but no override could be applied.
    Failed,
    /// Override resolution was disabled by the CLI.
    Disabled,
    /// A CLI R source took precedence over overrides.
    ShadowedByCli,
}

impl RSourceOverrideState {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Applied => "applied",
            Self::NotConfigured => "not_configured",
            Self::NoMatch => "no_match",
            Self::Failed => "failed",
            Self::Disabled => "disabled",
            Self::ShadowedByCli => "shadowed_by_cli",
        }
    }
}

/// A warning produced while resolving an R source.
#[derive(Debug, Clone)]
pub(crate) struct RSourceDiagnostic {
    pub(crate) code: &'static str,
    pub(crate) severity: &'static str,
    pub(crate) message: String,
    pub(crate) path: Option<PathBuf>,
}

pub(super) fn warning(
    code: &'static str,
    message: impl Into<String>,
    path: Option<PathBuf>,
) -> RSourceDiagnostic {
    RSourceDiagnostic {
        code,
        severity: "warning",
        message: message.into(),
        path,
    }
}

/// The result of resolving the configured R source and any directory override.
#[derive(Debug, Clone)]
pub(crate) struct RSourceResolutionReport {
    pub(crate) status: RSourceStatus,
    pub(crate) r_home: Option<PathBuf>,
    pub(crate) provider: Option<String>,
    pub(crate) file: Option<std::path::PathBuf>,
    pub(crate) key: Option<String>,
    pub(crate) requested_version: Option<String>,
    pub(crate) resolved_version: Option<String>,
    pub(crate) diagnostics: Vec<RSourceDiagnostic>,
    pub(crate) override_state: RSourceOverrideState,
}

impl RSourceResolutionReport {
    pub(super) fn from_status(
        status: RSourceStatus,
        r_home: Option<PathBuf>,
        override_state: RSourceOverrideState,
    ) -> Self {
        Self {
            status,
            r_home,
            provider: None,
            file: None,
            key: None,
            requested_version: None,
            resolved_version: None,
            diagnostics: Vec::new(),
            override_state,
        }
    }

    pub(super) fn applied(
        status: RSourceStatus,
        r_home: PathBuf,
        info: RSourceOverrideInfo,
        diagnostics: Vec<RSourceDiagnostic>,
    ) -> Self {
        Self {
            status,
            r_home: Some(r_home),
            provider: Some(info.provider),
            file: info.file,
            key: info.key,
            requested_version: Some(info.requested_version),
            resolved_version: Some(info.resolved_version),
            diagnostics,
            override_state: RSourceOverrideState::Applied,
        }
    }

    /// Emit all override diagnostics as one warning block for normal startup.
    pub(crate) fn emit_diagnostics(&self) {
        if self.diagnostics.is_empty() {
            return;
        }
        let block = self
            .diagnostics
            .iter()
            .map(display_message)
            .collect::<Vec<_>>()
            .join("\n");
        eprintln!("{block}");
        log::warn!("{block}");
    }

    pub(crate) fn override_info(&self) -> Option<RSourceOverrideInfo> {
        Some(RSourceOverrideInfo {
            provider: self.provider.clone()?,
            file: self.file.clone(),
            key: self.key.clone(),
            requested_version: self.requested_version.clone()?,
            resolved_version: self.resolved_version.clone()?,
        })
    }
}

fn display_message(diagnostic: &RSourceDiagnostic) -> String {
    let Some(path) = diagnostic.path.as_ref() else {
        return diagnostic.message.clone();
    };

    let raw_path = path.display().to_string();
    diagnostic.message.replace(&raw_path, &mask_home_path(path))
}

/// Resolve R and return a report without changing the process environment.
pub(crate) fn resolve_r_source(
    r_source: &RSource,
    r_source_overrides: &[RSourceOverride],
    base_dir: Option<&Path>,
    cli_r_home: Option<&std::path::Path>,
    cli_version: Option<&str>,
    no_r_source_overrides: bool,
) -> Result<RSourceResolutionReport> {
    // CLI --r-home overrides everything. An explicit disable still controls
    // the reported override state without changing the selected R source.
    if let Some(path) = cli_r_home {
        if !path.exists() {
            anyhow::bail!(
                "R_HOME path does not exist: {}\n\
                 Check your --r-home argument.",
                path.display()
            );
        }
        // Resolve R_HOME: if path looks like an installation prefix (has bin/R),
        // run `bin/R RHOME` to get the actual R_HOME directory
        let r_home = resolve_r_home_from_path(path)?;
        log::info!("Using R from --r-home: {}", r_home.display());
        return Ok(RSourceResolutionReport::from_status(
            RSourceStatus::ExplicitPath {
                path: r_home.clone(),
            },
            Some(r_home),
            if no_r_source_overrides {
                RSourceOverrideState::Disabled
            } else {
                RSourceOverrideState::ShadowedByCli
            },
        ));
    }

    // CLI --with-r-version overrides config (uses rig)
    if let Some(version) = cli_version {
        return setup_r_via_rig(version).map(|resolved| {
            RSourceResolutionReport::from_status(
                resolved.status,
                resolved.r_home,
                if no_r_source_overrides {
                    RSourceOverrideState::Disabled
                } else {
                    RSourceOverrideState::ShadowedByCli
                },
            )
        });
    }

    if no_r_source_overrides {
        return setup_r_fallback(r_source, RSourceOverrideState::Disabled);
    }

    if let Some(result) = setup_r_via_overrides(r_source_overrides, base_dir) {
        match result {
            OverrideResolution::Applied {
                status,
                r_home,
                info,
                diagnostics,
            } => {
                return Ok(RSourceResolutionReport::applied(
                    *status,
                    r_home,
                    info,
                    diagnostics,
                ));
            }
            OverrideResolution::Fallback { diagnostics } => {
                let mut report = setup_r_fallback(r_source, RSourceOverrideState::Failed)?;
                report.diagnostics = diagnostics;
                return Ok(report);
            }
        }
    }

    let override_state = if r_source_overrides.is_empty() {
        RSourceOverrideState::NotConfigured
    } else {
        RSourceOverrideState::NoMatch
    };
    setup_r_fallback(r_source, override_state)
}

/// Apply a resolved R source to the process environment during startup.
pub(crate) fn apply_r_source(resolution: &RSourceResolutionReport) -> Result<()> {
    if matches!(resolution.status, RSourceStatus::Path) {
        return Ok(());
    }

    let r_home = resolution
        .r_home
        .as_ref()
        .context("Resolved R source has no R_HOME")?;
    // SAFETY: This is called single-threaded during startup, before R is initialized.
    unsafe { std::env::set_var("R_HOME", r_home) };
    Ok(())
}

/// Set up R and return a resolution report for display and feature gating.
pub(crate) fn setup_r(
    r_source: &RSource,
    r_source_overrides: &[RSourceOverride],
    base_dir: Option<&Path>,
    cli_r_home: Option<&std::path::Path>,
    cli_version: Option<&str>,
    no_r_source_overrides: bool,
) -> Result<RSourceResolutionReport> {
    let resolution = resolve_r_source(
        r_source,
        r_source_overrides,
        base_dir,
        cli_r_home,
        cli_version,
        no_r_source_overrides,
    )?;
    apply_r_source(&resolution)?;
    Ok(resolution)
}

fn setup_r_fallback(
    r_source: &RSource,
    override_state: RSourceOverrideState,
) -> Result<RSourceResolutionReport> {
    setup_r_fallback_with(
        r_source,
        override_state,
        external::rig::rig_available,
        external::rig::resolve_version,
    )
}

pub(super) fn setup_r_fallback_with<FAvailable, FResolve>(
    r_source: &RSource,
    override_state: RSourceOverrideState,
    rig_available: FAvailable,
    resolve_version: FResolve,
) -> Result<RSourceResolutionReport>
where
    FAvailable: Fn() -> std::result::Result<(), external::rig::RigError>,
    FResolve:
        Fn(&str) -> std::result::Result<external::rig::ResolvedVersion, external::rig::RigError>,
{
    let resolved = match r_source {
        RSource::Mode(RSourceMode::Auto) => {
            // Auto mode: try rig if available, otherwise use PATH
            if rig_available().is_ok() {
                match resolve_version("default") {
                    Ok(resolved) => {
                        log::info!("Using rig default R version: {}", resolved.version);
                        ResolvedRSource {
                            status: RSourceStatus::Rig {
                                version: resolved.version,
                                override_info: None,
                            },
                            r_home: Some(PathBuf::from(resolved.r_home)),
                        }
                    }
                    Err(e) => {
                        log::debug!("Could not get rig default version: {}", e);
                        log::info!("Using R from PATH");
                        ResolvedRSource {
                            // Do not discover or assign R_HOME here. R will discover it
                            // during initialization, preserving PATH-mode startup behavior.
                            status: RSourceStatus::Path,
                            r_home: None,
                        }
                    }
                }
            } else {
                log::info!("Using R from PATH (rig not available)");
                ResolvedRSource {
                    // Do not discover or assign R_HOME here. R will discover it
                    // during initialization, preserving PATH-mode startup behavior.
                    status: RSourceStatus::Path,
                    r_home: None,
                }
            }
        }
        RSource::Mode(RSourceMode::Rig) => {
            // Rig mode: require rig
            match rig_available() {
                Ok(()) => {}
                Err(external::rig::RigError::NotInstalled) => {
                    anyhow::bail!(
                        r#"r_source = "rig" but rig is not installed.
Install rig from https://github.com/r-lib/rig or use "auto"."#
                    );
                }
                Err(external::rig::RigError::CommandFailed(reason)) => {
                    anyhow::bail!(
                        r#"r_source = "rig" but rig is installed and could not be run: {reason}.
Fix the rig installation or use "auto"."#
                    );
                }
                Err(error) => {
                    anyhow::bail!(
                        r#"r_source = "rig" but rig availability could not be checked: {error}.
Fix the rig installation or use "auto"."#
                    );
                }
            }
            match resolve_version("default") {
                Ok(resolved) => {
                    log::info!("Using rig default R version: {}", resolved.version);
                    ResolvedRSource {
                        status: RSourceStatus::Rig {
                            version: resolved.version,
                            override_info: None,
                        },
                        r_home: Some(PathBuf::from(resolved.r_home)),
                    }
                }
                Err(e) => {
                    anyhow::bail!("Failed to get rig default R version: {}", e);
                }
            }
        }
        RSource::Path { path } => {
            // Explicit path mode
            if !path.exists() {
                anyhow::bail!(
                    "R_HOME path does not exist: {}\n\
                     Check your r_source configuration.",
                    path.display()
                );
            }
            log::info!("Using R from explicit path: {}", path.display());
            ResolvedRSource {
                status: RSourceStatus::ExplicitPath { path: path.clone() },
                r_home: Some(path.clone()),
            }
        }
    };

    Ok(RSourceResolutionReport::from_status(
        resolved.status,
        resolved.r_home,
        override_state,
    ))
}

fn resolve_path_r_home_with<F>(find_r_library: F) -> Result<PathBuf>
where
    F: FnOnce() -> arf_libr::RResult<PathBuf>,
{
    let library_path = find_r_library().context("Failed to discover the R library from PATH")?;
    arf_libr::r_home_from_library_path(&library_path).with_context(|| {
        format!(
            "Failed to derive R_HOME from discovered R library: {}",
            library_path.display()
        )
    })
}

/// Resolve the PATH-mode R_HOME only for callers that need to report it.
pub(crate) fn resolve_path_r_home_for_report(report: &mut RSourceResolutionReport) {
    resolve_path_r_home_for_report_with(report, arf_libr::find_r_library);
}

pub(super) fn resolve_path_r_home_for_report_with<F>(
    report: &mut RSourceResolutionReport,
    find_r_library: F,
) where
    F: FnOnce() -> arf_libr::RResult<PathBuf>,
{
    if !matches!(report.status, RSourceStatus::Path) || report.r_home.is_some() {
        return;
    }

    match resolve_path_r_home_with(find_r_library) {
        Ok(r_home) => report.r_home = Some(r_home),
        Err(error) => {
            // When discovery is disabled the cause already explains itself, so
            // report it alone: the surrounding context describes a PATH search
            // that never ran. Take the payload rather than the `RError`
            // display, whose "not found at:" wording would read as a path.
            let disabled_message = arf_libr::is_r_auto_discovery_disabled()
                .then(
                    || match error.root_cause().downcast_ref::<arf_libr::RError>() {
                        Some(arf_libr::RError::LibraryNotFound(message)) => Some(message.clone()),
                        _ => None,
                    },
                )
                .flatten();
            let message = match disabled_message {
                Some(cause) => format!("Warning: {cause}"),
                None => format!("Warning: Failed to determine R_HOME from PATH: {error}"),
            };
            report
                .diagnostics
                .push(warning("r_discovery.failed", message, None));
        }
    }
}

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

    #[test]
    fn display_message_masks_its_own_path_and_leaves_pathless_messages_unchanged() {
        // display_message reads HOME indirectly through dirs::home_dir and mask_home_path.
        let _guard = crate::test_utils::lock_env();
        let home = dirs::home_dir().expect("test requires a home directory");
        let path = home.join("arf").join("broken.toml");
        let diagnostic = RSourceDiagnostic {
            code: "config.parse_failed",
            severity: "warning",
            message: format!(
                r#"Failed to load config from {}: TOML parse error"#,
                path.display()
            ),
            path: Some(path.clone()),
        };
        let pathless = RSourceDiagnostic {
            code: "r_discovery.failed",
            severity: "warning",
            message: r#"R automatic discovery failed."#.to_owned(),
            path: None,
        };

        // Assert the masking took effect rather than comparing against
        // `mask_home_path` again, which would also pass if it stopped masking.
        let masked = display_message(&diagnostic);
        assert!(
            masked.starts_with("Failed to load config from ~"),
            "{masked}"
        );
        assert!(!masked.contains(&home.display().to_string()), "{masked}");
        assert!(
            masked.ends_with("broken.toml: TOML parse error"),
            "{masked}"
        );

        assert_eq!(display_message(&pathless), pathless.message);
    }

    #[test]
    fn explicit_rig_mode_reports_command_failure_without_install_guidance() {
        let result = setup_r_fallback_with(
            &RSource::Mode(RSourceMode::Rig),
            RSourceOverrideState::NotConfigured,
            || {
                Err(external::rig::RigError::CommandFailed(
                    "permission denied".to_string(),
                ))
            },
            |_| panic!("rig's default version should not be resolved"),
        );

        let error = result.expect_err("rig command failure should reject explicit rig mode");
        let message = error.to_string();
        assert!(message.contains("permission denied"));
        assert!(!message.contains("Install rig"));
    }
}