arf-console 0.5.2

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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
#[cfg(not(windows))]
use std::path::PathBuf;
use std::process::Command;
#[cfg(not(windows))]
use std::process::Stdio;
#[cfg(not(windows))]
use std::thread;
#[cfg(not(windows))]
use std::time::{Duration, Instant};

#[cfg(not(windows))]
struct RLessEnvironment {
    _temp: tempfile::TempDir,
    bin_dir: PathBuf,
    home_dir: PathBuf,
    fake_r_home: PathBuf,
}

#[cfg(unix)]
struct FakeRigEnvironment {
    _temp: tempfile::TempDir,
    bin_dir: PathBuf,
    fake_r_home: PathBuf,
    rig: PathBuf,
    r: PathBuf,
}

#[cfg(unix)]
impl FakeRigEnvironment {
    fn new() -> Self {
        let temp = tempfile::tempdir().unwrap();
        let bin_dir = temp.path().join("bin");
        std::fs::create_dir(&bin_dir).unwrap();
        let fake_r_home = temp.path().join("fallback-r-home");
        std::fs::create_dir(&fake_r_home).unwrap();

        let r = bin_dir.join("R");
        write_executable(
            &r,
            r#"#!/bin/sh
if [ "$1" = "RHOME" ]; then
    printf '%s\n' "$FAKE_R_HOME"
    exit 0
fi
exit 1
"#,
        );

        let rig = bin_dir.join("rig");
        write_executable(
            &rig,
            r#"#!/bin/sh
if [ "$1" = "--version" ]; then exit 0; fi
if [ "$1" = "list" ]; then printf '%s\n' '[{"name":"4.4.2","default":true,"version":"4.4.2","aliases":["my-proj"],"path":"/fake/R/4.4.2","binary":"R"} ]'; exit 0; fi
exit 1
"#,
        );

        Self {
            _temp: temp,
            bin_dir,
            fake_r_home,
            rig,
            r,
        }
    }

    fn command(&self) -> Command {
        let mut command = isolated_command(self._temp.path());
        command
            .env("PATH", &self.bin_dir)
            .env("FAKE_R_HOME", &self.fake_r_home)
            .env_remove("R_HOME")
            .env_remove("ARF_R_HOME")
            .env_remove("ARF_R_VERSION");
        command
    }
}

/// Build a resolve command that cannot see the developer's global arf config.
fn isolated_command(temp_path: &std::path::Path) -> Command {
    let home_dir = temp_path.join("home");
    std::fs::create_dir_all(&home_dir).unwrap();
    let mut command = Command::new(env!("CARGO_BIN_EXE_arf"));
    command
        .env("HOME", home_dir)
        .env_remove("XDG_CONFIG_HOME")
        .env_remove("XDG_DATA_HOME")
        .env_remove("XDG_CACHE_HOME");
    command
}

#[cfg(unix)]
fn write_executable(path: &std::path::Path, contents: &str) {
    std::fs::write(path, contents).unwrap();
    use std::os::unix::fs::PermissionsExt;
    let mut permissions = std::fs::metadata(path).unwrap().permissions();
    permissions.set_mode(0o755);
    std::fs::set_permissions(path, permissions).unwrap();
}

#[cfg(not(windows))]
impl RLessEnvironment {
    fn new() -> Self {
        let temp = tempfile::tempdir().unwrap();
        let bin_dir = temp.path().join("bin");
        std::fs::create_dir(&bin_dir).unwrap();
        let home_dir = temp.path().join("home");
        std::fs::create_dir(&home_dir).unwrap();
        let fake_r_home = {
            let fake_r_home = temp.path().join("fake-r-home");
            let fake_r_library = arf_libr::r_library_path(&fake_r_home);
            std::fs::create_dir_all(fake_r_library.parent().unwrap()).unwrap();
            std::fs::write(fake_r_library, []).unwrap();
            fake_r_home
        };

        #[cfg(unix)]
        {
            let r_command = bin_dir.join("R");
            std::fs::write(
                &r_command,
                r#"#!/bin/sh
exit 1
"#,
            )
            .unwrap();
            use std::os::unix::fs::PermissionsExt;
            let mut permissions = std::fs::metadata(&r_command).unwrap().permissions();
            permissions.set_mode(0o755);
            std::fs::set_permissions(&r_command, permissions).unwrap();
        }

        Self {
            _temp: temp,
            bin_dir,
            home_dir,
            fake_r_home,
        }
    }

    /// Build a command that sees neither an R installation nor the developer's
    /// own configuration.
    ///
    /// Pointing `HOME` at an empty directory and clearing the XDG variables
    /// isolates the global `arf.toml`, which `dirs::config_dir()` resolves from
    /// `$XDG_CONFIG_HOME` or `$HOME` depending on the platform. Without this, a
    /// developer or CI image that configures `startup.r_source` would resolve an
    /// R installation and make these tests environment-dependent. The
    /// configuration cannot be isolated with `--config` here, because arf
    /// rejects that flag when it appears before a subcommand and this helper
    /// does not know which subcommand the caller will add.
    fn command(&self) -> Command {
        let mut command = Command::new(env!("CARGO_BIN_EXE_arf"));
        #[cfg(unix)]
        let path_entries = vec![self.bin_dir.clone()];
        #[cfg(not(unix))]
        let path_entries = vec![self.bin_dir.clone()];
        command
            .env_remove("R_HOME")
            .env_remove("ARF_R_HOME")
            .env_remove("ARF_R_VERSION")
            .env_remove("XDG_CONFIG_HOME")
            .env_remove("XDG_DATA_HOME")
            .env_remove("XDG_CACHE_HOME")
            .env("HOME", &self.home_dir)
            .env("PATH", std::env::join_paths(path_entries).unwrap());
        command
    }

    fn startup_command(&self) -> Command {
        let mut command = self.command();
        command.env("R_HOME", &self.fake_r_home);
        command
    }
}

#[test]
fn resolve_found_emits_descriptor_with_target() {
    let temp = tempfile::tempdir().unwrap();
    let output = isolated_command(temp.path())
        .args(["r", "resolve", "--r-home"])
        .arg(temp.path())
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    assert!(output.stderr.is_empty());
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["schema_version"], 1);
    assert_eq!(value["resolved"], true);
    assert_descriptor_path(&value, &value["target"]["r_home"], temp.path());
    assert!(value["target"]["r_binary"].is_null());
    assert!(value["target"]["resolved_version"].is_null());
    assert_eq!(value["selected_by"]["kind"], "r_home");
    assert_selected_by_nullable_fields_are_present(&value);
    assert!(value["selected_by"]["requested_version"].is_null());
    assert_eq!(
        value["selected_by"]["source"]["kind"],
        "command_line_argument"
    );
    assert_eq!(value["selected_by"]["source"]["name"], "--r-home");
    assert!(value["selected_by"]["source"]["path"].is_null());
    assert!(value["selected_by"]["source"]["format"].is_null());
    assert!(value["selected_by"]["source"]["key"].is_null());
    assert_descriptor_path(
        &value,
        &value["selected_by"]["requested_r_home"],
        temp.path(),
    );
    assert!(value["diagnostics"].as_array().unwrap().is_empty());
    insta::assert_snapshot!(
        "resolve_found_emits_descriptor_with_target",
        normalize_descriptor(&value)
    );
}

#[test]
fn resolve_relative_r_home_uses_one_absolute_path_representation() {
    let temp = tempfile::tempdir().unwrap();
    let r_home = temp.path().join("rh");
    std::fs::create_dir(&r_home).unwrap();

    let output = isolated_command(temp.path())
        .args(["r", "resolve", "--r-home", "rh"])
        .current_dir(temp.path())
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    let target_r_home = value["target"]["r_home"].as_str().unwrap();
    let selected_path = value["selected_by"]["requested_r_home"].as_str().unwrap();
    assert_eq!(target_r_home, selected_path);
    assert!(std::path::Path::new(target_r_home).is_absolute());
    assert_descriptor_path(&value, &value["target"]["r_home"], "rh");
    assert_descriptor_path(&value, &value["selected_by"]["requested_r_home"], "rh");
}

#[cfg(unix)]
fn write_uninstalled_project_override_fixture() -> tempfile::TempDir {
    let temp = tempfile::tempdir().unwrap();
    std::fs::write(
        temp.path().join("arf.toml"),
        r#"[experimental]
r_source_overrides = [
  { type = "toml-key", file = "rproject.toml", key = "project.r_version" },
]

[startup]
r_source = { path = "fallback-r-home" }
"#,
    )
    .unwrap();
    std::fs::create_dir(temp.path().join("fallback-r-home")).unwrap();
    // R 3.x ended at 3.6.3, so 3.99.99 can never collide with a real release.
    std::fs::write(
        temp.path().join("rproject.toml"),
        r#"[project]
r_version = "3.99.99"
"#,
    )
    .unwrap();
    temp
}

#[test]
#[cfg(unix)]
fn resolve_uninstalled_project_override_falls_back_to_startup_source() {
    let temp = write_uninstalled_project_override_fixture();
    let environment = FakeRigEnvironment::new();

    let fallback_output = environment
        .command()
        .args([
            "r",
            "resolve",
            "--config",
            "arf.toml",
            "--no-r-source-overrides",
        ])
        .current_dir(temp.path())
        .output()
        .unwrap();

    assert!(
        fallback_output.status.success(),
        "stderr: {:?}",
        fallback_output.stderr
    );
    let fallback_value: serde_json::Value =
        serde_json::from_slice(&fallback_output.stdout).unwrap();
    assert_eq!(fallback_value["resolved"], true);

    let output = environment
        .command()
        .args(["r", "resolve", "--config", "arf.toml"])
        .current_dir(temp.path())
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["resolved"], true);
    assert_eq!(
        value["target"]["r_home"],
        fallback_value["target"]["r_home"]
    );
    assert_eq!(value["selected_by"]["kind"], "default");
    assert_selected_by_nullable_fields_are_present(&value);
    assert!(value["selected_by"]["requested_r_home"].is_null());
    assert!(value["selected_by"]["requested_version"].is_null());
    assert_eq!(value["selected_by"]["source"]["kind"], "configuration_file");
    assert!(value["selected_by"]["source"]["name"].is_null());
    assert_descriptor_path(&value, &value["selected_by"]["source"]["path"], "arf.toml");
    assert_eq!(value["selected_by"]["source"]["format"], "toml");
    assert_eq!(value["selected_by"]["source"]["key"], "startup.r_source");

    let diagnostic = value["diagnostics"]
        .as_array()
        .unwrap()
        .iter()
        .find(|diagnostic| diagnostic["code"] == "r_source_override.version_not_installed")
        .expect("missing uninstalled-version override diagnostic");
    assert_eq!(diagnostic["path"], "rproject.toml");
}

#[test]
#[cfg(unix)]
fn resolve_project_file_version_request_reports_toml_source() {
    let temp = write_uninstalled_project_override_fixture();
    std::fs::write(
        temp.path().join("rproject.toml"),
        r#"[project]
r_version = "4.4.2"
"#,
    )
    .unwrap();
    let environment = FakeRigEnvironment::new();

    let output = environment
        .command()
        .args(["r", "resolve", "--config", "arf.toml"])
        .current_dir(temp.path())
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["selected_by"]["kind"], "version_request");
    assert_selected_by_nullable_fields_are_present(&value);
    assert!(value["selected_by"]["requested_r_home"].is_null());
    assert_eq!(value["selected_by"]["requested_version"], "4.4.2");
    assert_eq!(value["selected_by"]["source"]["kind"], "project_file");
    assert!(value["selected_by"]["source"]["name"].is_null());
    assert_descriptor_path(
        &value,
        &value["selected_by"]["source"]["path"],
        "rproject.toml",
    );
    assert_eq!(value["selected_by"]["source"]["format"], "toml");
    assert_eq!(value["selected_by"]["source"]["key"], "project.r_version");
    insta::assert_snapshot!(
        "resolve_project_file_version_request_reports_toml_source",
        normalize_descriptor(&value)
    );
}

#[test]
#[cfg(unix)]
fn resolve_project_file_version_request_reports_json_source() {
    let temp = write_uninstalled_project_override_fixture();
    std::fs::write(
        temp.path().join("arf.toml"),
        r#"[experimental]
r_source_overrides = [
  { type = "json-key", file = "renv.lock", key = "R.Version" },
]

[startup]
r_source = { path = "fallback-r-home" }
"#,
    )
    .unwrap();
    std::fs::write(
        temp.path().join("renv.lock"),
        r#"{"R":{"Version":"4.4.2"}}"#,
    )
    .unwrap();
    let environment = FakeRigEnvironment::new();

    let output = environment
        .command()
        .args(["r", "resolve", "--config", "arf.toml"])
        .current_dir(temp.path())
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["selected_by"]["kind"], "version_request");
    assert_selected_by_nullable_fields_are_present(&value);
    assert!(value["selected_by"]["requested_r_home"].is_null());
    assert_eq!(value["selected_by"]["requested_version"], "4.4.2");
    assert_eq!(value["selected_by"]["source"]["kind"], "project_file");
    assert!(value["selected_by"]["source"]["name"].is_null());
    assert_descriptor_path(&value, &value["selected_by"]["source"]["path"], "renv.lock");
    assert_eq!(value["selected_by"]["source"]["format"], "json");
    assert_eq!(value["selected_by"]["source"]["key"], "R.Version");
    insta::assert_snapshot!(
        "resolve_project_file_version_request_reports_json_source",
        normalize_descriptor(&value)
    );
}

#[test]
#[cfg(unix)]
fn resolve_project_file_version_request_reports_text_source() {
    let temp = tempfile::tempdir().unwrap();
    std::fs::write(
        temp.path().join("arf.toml"),
        r#"[experimental]
r_source_overrides = [{ type = "version-file", file = ".r-version" }]

[startup]
r_source = { path = "fallback-r-home" }
"#,
    )
    .unwrap();
    std::fs::create_dir(temp.path().join("fallback-r-home")).unwrap();
    std::fs::write(temp.path().join(".r-version"), "4.4.2\n").unwrap();
    let environment = FakeRigEnvironment::new();

    let output = environment
        .command()
        .args(["r", "resolve", "--config", "arf.toml"])
        .current_dir(temp.path())
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["selected_by"]["kind"], "version_request");
    assert_selected_by_nullable_fields_are_present(&value);
    assert!(value["selected_by"]["requested_r_home"].is_null());
    assert_eq!(value["selected_by"]["source"]["kind"], "project_file");
    assert!(value["selected_by"]["source"]["name"].is_null());
    assert_descriptor_path(
        &value,
        &value["selected_by"]["source"]["path"],
        ".r-version",
    );
    assert_eq!(value["selected_by"]["source"]["format"], "text");
    assert!(value["selected_by"]["source"]["key"].is_null());
    insta::assert_snapshot!(
        "resolve_project_file_version_request_reports_text_source",
        normalize_descriptor(&value)
    );
}

/// Project configuration is a hint that may fall back, while an explicit
/// user request must fail when the requested R version is not installed.
#[test]
#[cfg(unix)]
fn resolve_project_hint_and_explicit_version_have_different_outcomes() {
    let temp = write_uninstalled_project_override_fixture();
    let environment = FakeRigEnvironment::new();

    let project_hint = environment
        .command()
        .args(["r", "resolve", "--config", "arf.toml"])
        .current_dir(temp.path())
        .output()
        .unwrap();
    assert!(
        project_hint.status.success(),
        "stderr: {:?}",
        project_hint.stderr
    );
    let project_hint_value: serde_json::Value =
        serde_json::from_slice(&project_hint.stdout).unwrap();
    assert_eq!(project_hint_value["resolved"], true);
    assert_eq!(project_hint_value["selected_by"]["kind"], "default");
    assert_selected_by_nullable_fields_are_present(&project_hint_value);
    assert!(project_hint_value["selected_by"]["requested_r_home"].is_null());
    assert!(project_hint_value["selected_by"]["requested_version"].is_null());
    assert_eq!(
        project_hint_value["selected_by"]["source"]["kind"],
        "configuration_file"
    );

    let explicit_request = environment
        .command()
        .args([
            "r",
            "resolve",
            "--config",
            "arf.toml",
            "--with-r-version",
            "3.99.99",
        ])
        .current_dir(temp.path())
        .output()
        .unwrap();
    assert_structured_resolve_error(&explicit_request, "INVALID_PARAMS");
    assert_eq!(explicit_request.status.code(), Some(2));
}

#[test]
#[cfg(unix)]
fn resolve_environment_version_is_invalid_invocation() {
    let environment = FakeRigEnvironment::new();
    let output = environment
        .command()
        .args(["r", "resolve"])
        .env("ARF_R_VERSION", "3.99.99")
        .output()
        .unwrap();

    assert_structured_resolve_error(&output, "INVALID_PARAMS");
    assert_eq!(output.status.code(), Some(2));
}

#[test]
#[cfg(unix)]
fn resolve_environment_version_reports_environment_source() {
    let environment = FakeRigEnvironment::new();
    let output = environment
        .command()
        .args(["r", "resolve"])
        .env("ARF_R_VERSION", "4.4.2")
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["selected_by"]["kind"], "version_request");
    assert_selected_by_nullable_fields_are_present(&value);
    assert!(value["selected_by"]["requested_r_home"].is_null());
    assert_eq!(value["selected_by"]["requested_version"], "4.4.2");
    assert_eq!(
        value["selected_by"]["source"]["kind"],
        "environment_variable"
    );
    assert_eq!(value["selected_by"]["source"]["name"], "ARF_R_VERSION");
    insta::assert_snapshot!(
        "resolve_environment_version_reports_environment_source",
        normalize_descriptor(&value)
    );
}

#[test]
#[cfg(unix)]
fn resolve_without_config_reports_built_in_default_source() {
    let temp = tempfile::tempdir().unwrap();
    let environment = FakeRigEnvironment::new();
    let missing_config = temp.path().join("missing-arf.toml");
    let output = environment
        .command()
        .args(["r", "resolve", "--config"])
        .arg(missing_config)
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["selected_by"]["kind"], "default");
    assert_selected_by_nullable_fields_are_present(&value);
    assert!(value["selected_by"]["requested_r_home"].is_null());
    assert!(value["selected_by"]["requested_version"].is_null());
    assert_eq!(value["selected_by"]["source"]["kind"], "built_in_default");
    assert!(value["selected_by"]["source"]["name"].is_null());
    assert!(value["selected_by"]["source"]["path"].is_null());
    assert!(value["selected_by"]["source"]["format"].is_null());
    assert!(value["selected_by"]["source"]["key"].is_null());
    insta::assert_snapshot!(
        "resolve_without_config_reports_built_in_default_source",
        normalize_descriptor(&value)
    );
}

#[test]
#[cfg(not(windows))]
fn resolve_not_found_is_successful_false_descriptor() {
    let environment = RLessEnvironment::new();
    let output = environment
        .command()
        .args([
            "r",
            "resolve",
            "--no-r-auto-discovery",
            "--no-r-source-overrides",
        ])
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["resolved"], false);
    assert!(value["target"].is_null());
    assert!(value.as_object().unwrap().contains_key("provider"));
    assert!(value["provider"].is_null());
    let diagnostic = value["diagnostics"]
        .as_array()
        .unwrap()
        .iter()
        .find(|diagnostic| diagnostic["code"] == "r_discovery.failed")
        .expect("expected an r_discovery.failed diagnostic");
    // Snapshot the whole message rather than checking a substring, which still
    // passes when the message is wrapped in text describing a different
    // failure, such as a missing path or a PATH search that never ran.
    insta::assert_snapshot!(
        diagnostic["message"].as_str().unwrap(),
        @"R automatic discovery is disabled. Set R_HOME, pass --r-home, or remove --no-r-auto-discovery."
    );
    insta::assert_snapshot!(
        "resolve_not_found_is_successful_false_descriptor",
        normalize_descriptor(&value)
    );
}

#[test]
#[cfg(not(windows))]
fn resolve_explicit_r_home_still_works_with_no_r_auto_discovery() {
    let environment = RLessEnvironment::new();
    let output = environment
        .command()
        .args(["r", "resolve", "--no-r-auto-discovery", "--r-home"])
        .arg(&environment.fake_r_home)
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["resolved"], true);
    assert_descriptor_path(&value, &value["target"]["r_home"], &environment.fake_r_home);
    assert_eq!(value["provider"], "explicit_path");
    assert_eq!(value["selected_by"]["kind"], "r_home");
}

#[test]
fn resolve_broken_config_falls_back_with_diagnostic() {
    let temp = tempfile::tempdir().unwrap();
    let config = temp.path().join("broken.toml");
    std::fs::write(&config, "not valid = [toml").unwrap();
    let r_home = temp.path().join("r-home");
    std::fs::create_dir(&r_home).unwrap();

    let output = isolated_command(temp.path())
        .args(["r", "resolve", "--config"])
        .arg(&config)
        .args(["--r-home"])
        .arg(&r_home)
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    assert!(output.stderr.is_empty());
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["resolved"], true);
    assert_descriptor_path(&value, &value["target"]["r_home"], &r_home);
    assert!(
        value["diagnostics"]
            .as_array()
            .unwrap()
            .iter()
            .any(|diagnostic| diagnostic["code"] == "config.parse_failed")
    );
    insta::assert_snapshot!(
        "resolve_broken_config_falls_back_with_diagnostic",
        normalize_descriptor(&value)
    );
}

#[test]
fn resolve_environment_source_reports_environment_origin() {
    let temp = tempfile::tempdir().unwrap();
    let output = isolated_command(temp.path())
        .args(["r", "resolve"])
        .env("ARF_R_HOME", temp.path())
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["selected_by"]["kind"], "r_home");
    assert_selected_by_nullable_fields_are_present(&value);
    assert!(value["selected_by"]["requested_version"].is_null());
    assert_eq!(
        value["selected_by"]["source"]["kind"],
        "environment_variable"
    );
    assert_eq!(value["selected_by"]["source"]["name"], "ARF_R_HOME");
}

#[test]
#[cfg(unix)]
fn resolve_invalid_version_is_invalid_invocation() {
    let environment = FakeRigEnvironment::new();
    let output = environment
        .command()
        .args(["r", "resolve", "--with-r-version", "not-a-version"])
        .output()
        .unwrap();

    assert_structured_resolve_error(&output, "INVALID_PARAMS");
    assert_eq!(output.status.code(), Some(2));
}

#[test]
#[cfg(unix)]
fn resolve_valid_but_uninstalled_version_is_invalid_invocation() {
    let environment = FakeRigEnvironment::new();

    let output = environment
        .command()
        .args(["r", "resolve", "--with-r-version", "3.99.99"])
        .output()
        .unwrap();

    assert_structured_resolve_error(&output, "INVALID_PARAMS");
    assert_eq!(output.status.code(), Some(2));
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert!(
        error["error"]["message"]
            .as_str()
            .unwrap()
            .contains("3.99.99")
    );
}

#[test]
#[cfg(not(windows))]
fn resolve_version_without_rig_is_invalid_invocation() {
    let environment = RLessEnvironment::new();
    let output = environment
        .command()
        .args(["r", "resolve", "--with-r-version", "4.5.2"])
        .output()
        .unwrap();

    assert_structured_resolve_error(&output, "INVALID_PARAMS");
    assert_eq!(output.status.code(), Some(2));
}

#[test]
#[cfg(unix)]
fn resolve_rig_alias_is_accepted_before_version_spec_validation() {
    let environment = FakeRigEnvironment::new();
    let output = environment
        .command()
        .args(["r", "resolve", "--with-r-version", "my-proj"])
        .output()
        .unwrap();

    assert!(output.status.success(), "stderr: {:?}", output.stderr);
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["target"]["resolved_version"], "4.4.2");
    assert_selected_by_nullable_fields_are_present(&value);
    assert!(value["selected_by"]["requested_r_home"].is_null());
    assert_eq!(value["selected_by"]["requested_version"], "my-proj");
    assert_eq!(value["selected_by"]["kind"], "version_request");
    assert_eq!(
        value["selected_by"]["source"]["kind"],
        "command_line_argument"
    );
    assert_eq!(value["selected_by"]["source"]["name"], "--with-r-version");
    insta::assert_snapshot!(
        "resolve_rig_alias_is_accepted_before_version_spec_validation",
        normalize_descriptor(&value)
    );
}

#[test]
#[cfg(unix)]
fn resolve_malformed_rig_output_is_internal_error() {
    let environment = FakeRigEnvironment::new();
    std::fs::write(
        &environment.rig,
        r#"#!/bin/sh
if [ "$1" = "--version" ]; then exit 0; fi
if [ "$1" = "list" ]; then printf '%s\n' 'not json'; exit 0; fi
exit 1
"#,
    )
    .unwrap();

    let output = environment
        .command()
        .args(["r", "resolve", "--with-r-version", "4.4.2"])
        .output()
        .unwrap();

    assert_structured_resolve_error(&output, "INTERNAL_ERROR");
    assert_eq!(output.status.code(), Some(4));
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert!(
        error["error"]["message"]
            .as_str()
            .unwrap()
            .contains("failed to parse rig output")
    );
}

#[test]
#[cfg(unix)]
fn resolve_failing_rig_is_internal_error() {
    let environment = FakeRigEnvironment::new();
    write_executable(&environment.rig, "#!/bin/sh\nexit 1\n");

    let output = environment
        .command()
        .args(["r", "resolve", "--with-r-version", "4.4.2"])
        .output()
        .unwrap();

    assert_structured_resolve_error(&output, "INTERNAL_ERROR");
    assert_eq!(output.status.code(), Some(4));
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert!(
        error["error"]["message"]
            .as_str()
            .unwrap()
            .contains("Failed to run rig while checking whether it is available")
    );
}

#[test]
#[cfg(unix)]
fn resolve_r_binary_failure_is_internal_error() {
    let environment = FakeRigEnvironment::new();
    std::fs::write(&environment.r, "#!/bin/sh\nexit 1\n").unwrap();

    let output = environment
        .command()
        .args(["r", "resolve", "--with-r-version", "4.4.2"])
        .output()
        .unwrap();

    assert_structured_resolve_error(&output, "INTERNAL_ERROR");
    assert_eq!(output.status.code(), Some(4));
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert!(
        error["error"]["message"]
            .as_str()
            .unwrap()
            .contains("RHOME failed")
    );
}

#[test]
fn resolve_missing_r_home_returns_invalid_params_exit_code() {
    let temp = tempfile::tempdir().unwrap();
    let missing_r_home = temp.path().join("missing-r-home");
    let output = isolated_command(temp.path())
        .args(["r", "resolve", "--r-home"])
        .arg(missing_r_home)
        .output()
        .unwrap();

    assert_structured_resolve_error(&output, "INVALID_PARAMS");
    assert_eq!(output.status.code(), Some(2));
}

fn assert_structured_resolve_error(output: &std::process::Output, code: &str) {
    assert!(output.stdout.is_empty());
    let value: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    let error = value["error"].as_object().unwrap();
    assert_eq!(error["code"], code);
    assert!(error["message"].is_string());
    assert!(error["hint"].is_null());
    assert!(error["data"].is_null());
}

fn assert_selected_by_nullable_fields_are_present(value: &serde_json::Value) {
    let selected_by = value["selected_by"].as_object().unwrap();
    for field in ["requested_r_home", "requested_version"] {
        assert!(
            selected_by.contains_key(field),
            "missing selected_by.{field}"
        );
    }

    let source = selected_by["source"].as_object().unwrap();
    for field in ["name", "path", "format", "key"] {
        assert!(
            source.contains_key(field),
            "missing selected_by.source.{field}"
        );
    }
}

fn normalize_descriptor(value: &serde_json::Value) -> String {
    let mut normalized = value.clone();
    let descriptor = normalized.as_object_mut().unwrap();

    replace_non_null(descriptor.get_mut("cwd"), "<cwd>");
    if let Some(resolver) = descriptor
        .get_mut("resolver")
        .and_then(|resolver| resolver.as_object_mut())
    {
        replace_non_null(resolver.get_mut("version"), "<arf-version>");
    }

    if let Some(target) = descriptor
        .get_mut("target")
        .and_then(|target| target.as_object_mut())
    {
        replace_non_null(target.get_mut("r_home"), "<r-home>");
        replace_non_null(target.get_mut("r_binary"), "<r-binary>");
        // The fake rig fixture used by every snapshot with a resolved version
        // always reports 4.4.2, so retaining that value pins the fixture's
        // deterministic version selection.
    }

    if let Some(selected_by) = descriptor
        .get_mut("selected_by")
        .and_then(|selected_by| selected_by.as_object_mut())
    {
        replace_non_null(
            selected_by.get_mut("requested_r_home"),
            "<requested-r-home>",
        );
        if let Some(source) = selected_by
            .get_mut("source")
            .and_then(|source| source.as_object_mut())
        {
            replace_non_null(source.get_mut("path"), "<source-path>");
        }
    }

    if let Some(diagnostics) = descriptor
        .get_mut("diagnostics")
        .and_then(|diagnostics| diagnostics.as_array_mut())
    {
        for diagnostic in diagnostics {
            if let Some(diagnostic) = diagnostic.as_object_mut() {
                // A message that names a path names the diagnostic's own path,
                // so substitute that exact string. Recognizing paths by their
                // syntax instead cannot be made reliable: a pattern that ends a
                // Windows path at the wrong character produces a snapshot that
                // differs from the one committed on Unix, and drive letters,
                // `~`, UNC prefixes and spaces in paths each break it
                // differently.
                let path = diagnostic
                    .get("path")
                    .and_then(|path| path.as_str())
                    .map(str::to_owned);
                let message = diagnostic
                    .get("message")
                    .and_then(|message| message.as_str())
                    .map(str::to_owned);
                if let (Some(path), Some(message)) = (path.as_deref(), message) {
                    diagnostic.insert(
                        "message".to_owned(),
                        serde_json::Value::String(message.replace(path, "<path>")),
                    );
                }
                replace_non_null(diagnostic.get_mut("path"), "<diagnostic-path>");
            }
        }
    }

    serde_json::to_string_pretty(&normalized).unwrap()
}

/// The descriptor snapshots are shared across platforms, so normalizing a
/// diagnostic must not depend on how the platform spells a path. Windows CI is
/// the only place a regression here would surface, so exercise the shapes it
/// produces directly.
#[test]
fn normalize_descriptor_handles_paths_from_any_platform() {
    for path in [
        r"/tmp/.tmpABC/broken.toml",
        r"C:\Users\runner\AppData\Local\Temp\.tmpABC\broken.toml",
        r"\\server\share\broken.toml",
        r"C:\Program Files\arf config\broken.toml",
    ] {
        let value = serde_json::json!({
            "diagnostics": [{
                "code": "config.parse_failed",
                "severity": "warning",
                "message": format!("Failed to load config from {path}: TOML parse error"),
                "path": path,
            }],
        });
        let normalized = normalize_descriptor(&value);
        assert!(
            normalized.contains(r"<path>: TOML parse error"),
            "path {path} normalized to: {normalized}"
        );
        assert!(!normalized.contains("broken.toml"), "leaked {path}");
    }

    let absolute_path = r"C:\Users\runner\AppData\Local\Temp\.tmpABC\broken.toml";
    let home_relative_path = r"~\AppData\Local\Temp\.tmpABC\broken.toml";
    let value = serde_json::json!({
        "diagnostics": [{
            "code": "config.parse_failed",
            "severity": "warning",
            "message": format!("Failed to load config from {home_relative_path}: TOML parse error"),
            "path": absolute_path,
        }],
    });
    // Normalization can only substitute a spelling it is given, so it depends on
    // the producer using the same one in both fields. Pin that dependency: when
    // they disagree, the message keeps a path the snapshot cannot absorb, and the
    // snapshot turns platform-specific. This is why a diagnostic is built with
    // the raw path and masked only when rendered for a person. Windows is where
    // divergence would show, because its temporary directories sit under the
    // user profile and Unix ones do not.
    let normalized: serde_json::Value =
        serde_json::from_str(&normalize_descriptor(&value)).unwrap();
    assert_eq!(
        normalized["diagnostics"][0]["message"],
        serde_json::Value::String(format!(
            "Failed to load config from {home_relative_path}: TOML parse error"
        )),
        "expected the mismatched spelling to survive, so this test keeps \
         documenting why the two fields must agree"
    );
}

fn replace_non_null(value: Option<&mut serde_json::Value>, placeholder: &str) {
    if let Some(value) = value
        && !value.is_null()
    {
        *value = serde_json::Value::String(placeholder.to_owned());
    }
}

/// Assert a descriptor path using its `cwd` for relative expected paths.
///
/// On macOS, `getcwd` resolves the `/var` symlink to `/private/var`, while
/// paths returned by `tempfile` may still contain `/var`. Cwd-derived paths
/// must therefore be compared against the descriptor's `cwd`, not directly
/// against a path returned by `tempfile`.
fn assert_descriptor_path(
    value: &serde_json::Value,
    actual: &serde_json::Value,
    expected_path: impl AsRef<std::path::Path>,
) {
    let cwd = std::path::Path::new(value["cwd"].as_str().unwrap());
    let expected_path = expected_path.as_ref();
    let expected = if expected_path.is_absolute() {
        expected_path.to_owned()
    } else {
        cwd.join(expected_path)
    };
    assert_eq!(
        actual,
        &serde_json::Value::String(expected.display().to_string())
    );
}

/// This covers initialization-failure fallback, not PATH discovery.
#[test]
#[cfg(not(windows))]
fn startup_survives_without_r_on_path() {
    let environment = RLessEnvironment::new();
    let mut child = environment
        .startup_command()
        .args(["--no-banner", "--no-history"])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    let timeout = Duration::from_secs(10);
    let start = Instant::now();
    loop {
        if child.try_wait().unwrap().is_some() {
            break;
        }
        if start.elapsed() >= timeout {
            let _ = child.kill();
            let output = child.wait_with_output().unwrap();
            panic!(
                "arf did not exit within {timeout:?}; stderr={}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
        thread::sleep(Duration::from_millis(50));
    }

    let output = child.wait_with_output().unwrap();

    assert!(
        output.status.success(),
        "arf should start and exit cleanly without a usable R library: stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(String::from_utf8_lossy(&output.stderr).contains("R evaluation will not be available"));
}