arf-console 0.6.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! R code formatter integration.
//!
//! This module provides formatting of R code using external formatter backends.

use crate::config::{FormatterBackend, ReprexFormatter};
use std::ffi::OsStr;
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::OnceLock;

const AIR_STDIN_FILE_PATH: &str = "arf-reprex.R";

/// The user-facing context for a missing formatter diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormatterUnavailableContext {
    /// An explicit `--reprex=format` request.
    ExplicitCli,
    /// A configured format mode that will fall back to reprex on mode.
    ConfiguredMode,
    /// The interactive `:reprex format` command.
    MetaCommand,
}

/// Build the diagnostic shown when a configured formatter is unavailable.
pub fn unavailable_message(
    formatter: ReprexFormatter,
    context: FormatterUnavailableContext,
) -> String {
    let backend = match formatter {
        ReprexFormatter::Auto => "Air and Arity formatter CLIs".to_string(),
        ReprexFormatter::Air => "Air CLI ('air' command)".to_string(),
        ReprexFormatter::Arity => "Arity CLI ('arity' command)".to_string(),
    };
    match context {
        FormatterUnavailableContext::ExplicitCli => format!(
            "Cannot use --reprex=format: {backend} not found in PATH.\n{}",
            install_guidance(formatter)
        ),
        FormatterUnavailableContext::ConfiguredMode => format!(
            "Warning: Reprex format mode is configured but {backend} was not found; using reprex on mode."
        ),
        FormatterUnavailableContext::MetaCommand => {
            format!("Error: Cannot use reprex format mode - {backend} not found in PATH.")
        }
    }
}

fn install_guidance(formatter: ReprexFormatter) -> String {
    match formatter {
        ReprexFormatter::Auto => {
            "Install Air CLI from https://github.com/posit-dev/air or Arity CLI from https://github.com/jolars/arity".to_string()
        }
        ReprexFormatter::Air => format!(
            "Install Air CLI from {}",
            FormatterBackend::Air.install_url()
        ),
        ReprexFormatter::Arity => format!(
            "Install Arity CLI from {}",
            FormatterBackend::Arity.install_url()
        ),
    }
}

/// Resolve a configured formatter selector to a concrete backend.
pub fn resolve_formatter(selector: ReprexFormatter) -> Option<FormatterBackend> {
    resolve_formatter_with(selector, is_formatter_available)
}

/// Resolve a formatter using an injected availability function.
///
/// The injected form keeps selector precedence deterministic in tests without
/// mutating process-global PATH state or the availability cache.
pub fn resolve_formatter_with(
    selector: ReprexFormatter,
    mut available: impl FnMut(FormatterBackend) -> bool,
) -> Option<FormatterBackend> {
    match selector {
        ReprexFormatter::Auto => [FormatterBackend::Air, FormatterBackend::Arity]
            .into_iter()
            .find(|backend| available(*backend)),
        ReprexFormatter::Air => available(FormatterBackend::Air).then_some(FormatterBackend::Air),
        ReprexFormatter::Arity => {
            available(FormatterBackend::Arity).then_some(FormatterBackend::Arity)
        }
    }
}

/// Check if a formatter backend is available on the system.
pub fn is_formatter_available(formatter: FormatterBackend) -> bool {
    match formatter {
        FormatterBackend::Air => {
            static AIR_AVAILABLE: OnceLock<bool> = OnceLock::new();
            *AIR_AVAILABLE.get_or_init(|| {
                Command::new(formatter.command())
                    .arg("--version")
                    .output()
                    .map(|o| o.status.success())
                    .unwrap_or(false)
            })
        }
        FormatterBackend::Arity => {
            static ARITY_AVAILABLE: OnceLock<bool> = OnceLock::new();
            *ARITY_AVAILABLE.get_or_init(|| {
                Command::new(formatter.command())
                    .arg("--version")
                    .output()
                    .map(|o| o.status.success())
                    .unwrap_or(false)
            })
        }
    }
}

/// Format R code using the selected backend.
///
/// Returns the formatted code on success, or a formatting error.
/// Callers must not evaluate the unformatted code when an error is returned.
///
/// The current backend reads code from stdin and writes formatted code to stdout.
/// Its virtual path lets the backend discover project configuration from the cwd.
pub fn format_code(formatter: FormatterBackend, code: &str) -> Result<String, FormatterError> {
    match formatter {
        FormatterBackend::Air | FormatterBackend::Arity => format_backend(formatter, code),
    }
}

fn format_backend(formatter: FormatterBackend, code: &str) -> Result<String, FormatterError> {
    // Skip empty or whitespace-only input
    if code.trim().is_empty() {
        return Ok(code.to_string());
    }

    // Check if formatter is available
    if !is_formatter_available(formatter) {
        log::debug!(
            "Formatter '{}' not available, skipping format",
            formatter.command()
        );
        return Err(FormatterError::Io {
            formatter,
            source: std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("{} command is unavailable", formatter.command()),
            ),
        });
    }

    match format_via_stdin(formatter, code) {
        Ok(formatted) => Ok(formatted),
        Err(e) => {
            log::debug!("Formatting failed: {}", e);
            Err(e)
        }
    }
}

fn formatter_args(formatter: FormatterBackend, virtual_path: &Path) -> Vec<String> {
    match formatter {
        FormatterBackend::Air => vec![
            "format".to_string(),
            "--stdin-file-path".to_string(),
            virtual_path.display().to_string(),
            "--force".to_string(),
        ],
        FormatterBackend::Arity => vec!["format".to_string(), "-".to_string()],
    }
}

fn format_via_stdin(formatter: FormatterBackend, code: &str) -> Result<String, FormatterError> {
    run_formatter_command(
        formatter,
        OsStr::new(formatter.command()),
        Path::new(AIR_STDIN_FILE_PATH),
        code,
    )
}

fn run_formatter_command(
    formatter: FormatterBackend,
    command: &OsStr,
    virtual_path: &Path,
    code: &str,
) -> Result<String, FormatterError> {
    run_formatter_command_with_prefix_args(formatter, command, &[], virtual_path, code)
}

fn run_formatter_command_with_prefix_args(
    formatter: FormatterBackend,
    command: &OsStr,
    prefix_args: &[&str],
    virtual_path: &Path,
    code: &str,
) -> Result<String, FormatterError> {
    let args = formatter_args(formatter, virtual_path);
    let mut child = Command::new(command)
        .args(prefix_args)
        .args(&args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|source| FormatterError::Io { formatter, source })?;

    child
        .stdin
        .take()
        .ok_or_else(|| FormatterError::Io {
            formatter,
            source: std::io::Error::other("formatter stdin unavailable"),
        })?
        .write_all(code.as_bytes())
        .map_err(|source| FormatterError::Io { formatter, source })?;
    let output = child
        .wait_with_output()
        .map_err(|source| FormatterError::Io { formatter, source })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // Parse errors are common (incomplete expressions), don't log as error
        if stderr.contains("Parse") || stderr.contains("parse") {
            log::trace!(
                "Formatter parse error (expected for incomplete code): {}",
                stderr
            );
        } else {
            log::debug!("Formatter returned error: {}", stderr);
        }
        return Err(FormatterError::FormatFailed {
            formatter,
            stderr: stderr.to_string(),
        });
    }

    let formatted =
        String::from_utf8(output.stdout).map_err(|error| FormatterError::FormatFailed {
            formatter,
            stderr: error.to_string(),
        })?;
    Ok(preserve_newline_style(code, formatted))
}

fn preserve_newline_style(original: &str, mut formatted: String) -> String {
    let original_crlf = original.ends_with("\r\n");
    let original_has_newline = original.ends_with('\n');
    let formatted_has_newline = formatted.ends_with('\n');

    if !original_has_newline && formatted_has_newline {
        formatted.pop();
        if formatted.ends_with('\r') {
            formatted.pop();
        }
    } else if original_crlf {
        formatted = formatted.replace("\r\n", "\n").replace('\n', "\r\n");
    } else if original_has_newline {
        formatted = formatted.replace("\r\n", "\n");
    }
    formatted
}

/// Errors that can occur during formatting.
#[derive(Debug)]
pub enum FormatterError {
    Unavailable {
        selector: ReprexFormatter,
    },
    Io {
        formatter: FormatterBackend,
        source: std::io::Error,
    },
    FormatFailed {
        formatter: FormatterBackend,
        stderr: String,
    },
}

impl std::fmt::Display for FormatterError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FormatterError::Unavailable { selector } => write!(
                f,
                "No formatter backend is available for selector '{selector}'."
            ),
            FormatterError::Io { formatter, source } => write!(
                f,
                "{} formatting could not be started: {}\nEnsure {} CLI {} or later is installed.",
                formatter.display_name(),
                source,
                formatter.display_name(),
                formatter.minimum_version()
            ),
            FormatterError::FormatFailed { formatter, stderr } => write!(
                f,
                "{} formatting failed: {}\nEnsure {} CLI {} or later is installed.",
                formatter.display_name(),
                stderr.trim(),
                formatter.display_name(),
                formatter.minimum_version()
            ),
        }
    }
}

impl std::error::Error for FormatterError {}

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

    #[test]
    fn test_format_empty_code() {
        let result = format_code(FormatterBackend::Air, "").unwrap();
        assert_eq!(result, "");

        let result = format_code(FormatterBackend::Air, "   ").unwrap();
        assert_eq!(result, "   ");
    }

    #[test]
    fn formatter_args_use_air_stdin_contract() {
        assert_eq!(
            formatter_args(FormatterBackend::Air, Path::new("arf-reprex.R")),
            ["format", "--stdin-file-path", "arf-reprex.R", "--force"]
        );
    }

    #[test]
    fn formatter_args_use_arity_stdin_contract() {
        assert_eq!(
            formatter_args(FormatterBackend::Arity, Path::new("arf-reprex.R")),
            ["format", "-"]
        );
    }

    #[test]
    fn formatter_resolution_prefers_air_when_both_are_available() {
        assert_eq!(
            resolve_formatter_with(ReprexFormatter::Auto, |backend| {
                matches!(backend, FormatterBackend::Air | FormatterBackend::Arity)
            }),
            Some(FormatterBackend::Air)
        );
    }

    #[test]
    fn formatter_resolution_uses_air_when_only_air_is_available() {
        assert_eq!(
            resolve_formatter_with(ReprexFormatter::Auto, |backend| {
                backend == FormatterBackend::Air
            }),
            Some(FormatterBackend::Air)
        );
    }

    #[test]
    fn formatter_resolution_uses_arity_when_air_is_unavailable() {
        assert_eq!(
            resolve_formatter_with(ReprexFormatter::Auto, |backend| {
                backend == FormatterBackend::Arity
            }),
            Some(FormatterBackend::Arity)
        );
    }

    #[test]
    fn formatter_resolution_returns_none_when_no_backend_is_available() {
        assert_eq!(
            resolve_formatter_with(ReprexFormatter::Auto, |_| false),
            None
        );
    }

    #[test]
    fn explicit_formatter_selection_does_not_fallback() {
        assert_eq!(
            resolve_formatter_with(ReprexFormatter::Air, |backend| {
                backend == FormatterBackend::Arity
            }),
            None
        );
        assert_eq!(
            resolve_formatter_with(ReprexFormatter::Arity, |backend| {
                backend == FormatterBackend::Air
            }),
            None
        );
    }

    #[test]
    fn formatter_process_receives_stdin_and_expected_arguments() {
        let command = std::env::current_exe().unwrap();
        let result = run_formatter_command_with_prefix_args(
            FormatterBackend::Air,
            command.as_os_str(),
            &test_formatter_prefix_args(),
            Path::new("virtual.R"),
            "x <- 1",
        );
        assert_eq!(test_formatter_output(&result.unwrap()), "x <- 1");
    }

    #[test]
    fn arity_process_receives_stdin_and_expected_arguments() {
        let command = std::env::current_exe().unwrap();
        let result = run_formatter_command_with_prefix_args(
            FormatterBackend::Arity,
            command.as_os_str(),
            &test_formatter_prefix_args(),
            Path::new("virtual.R"),
            "x <- 1",
        );
        assert_eq!(test_formatter_output(&result.unwrap()), "x <- 1");
    }

    #[test]
    fn formatter_process_failure_is_returned_as_an_error() {
        let command = std::env::current_exe().unwrap();
        let result = run_formatter_command_with_prefix_args(
            FormatterBackend::Air,
            command.as_os_str(),
            &test_formatter_prefix_args(),
            Path::new("virtual.R"),
            "formatter failure test",
        );
        assert!(
            matches!(result, Err(FormatterError::FormatFailed { stderr, .. }) if stderr.contains("formatter failed"))
        );
    }

    fn test_formatter_prefix_args() -> [&'static str; 3] {
        [
            "--exact",
            "external::formatter::tests::formatter_test_helper_process",
            "--",
        ]
    }

    fn test_formatter_output(output: &str) -> &str {
        const START: &str = "\0formatter-output-start\0";
        const END: &str = "\0formatter-output-end\0";
        output
            .split_once(START)
            .and_then(|(_, output)| output.split_once(END))
            .map(|(output, _)| output)
            .expect("test formatter output markers are present")
    }

    #[test]
    fn formatter_test_helper_process() {
        let args: Vec<_> = std::env::args_os().collect();
        let helper_prefix = [
            OsStr::new("--exact"),
            OsStr::new("external::formatter::tests::formatter_test_helper_process"),
            OsStr::new("--"),
        ];
        if !args.get(1..4).is_some_and(|args| args == helper_prefix) {
            return;
        }
        let formatter_args: Vec<_> = args[4..]
            .iter()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        assert!(
            formatter_args == ["format", "--stdin-file-path", "virtual.R", "--force"]
                || formatter_args == ["format", "-"],
            "unexpected formatter arguments: {formatter_args:?}"
        );

        use std::io::{Read, Write};
        let mut input = String::new();
        std::io::stdin().read_to_string(&mut input).unwrap();
        if input == "formatter failure test" {
            writeln!(std::io::stderr(), "formatter failed").unwrap();
            std::process::exit(17);
        }
        let mut stdout = std::io::stdout();
        stdout.write_all(b"\0formatter-output-start\0").unwrap();
        stdout.write_all(input.as_bytes()).unwrap();
        stdout.write_all(b"\0formatter-output-end\0").unwrap();
    }

    #[test]
    fn formatter_failure_message_includes_stderr_and_version_guidance() {
        let error = FormatterError::FormatFailed {
            formatter: FormatterBackend::Air,
            stderr: "stdin parse error\n".to_string(),
        };
        insta::assert_snapshot!(format!("{error}"), @r###"
Air formatting failed: stdin parse error
Ensure Air CLI 0.9.0 or later is installed.
"###);
    }

    #[test]
    fn arity_failure_message_includes_stderr_and_version_guidance() {
        let error = FormatterError::FormatFailed {
            formatter: FormatterBackend::Arity,
            stderr: "stdin parse error\n".to_string(),
        };
        insta::assert_snapshot!(format!("{error}"), @r###"
Arity formatting failed: stdin parse error
Ensure Arity CLI 0.18.0 or later is installed.
"###);
    }

    #[test]
    fn preserve_newline_style_keeps_trailing_style() {
        assert_eq!(preserve_newline_style("x", "x\n".to_string()), "x");
        assert_eq!(preserve_newline_style("x\n", "x\r\n".to_string()), "x\n");
        assert_eq!(preserve_newline_style("x\r\n", "x\n".to_string()), "x\r\n");
    }

    #[test]
    fn unavailable_explicit_cli_message_snapshot() {
        insta::assert_snapshot!(
            unavailable_message(
                ReprexFormatter::Air,
                FormatterUnavailableContext::ExplicitCli
            ),
            @r###"
Cannot use --reprex=format: Air CLI ('air' command) not found in PATH.
Install Air CLI from https://github.com/posit-dev/air
"###
        );
    }

    #[test]
    fn unavailable_configured_mode_message_snapshot() {
        insta::assert_snapshot!(
            unavailable_message(
                ReprexFormatter::Air,
                FormatterUnavailableContext::ConfiguredMode
            ),
            @r###"Warning: Reprex format mode is configured but Air CLI ('air' command) was not found; using reprex on mode."###
        );
    }

    #[test]
    fn unavailable_meta_command_message_snapshot() {
        insta::assert_snapshot!(
            unavailable_message(
                ReprexFormatter::Air,
                FormatterUnavailableContext::MetaCommand
            ),
            @r###"Error: Cannot use reprex format mode - Air CLI ('air' command) not found in PATH."###
        );
    }

    #[test]
    fn unavailable_arity_explicit_cli_message_snapshot() {
        insta::assert_snapshot!(
            unavailable_message(
                ReprexFormatter::Arity,
                FormatterUnavailableContext::ExplicitCli
            ),
            @r###"
Cannot use --reprex=format: Arity CLI ('arity' command) not found in PATH.
Install Arity CLI from https://github.com/jolars/arity
"###
        );
    }

    #[test]
    fn unavailable_auto_explicit_cli_message_snapshot() {
        insta::assert_snapshot!(
            unavailable_message(
                ReprexFormatter::Auto,
                FormatterUnavailableContext::ExplicitCli
            ),
            @r###"
Cannot use --reprex=format: Air and Arity formatter CLIs not found in PATH.
Install Air CLI from https://github.com/posit-dev/air or Arity CLI from https://github.com/jolars/arity
"###
        );
    }

    #[test]
    #[ignore] // Requires air to be installed
    fn test_format_simple_assignment() {
        let code = "x<-1+2";
        let result = format_code(FormatterBackend::Air, code).unwrap();
        assert_eq!(result, "x <- 1 + 2");
    }

    #[test]
    #[ignore] // Requires air to be installed
    fn test_format_function_definition() {
        let code = "f=function(x,y){x+y}";
        let result = format_code(FormatterBackend::Air, code).unwrap();
        // air formats this with proper spacing and indentation
        assert!(result.contains("function(x, y)"));
        assert!(result.contains("x + y"));
    }

    #[test]
    #[ignore] // Requires air to be installed
    fn test_format_preserves_trailing_newline_style() {
        // Without trailing newline
        let code = "x <- 1";
        let result = format_code(FormatterBackend::Air, code).unwrap();
        assert!(!result.ends_with('\n'));

        // With trailing newline
        let code = "x <- 1\n";
        let result = format_code(FormatterBackend::Air, code).unwrap();
        assert!(result.ends_with('\n'));
    }

    #[test]
    #[ignore] // Requires Arity >=0.18.0 to be installed
    fn test_arity_format_simple_assignment() {
        let code = "x<-1+2";
        let result = format_code(FormatterBackend::Arity, code).unwrap();
        assert_eq!(result, "x <- 1 + 2");
    }

    #[test]
    #[ignore] // Requires Arity >=0.18.0 to be installed
    fn test_arity_format_preserves_trailing_newline_style() {
        // Without trailing newline
        let code = "x <- 1";
        let result = format_code(FormatterBackend::Arity, code).unwrap();
        assert!(!result.ends_with('\n'));

        // With trailing newline
        let code = "x <- 1\n";
        let result = format_code(FormatterBackend::Arity, code).unwrap();
        assert!(result.ends_with('\n'));
    }
}