eclipse-cli 0.13.4

Command-line interface for eclipse
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
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
//! The `release` channel of `eclipse upgrade`: fetch a tag's tarball, prove it, swap it in.
//!
//! What makes this safe is not where the bytes came from, it is three checks in order. The
//! SHA256 must equal the one the same release published; the tarball must unpack to exactly the
//! two binaries; and the unpacked `eclipse --version` must name the tag that was just
//! downloaded. A mirror that lies about a version has to also publish a matching checksum *and*
//! ship a binary that reports that version — at which point it is a fork, not an accident.
//!
//! Nothing is replaced until all three pass. The old binaries are kept beside the new ones as
//! `<name>.old` (renaming one back is the rollback), the swap is a rename over a staged copy so
//! there is no moment with no binary, and the marker is rewritten last.
//!
//! A swap is three renames over three binaries, so it is *not* atomic across them: a failure on the
//! second leaves `eclipse` new and `eclipse-web` old. That is why the swap puts the binaries it has
//! already replaced back before it returns — and why a rollback that itself fails names the binary
//! still carrying the new one rather than pretending the install is whole.
//!
//! The marker is the commit point, so it is written last and the swap waits for it: a record that
//! cannot be written takes the new binaries back with it. Three new binaries beside a marker naming
//! the old version is the one state `upgrade` cannot leave on its own — it reads the marker, says
//! "already up to date", and never offers that release again (`#599`).
//!
//! The network is asked from one short-lived runtime on its own thread. `eclipse upgrade` is a
//! batch command that starts no other work, and this keeps [`run`] — and every test of it —
//! synchronous.

use crate::upgrade::{no_run_in_progress, Cmd, Opts, Runner, Setup, Term, Verdict};
use anyhow::{anyhow, bail, Context, Result};
use eclipse_core::config::UpdateConfig;
use eclipse_core::http;
use eclipse_core::update::{self, Channel, InstallMarker, Release, Version};
use std::io::IsTerminal;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Two static binaries do not approach this. A download that answers with more is not a release.
const MAX_TARBALL_BYTES: u64 = 128 * 1024 * 1024;

/// `SHA256SUMS` is a handful of lines.
const MAX_SUMS_BYTES: u64 = 64 * 1024;

/// One asset over a slow link, not a notice.
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);

const BINARIES: [&str; 3] = ["eclipse", "eclipse-web", "eclipse-gateway"];

/// Run `eclipse upgrade` for an install that came from a release tarball.
pub fn run(
    opts: &Opts,
    setup: &Setup,
    marker: &InstallMarker,
    runner: &dyn Runner,
    term: &mut Term,
) -> Result<Verdict> {
    let bin_dir = marker.prefix.join("bin");
    let binary = bin_dir.join("eclipse");
    if !binary.is_file() {
        bail!(
            "{} says eclipse was installed under {}, but {} does not exist. Nothing was \
             changed, and nothing will be installed anywhere new: if the install was moved or \
             removed, install from the release tarball again to record it",
            setup.marker.display(),
            marker.prefix.display(),
            binary.display()
        );
    }
    if !opts.check {
        no_run_in_progress(setup)?;
    }
    let Some(installed) = marker.version.as_deref().and_then(Version::parse) else {
        bail!(
            "{} does not say which version is installed, so there is nothing to compare a newer \
             tag with. Re-run install.sh from the tarball you installed (that is what records \
             it); nothing was changed",
            setup.marker.display()
        );
    };

    let asked = setup
        .update
        .releases
        .as_deref()
        .unwrap_or(update::DEFAULT_RELEASES_URL);
    let latest = fetch(asked, &setup.update).map_err(|e| {
        anyhow!("could not ask {asked} for the newest release: {e}. Nothing was changed")
    })?;

    if latest.version <= installed {
        writeln!(
            term.out,
            "{} {installed} on the {} release",
            term.style.green("already up to date:"),
            latest.tag
        )?;
        // Same reason as the source channel: nothing to install does not mean nothing to do. A
        // machine that took its binaries from `install.sh --upgrade` has the new build and the old
        // file, and `eclipse upgrade` is what a person runs to catch up. `--check` writes nothing —
        // and neither does `--dry-run`, which returned from its own branch further down before this
        // one existed and must not have a migration run behind its back (`#601`).
        if !opts.check && !opts.dry_run {
            crate::upgrade::migrate_config(term, &marker.prefix)?;
        }
        return Ok(Verdict::Current);
    }

    writeln!(
        term.out,
        "{installed} installed; {} is the newest release",
        latest.tag
    )?;
    if opts.check {
        return Ok(Verdict::Behind);
    }
    if opts.dry_run {
        writeln!(term.out, "dry run: nothing below is fetched or run.")?;
        writeln!(term.out, "  GET {}", latest.tarball_url)?;
        writeln!(term.out, "  GET {}", latest.sums_url)?;
        writeln!(
            term.out,
            "  sha256sum {} (must equal the digest in SHA256SUMS)",
            latest.tarball_name
        )?;
        writeln!(
            term.out,
            "  tar -xzf {} (must hold eclipse, eclipse-web and eclipse-gateway)",
            latest.tarball_name
        )?;
        writeln!(
            term.out,
            "  <unpacked>/eclipse --version (must say `eclipse {}`)",
            latest.version
        )?;
        for name in BINARIES {
            writeln!(
                term.out,
                "  install <unpacked>/{name} -> {} (the old one kept as {name}.old)",
                bin_dir.join(name).display()
            )?;
        }
        // The plan names the restart too: the binaries on disk are not the ones a running
        // gateway is executing, which is the whole reason an upgrade needs a second half.
        if !opts.no_restart && crate::gateway_cli::installed_unit().is_some() {
            writeln!(
                term.out,
                "  systemctl --user restart {} (it is serving the old build until it does)",
                crate::gateway_cli::SERVICE_NAME
            )?;
        }
        writeln!(
            term.out,
            "Config and sessions are not touched: an upgrade replaces the binaries and the install record."
        )?;
        return Ok(Verdict::Planned);
    }

    // A major version is the one case where "newer" is not the same as "the one you want". Ask,
    // and refuse rather than assume when there is no one to ask.
    if latest.version.major != installed.major {
        major_gate(term, installed, &latest)?;
    }

    let state = setup
        .marker
        .parent()
        .context("the install record has no directory")?;
    // The pid alone is not unique enough: every test in one process shares it, and two runs
    // that picked the same directory would delete each other's downloads mid-flight.
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let work = state.join(format!("upgrade-{}-{stamp}", std::process::id()));
    std::fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;

    let done = perform(runner, &latest, &bin_dir, &work, setup, marker, term);
    // The binaries are new; a process that is already running is not. Do the restart here rather
    // than printing a reminder: this is the reason the upgrade was asked for.
    if matches!(done, Ok(Verdict::Upgraded)) {
        // A restart that cannot be run says so and stops nothing: the binaries are in place and
        // the marker is written, so `?` here reported a failed upgrade for a completed one and
        // skipped the migration behind it, leaving the config a shape behind while the next run
        // said "up to date" (`#404`).
        if let Err(e) = crate::upgrade::after_the_binaries(term, runner, opts) {
            writeln!(
                term.out,
                "{}",
                term.style.dim(&format!(
                    "the gateway was not restarted ({e}); `eclipse gateway restart` when you are ready"
                ))
            )?;
        }
        // The binaries just changed, so the file may be a shape behind: the same step the source
        // channel takes after installing, through the binary that was just put in place.
        crate::upgrade::migrate_config(term, &marker.prefix)?;
    }
    // The unpacked tree is scaffolding either way; the tarball is the only trace worth keeping,
    // and it is not worth keeping.
    let _ = std::fs::remove_dir_all(&work);
    done
}

/// Everything that touches the disk, so the temp tree is removed on both outcomes.
fn perform(
    runner: &dyn Runner,
    latest: &Release,
    bin_dir: &Path,
    work: &Path,
    setup: &Setup,
    marker: &InstallMarker,
    term: &mut Term,
) -> Result<Verdict> {
    writeln!(term.out, "downloading {} ...", latest.tarball_name)?;
    term.out.flush()?;
    let (tarball, sums) = download(latest, work)?;

    let expected = expected_digest(&sums, &latest.tarball_name)?;
    let actual = sha256_of(runner, &tarball)?;
    if actual != expected {
        bail!(
            "the downloaded {} has SHA256 {actual}, and {} says it should be {expected}. The \
             download is corrupt or not what the release published; it was not installed, \
             nothing was replaced, and the download was discarded",
            latest.tarball_name,
            update::SUMS_NAME
        );
    }

    let unpacked = unpack(runner, &tarball, work)?;
    the_binary_says_its_version(runner, latest, &unpacked)?;
    // Beside the binaries' `.old` copies, so the rollback recipe restores the versions *and* the
    // record that says which version this is. Renaming a binary back while the marker keeps the new
    // version produced an install that `upgrade` reported as "already up to date" for ever.
    let kept_marker = keep_the_marker(setup)?;
    let swapped = swap(bin_dir, &unpacked)?;
    // The marker is the commit point, so a record that cannot be written takes the binaries back
    // with it: new binaries beside a marker naming the old version is the install `upgrade` calls
    // up to date for ever, and it is the one failure the next run cannot see (`#599`).
    if let Err(e) = write_marker(setup, marker, latest) {
        return Err(roll_back(bin_dir, &swapped, e));
    }

    writeln!(
        term.out,
        "{} {} \u{2192} {} ({}).",
        term.style.green("upgraded:"),
        marker.version.as_deref().unwrap_or("?"),
        latest.version,
        latest.tag
    )?;
    // The binaries are new; a process that is already running is not. The restart belongs to this
    // half of the upgrade, not to a reminder printed at the end of it.
    // (It is called by the caller once `perform` has returned `Upgraded`.)
    // Both halves of a rollback, in one place: the binaries carry their `.old` beside them and the
    // record is kept as `install.json.old`. Restoring only the binaries left the marker naming the
    // new version, and the next `upgrade` called that install up to date.
    writeln!(
        term.out,
        "{} rename each {}/<name>.old back over <name>, then restore {} from {} — without the \
         record the next upgrade thinks it is already on {}.",
        term.style.dim("to roll back:"),
        bin_dir.display(),
        setup.marker.display(),
        kept_marker.display(),
        latest.version
    )?;
    Ok(Verdict::Upgraded)
}

/// Ask the releases question. The runtime is short-lived and lives on its own thread so this
/// module stays synchronous inside an `async fn main` that has its own runtime.
fn fetch(asked: &str, cfg: &UpdateConfig) -> std::result::Result<Release, String> {
    let cfg = cfg.clone();
    let result = std::thread::scope(|scope| {
        scope
            .spawn(move || {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .map_err(|e| e.to_string())?;
                rt.block_on(update::fetch_release(&cfg))
            })
            .join()
    });
    match result {
        Ok(r) => r,
        Err(_) => Err(format!("the request to {asked} could not be run")),
    }
}

/// Fetch the tarball and its digests into `work`. Both, or neither is used: a tarball with no
/// `SHA256SUMS` cannot be checked and is not installed.
fn download(latest: &Release, work: &Path) -> Result<(PathBuf, PathBuf)> {
    let tarball = work.join(&latest.tarball_name);
    let sums = work.join(update::SUMS_NAME);
    let (want_tar, want_sums) = (tarball.clone(), sums.clone());
    let (tar_url, sums_url) = (latest.tarball_url.clone(), latest.sums_url.clone());
    let result = std::thread::scope(|scope| {
        scope
            .spawn(move || {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .map_err(|e| e.to_string())?;
                rt.block_on(async move {
                    http::download(&tar_url, DOWNLOAD_TIMEOUT, MAX_TARBALL_BYTES, &want_tar)
                        .await?;
                    http::download(&sums_url, DOWNLOAD_TIMEOUT, MAX_SUMS_BYTES, &want_sums).await?;
                    Ok::<(), String>(())
                })
            })
            .join()
    });
    match result {
        Ok(Ok(())) => Ok((tarball, sums)),
        Ok(Err(e)) => {
            let _ = std::fs::remove_file(&tarball);
            let _ = std::fs::remove_file(&sums);
            bail!(
                "could not download {}: {e}. Nothing was replaced",
                latest.tarball_name
            )
        }
        Err(_) => {
            let _ = std::fs::remove_file(&tarball);
            let _ = std::fs::remove_file(&sums);
            bail!(
                "could not download {}: the download could not be run. Nothing was replaced",
                latest.tarball_name
            )
        }
    }
}

/// The digest `SHA256SUMS` gives for `name`. Anything unparsable is a refusal, never a skip:
/// a checksum file this cannot read is the same as no checksum file.
fn expected_digest(sums: &Path, name: &str) -> Result<String> {
    let text =
        std::fs::read_to_string(sums).with_context(|| format!("reading {}", sums.display()))?;
    for line in text.lines() {
        let mut parts = line.split_whitespace();
        let (Some(digest), Some(file)) = (parts.next(), parts.next()) else {
            continue;
        };
        // `sha256sum` writes "hex  name"; some tools mark binary mode with "hex *name".
        if file.trim_start_matches('*') != name {
            continue;
        }
        if digest.len() == 64 && digest.bytes().all(|b| b.is_ascii_hexdigit()) {
            return Ok(digest.to_ascii_lowercase());
        }
    }
    bail!(
        "{} names no SHA256 for {name}, so the download cannot be checked. Nothing was \
         replaced",
        sums.display()
    )
}

/// `sha256sum`. In-process digest code would be one more thing to get wrong; coreutils has been
/// right for decades, and a missing one is a sentence rather than a silent skip.
fn sha256_of(runner: &dyn Runner, path: &Path) -> Result<String> {
    let cmd = Cmd {
        program: "sha256sum".into(),
        args: vec![path.display().to_string()],
        dir: None,
        stream: false,
        no_prompt: false,
    };
    let out = runner.run(&cmd).map_err(|e| {
        anyhow!(
            "could not run `{}`: {e}. An upgrade of a release install needs sha256sum \
             (coreutils) to verify the download",
            cmd.display()
        )
    })?;
    if !out.success {
        bail!("`{}` failed: {}", cmd.display(), out.stderr.trim());
    }
    let digest = out
        .stdout
        .split_whitespace()
        .next()
        .unwrap_or("")
        .to_ascii_lowercase();
    if digest.len() != 64 || !digest.bytes().all(|b| b.is_ascii_hexdigit()) {
        bail!(
            "`{}` printed something that is not a SHA256: {:?}",
            cmd.display(),
            out.stdout.trim()
        );
    }
    Ok(digest)
}

/// `tar -xzf` under `into`, then the single directory a release tarball carries.
fn unpack(runner: &dyn Runner, tarball: &Path, into: &Path) -> Result<PathBuf> {
    let cmd = Cmd {
        program: "tar".into(),
        args: vec![
            // The archive's own uid/gid and modes are not the installing user's business: a
            // release tarball built on a runner that ran as root would otherwise try to reproduce
            // that, and `tar` warns (or, as root, obeys).
            "--no-same-owner".into(),
            "--no-same-permissions".into(),
            "-xzf".into(),
            tarball.display().to_string(),
            "-C".into(),
            into.display().to_string(),
        ],
        dir: None,
        stream: false,
        no_prompt: false,
    };
    let out = runner.run(&cmd).map_err(|e| {
        anyhow!(
            "could not run `{}`: {e}. An upgrade of a release install needs tar.",
            cmd.display()
        )
    })?;
    if !out.success {
        bail!(
            "`{}` failed: {}. Nothing was replaced",
            cmd.display(),
            out.stderr.trim()
        );
    }
    let dirs: Vec<PathBuf> = std::fs::read_dir(into)
        .with_context(|| format!("reading {}", into.display()))?
        .flatten()
        .map(|e| e.path())
        // `file_type()` rather than `is_dir()`: the latter follows a symlink, and the one
        // directory this tarball carries must be a directory, not a link to somewhere else.
        .filter(|p| {
            std::fs::symlink_metadata(p)
                .map(|m| m.file_type().is_dir())
                .unwrap_or(false)
        })
        .collect();
    match dirs.as_slice() {
        [one] => Ok(one.clone()),
        _ => bail!(
            "the tarball did not unpack to one directory ({} found). Nothing was replaced",
            dirs.len()
        ),
    }
}

/// The unpacked binary has to name the version the release claims. A tarball for another
/// platform, or a truncated one, is caught here rather than after the swap.
fn the_binary_says_its_version(runner: &dyn Runner, latest: &Release, dir: &Path) -> Result<()> {
    let binary = dir.join("eclipse");
    let missing: Vec<&str> = BINARIES
        .iter()
        .copied()
        .filter(|name| !dir.join(name).is_file())
        .collect();
    if !missing.is_empty() {
        // `#412`: this used to name two of the three binaries it checks, so a tarball missing only
        // `eclipse-gateway` was described as though the other two were wrong — at the one moment
        // when nothing has been replaced and the message is all the reader has.
        bail!(
            "the tarball for {} has no {} at its top level. Nothing was replaced",
            latest.tag,
            missing.join(" or ")
        );
    }
    let cmd = Cmd {
        program: binary.display().to_string(),
        args: vec!["--version".into()],
        dir: None,
        stream: false,
        no_prompt: false,
    };
    let out = runner
        .run(&cmd)
        .map_err(|e| anyhow!("could not run `{}`: {e}", cmd.display()))?;
    let said = out.stdout.trim();
    let want = format!("eclipse {}", latest.version);
    if !out.success || said != want {
        bail!(
            "the tarball for {} unpacks to a binary that says {said:?}, not {want:?}. That is \
             not the release it claims to be; nothing was replaced",
            latest.tag
        );
    }
    Ok(())
}

/// One binary a swap replaced.
#[derive(Debug)]
struct Moved {
    name: &'static str,
    /// Whether the install had this binary before the swap. A target the swap introduced has
    /// nothing to restore, so undoing it is removing it — leaving it behind is a mixed install
    /// with an extra binary, which is the state this file exists to keep out of (`#599`).
    existed: bool,
}

/// What a swap changed, so a failure after it can undo exactly that and nothing else.
#[derive(Debug, Default)]
struct Swap {
    /// Every target the swap replaced, in the order it did so.
    moved: Vec<Moved>,
}

/// Stage every binary first, then replace them: a staging copy that fails leaves the install
/// untouched, and each replacement is a rename over the old file, so nothing ever runs without a
/// binary.
///
/// Replacing is the part that can stop half-way. `stage_and_swap` puts back what it already swapped
/// before returning an error, so the only thing left to clean here is the staging copies.
fn swap(bin_dir: &Path, from: &Path) -> Result<Swap> {
    let result = stage_and_swap(bin_dir, from);
    if result.is_err() {
        // Staging copies are junk whatever happened: either they were never renamed over anything,
        // or they were and the target holds the same bytes now. They are not the rollback.
        for name in BINARIES {
            let _ = std::fs::remove_file(bin_dir.join(format!(".{name}.new")));
        }
    }
    result
}

fn stage_and_swap(bin_dir: &Path, from: &Path) -> Result<Swap> {
    let mut staged = Vec::new();
    for name in BINARIES {
        let source = from.join(name);
        let new = bin_dir.join(format!(".{name}.new"));
        std::fs::copy(&source, &new)
            .with_context(|| format!("staging {} from {}", new.display(), source.display()))?;
        std::fs::set_permissions(&new, std::fs::Permissions::from_mode(0o755))
            .with_context(|| format!("making {} executable", new.display()))?;
        staged.push((name, new));
    }
    // Every `.old` before the first rename, not one per target as it is reached. A backup that
    // cannot be kept is then a refusal while the install is still whole, instead of a swap already
    // under way with nothing to put back; and `existed` below is a fact about the install rather
    // than about a `.old` an earlier upgrade happened to leave lying there (`#599`).
    let mut plan = Vec::new();
    for (name, new) in staged {
        let target = bin_dir.join(name);
        let existed = target.is_file();
        if existed {
            let old = bin_dir.join(format!("{name}.old"));
            std::fs::copy(&target, &old).with_context(|| {
                format!(
                    "keeping {} as {}; nothing was replaced",
                    target.display(),
                    old.display()
                )
            })?;
        }
        plan.push((name, new, existed));
    }
    let mut swap = Swap::default();
    for (name, new, existed) in plan {
        let target = bin_dir.join(name);
        if let Err(e) = std::fs::rename(&new, &target) {
            return Err(roll_back(
                bin_dir,
                &swap,
                anyhow!("replacing {}: {e}", target.display()),
            ));
        }
        swap.moved.push(Moved { name, existed });
    }
    Ok(swap)
}

/// Put the install back the way the swap found it, and report the failure that caused it.
///
/// Two shapes of undo, because a swap changes two things: a target that was there is restored from
/// its `.old`, and a target the swap introduced is removed — it was not in this install before, and
/// leaving it is the mixed set this file exists to avoid. Without this a failure on the third
/// binary left `eclipse` and `eclipse-web` new and `eclipse-gateway` old — a set that cannot be
/// upgraded out of, because the marker still named the old version. A restore that fails is named:
/// an install that is genuinely mixed must say which binary it is, not return a clean-looking error.
fn roll_back(bin_dir: &Path, swapped: &Swap, cause: anyhow::Error) -> anyhow::Error {
    let mut stuck = Vec::new();
    for moved in swapped.moved.iter().rev() {
        let target = bin_dir.join(moved.name);
        if !moved.existed {
            if let Err(e) = std::fs::remove_file(&target) {
                stuck.push(format!("{} ({e})", moved.name));
            }
            continue;
        }
        let old = bin_dir.join(format!("{}.old", moved.name));
        if !old.is_file() {
            // It was there, and the copy that would put it back is not: say so rather than skip it
            // and report the install whole.
            stuck.push(format!("{} ({} is missing)", moved.name, old.display()));
            continue;
        }
        if let Err(e) = std::fs::rename(&old, &target) {
            stuck.push(format!("{} ({e})", moved.name));
        }
    }
    if stuck.is_empty() {
        cause.context("the swap was undone; the install still runs what it ran before")
    } else {
        cause.context(format!(
            "the swap could not be undone for {}: that binary is the new one and this install is \
             mixed — reinstall from a tarball by hand",
            stuck.join(", ")
        ))
    }
}

/// Rewrite the install record, atomically and last: an upgrade that crashed before this would
/// still be reported as the version it replaced.
/// Keep the current install record as `install.json.old` before it is rewritten.
///
/// The binaries' rollback keeps `<name>.old` beside each target, and this is the same idea for the
/// marker: renaming a binary back without it leaves an install whose record names the version it no
/// longer runs, and `upgrade` refuses to offer that version again.
fn keep_the_marker(setup: &Setup) -> Result<PathBuf> {
    let kept = setup.marker.with_extension("json.old");
    std::fs::copy(&setup.marker, &kept).with_context(|| {
        format!(
            "keeping {} as {}; nothing was replaced",
            setup.marker.display(),
            kept.display()
        )
    })?;
    Ok(kept)
}

fn write_marker(setup: &Setup, old: &InstallMarker, latest: &Release) -> Result<()> {
    let marker = InstallMarker {
        channel: Channel::Release,
        prefix: old.prefix.clone(),
        workspace: None,
        commit: None,
        installed_at: update::rfc3339_utc(eclipse_core::session::now_ms()),
        build: old.build.clone(),
        version: Some(latest.version.to_string()),
    };
    let text =
        serde_json::to_string_pretty(&marker).context("writing the install record as JSON")? + "\n";
    let tmp = setup
        .marker
        .with_extension(format!("json.{}.tmp", std::process::id()));
    std::fs::write(&tmp, text).with_context(|| format!("writing {}", tmp.display()))?;
    std::fs::rename(&tmp, &setup.marker)
        .inspect_err(|_| {
            // A record that never became the marker is not one: leaving `install.json.<pid>.tmp`
            // beside it invites the next reader to take a half-written file for the install.
            let _ = std::fs::remove_file(&tmp);
        })
        .with_context(|| format!("replacing {}", setup.marker.display()))?;
    Ok(())
}

/// A major jump says what it is and asks; refused rather than assumed when nobody can answer.
fn major_gate(term: &mut Term, installed: Version, latest: &Release) -> Result<()> {
    writeln!(
        term.out,
        "{} {installed} to {} crosses a major version, and a major release may change \
         behaviour or configuration. Nothing has been replaced yet.",
        term.style.yellow("major version:"),
        latest.version
    )?;
    match &latest.page {
        Some(page) => writeln!(term.out, "  what changed: {page}")?,
        None => writeln!(term.out, "  the release is {}", latest.tag)?,
    }
    term.out.flush()?;
    if !std::io::stdin().is_terminal() {
        bail!(
            "{} crosses a major version and this run has no terminal to ask in. Run `eclipse \
             upgrade` from an interactive shell to confirm it. Nothing was changed",
            latest.tag
        );
    }
    let ok = crate::setup::confirm(
        &format!("Upgrade to {} across a major version?", latest.tag),
        false,
    )?
    .unwrap_or(false);
    if !ok {
        bail!("nothing was changed: {} was not confirmed", latest.tag);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ui::Style;
    use crate::upgrade::SystemRunner;
    use std::io::{Read, Write};
    use std::sync::{Arc, Mutex};

    fn chmod_x(path: &Path) {
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    /// A tarball built here, shaped like the release workflow's: one directory holding the two
    /// binaries, each a stub that says what version it is. Named exactly as the asset the JSON
    /// advertises, because the download path is the name.
    fn build_tarball(dir: &Path, name: &str, says: &str) -> PathBuf {
        let staging = dir.join("staging");
        let inside = staging.join(name);
        std::fs::create_dir_all(&inside).unwrap();
        for (file, body) in [
            // Records how it was called: the upgrade runs `config migrate` through the binary it
            // just installed, so "was it called, and with what" is the only observable.
            (
                "eclipse",
                format!("#!/bin/sh\necho \"$@\" >> \"${{0%/*}}/calls\"\necho \"eclipse {says}\"\n"),
            ),
            ("eclipse-web", "#!/bin/sh\nexit 0\n".to_string()),
            ("eclipse-gateway", "#!/bin/sh\nexit 0\n".to_string()),
        ] {
            let path = inside.join(file);
            std::fs::write(&path, body).unwrap();
            chmod_x(&path);
        }
        std::fs::write(inside.join("VERSION"), format!("{says}\n")).unwrap();
        let tarball = dir.join(format!("{name}.tar.gz"));
        let out = std::process::Command::new("tar")
            .current_dir(&staging)
            .args(["-czf", tarball.to_str().unwrap(), name])
            .output()
            .unwrap();
        assert!(out.status.success(), "{out:?}");
        tarball
    }

    fn digest(path: &Path) -> String {
        let out = std::process::Command::new("sha256sum")
            .arg(path)
            .output()
            .unwrap();
        assert!(out.status.success());
        String::from_utf8_lossy(&out.stdout)
            .split_whitespace()
            .next()
            .unwrap()
            .to_string()
    }

    fn release_json(port: u16, tag: &str, name: &str) -> Vec<u8> {
        format!(
            r#"{{"tag_name":"{tag}","html_url":"http://127.0.0.1:{port}/page",
                 "assets":[
                   {{"name":"{name}.tar.gz","browser_download_url":"http://127.0.0.1:{port}/dl/{name}.tar.gz"}},
                   {{"name":"SHA256SUMS","browser_download_url":"http://127.0.0.1:{port}/dl/SHA256SUMS"}}
                 ]}}"#
        )
        .into_bytes()
    }

    /// One loopback server: `/latest` answers the releases question, `/dl/<name>` serves a file
    /// out of `dir`, and every path asked for is recorded.
    fn serve(
        dir: PathBuf,
        tag: &'static str,
        name: &'static str,
    ) -> (String, Arc<Mutex<Vec<String>>>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let hits = Arc::new(Mutex::new(Vec::new()));
        let counted = hits.clone();
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut s) = stream else { break };
                let mut buf = [0u8; 4096];
                let n = s.read(&mut buf).unwrap_or(0);
                let request = String::from_utf8_lossy(&buf[..n]).to_string();
                let path = request.split_whitespace().nth(1).unwrap_or("/").to_string();
                counted.lock().unwrap().push(path.clone());
                let (status, body): (&str, Vec<u8>) = if path == "/latest" {
                    ("200 OK", release_json(port, tag, name))
                } else if let Some(file) = path.strip_prefix("/dl/") {
                    match std::fs::read(dir.join(file)) {
                        Ok(bytes) => ("200 OK", bytes),
                        Err(_) => ("404 Not Found", b"no such asset".to_vec()),
                    }
                } else {
                    ("404 Not Found", b"nothing here".to_vec())
                };
                let head = format!(
                    "HTTP/1.1 {status}\r\ncontent-length: {}\r\ncontent-type: application/octet-stream\r\nconnection: close\r\n\r\n",
                    body.len()
                );
                let _ = s.write_all(head.as_bytes());
                let _ = s.write_all(&body);
            }
        });
        (format!("http://127.0.0.1:{port}/latest"), hits)
    }

    struct Install {
        _root: tempfile::TempDir,
        /// One at a time, like the source-channel fixtures: these tests start real processes.
        _serial: std::sync::MutexGuard<'static, ()>,
        prefix: PathBuf,
        marker: PathBuf,
        state: PathBuf,
        url: String,
        hits: Arc<Mutex<Vec<String>>>,
    }

    impl Install {
        /// An install of `installed` with a release served at `tag`; `says` is what the tarball's
        /// binary reports, which is the tag unless a test is lying.
        fn new(installed: &str, tag: &'static str, says: &str) -> Install {
            Self::with_digest_of(installed, tag, says, None)
        }

        /// The same, with `SHA256SUMS` naming a digest that is not the tarball's.
        fn with_digest_of(
            installed: &str,
            tag: &'static str,
            says: &str,
            corrupt_sums: Option<String>,
        ) -> Install {
            let serial = crate::repl::serial();
            let root = tempfile::tempdir().unwrap();
            let base = root.path().to_path_buf();
            let (prefix, state, assets) =
                (base.join("prefix"), base.join("state"), base.join("assets"));
            for d in [prefix.join("bin"), state.clone(), assets.clone()] {
                std::fs::create_dir_all(d).unwrap();
            }
            std::fs::write(prefix.join("bin/eclipse"), "old eclipse\n").unwrap();
            std::fs::write(prefix.join("bin/eclipse-web"), "old web\n").unwrap();

            let name = format!("eclipse-{tag}-x86_64-unknown-linux-gnu");
            let tarball = build_tarball(&assets, &name, says);
            let digest = corrupt_sums.unwrap_or_else(|| digest(&tarball));
            std::fs::write(
                assets.join("SHA256SUMS"),
                format!("{digest}  {name}.tar.gz\n"),
            )
            .unwrap();

            let name_static: &'static str = Box::leak(name.clone().into_boxed_str());
            let (url, hits) = serve(assets, tag, name_static);
            let marker = state.join("install.json");
            std::fs::write(
                &marker,
                format!(
                    r#"{{"channel":"release","prefix":{},"workspace":null,"commit":null,"installed_at":"2026-01-01T00:00:00Z","build":"release","version":"{installed}"}}"#,
                    serde_json::to_string(&prefix).unwrap()
                ),
            )
            .unwrap();
            Install {
                _root: root,
                _serial: serial,
                prefix,
                marker,
                state,
                url,
                hits,
            }
        }

        /// What the installed binary was called with, one invocation per line.
        fn calls(&self) -> String {
            std::fs::read_to_string(self.prefix.join("bin/calls")).unwrap_or_default()
        }

        fn setup(&self) -> Setup {
            Setup {
                marker: self.marker.clone(),
                session_dirs: Vec::new(),
                update: UpdateConfig {
                    check: eclipse_core::config::UpdateCheck::Off,
                    track: eclipse_core::config::Track::Release,
                    remote: None,
                    releases: Some(self.url.clone()),
                },
            }
        }

        fn go(&self, opts: Opts) -> (Result<Verdict>, String, String) {
            // The same dispatch `upgrade::run` does, from the record on disk.
            let setup = self.setup();
            let marker = InstallMarker::load(&setup.marker).unwrap().unwrap();
            let (mut out, mut err) = (Vec::new(), Vec::new());
            let verdict = run(
                &opts,
                &setup,
                &marker,
                &SystemRunner,
                &mut Term {
                    out: &mut out,
                    err: &mut err,
                    style: Style::plain(),
                    err_style: Style::plain(),
                },
            );
            (
                verdict,
                String::from_utf8_lossy(&out).into_owned(),
                String::from_utf8_lossy(&err).into_owned(),
            )
        }

        fn binary(&self) -> String {
            std::fs::read_to_string(self.prefix.join("bin/eclipse")).unwrap()
        }

        fn marker_json(&self) -> serde_json::Value {
            serde_json::from_str(&std::fs::read_to_string(&self.marker).unwrap()).unwrap()
        }

        fn asked_for(&self, needle: &str) -> usize {
            self.hits
                .lock()
                .unwrap()
                .iter()
                .filter(|p| p.contains(needle))
                .count()
        }
    }

    const UPGRADE: Opts = Opts {
        check: false,
        dry_run: false,
        no_restart: false,
    };
    const CHECK: Opts = Opts {
        check: true,
        dry_run: false,
        no_restart: false,
    };
    const PLAN: Opts = Opts {
        check: false,
        dry_run: true,
        no_restart: false,
    };

    fn refusal(r: Result<Verdict>) -> String {
        format!("{:#}", r.expect_err("expected a refusal"))
    }

    /// `#412`: the check requires three binaries and the message named two, so a tarball missing
    /// only `eclipse-gateway` was described as though `eclipse` and `eclipse-web` were wrong — at
    /// the one moment when nothing has been replaced and the message is all the reader has.
    #[test]
    fn a_tarball_missing_one_binary_names_the_one_it_is_missing() {
        let dir = tempfile::tempdir().unwrap();
        let latest = Release {
            tag: "v0.12.3".into(),
            version: Version::parse("v0.12.3").unwrap(),
            tarball_url: "https://example.invalid/t.tgz".into(),
            tarball_name: "t.tar.gz".into(),
            sums_url: "https://example.invalid/t.tgz.sha256".into(),
            page: None,
        };
        for name in BINARIES {
            if name == "eclipse-gateway" {
                continue;
            }
            std::fs::write(dir.path().join(name), "#!/bin/sh\nexit 0\n").unwrap();
        }
        let msg = format!(
            "{:#}",
            the_binary_says_its_version(&SystemRunner, &latest, dir.path())
                .expect_err("a tarball with two of three binaries is refused")
        );
        assert!(
            msg.contains("eclipse-gateway"),
            "the message names the one that is missing: {msg}"
        );
        assert!(
            !msg.contains("does not hold eclipse and"),
            "and does not blame the two that are there: {msg}"
        );
    }

    /// A swap is three renames, so it can stop after the first. `eclipse` new and `eclipse-web` old
    /// is an install that cannot be upgraded out of — the marker still names the old version — so the
    /// binaries already replaced are put back before the error is returned.
    #[test]
    fn a_swap_that_stops_half_way_puts_back_what_it_already_replaced() {
        let dir = tempfile::tempdir().unwrap();
        let bin_dir = dir.path().join("bin");
        let from = dir.path().join("unpacked");
        std::fs::create_dir_all(&bin_dir).unwrap();
        std::fs::create_dir_all(&from).unwrap();
        for (name, body) in [
            ("eclipse", "old eclipse\n"),
            ("eclipse-web", "old web\n"),
            ("eclipse-gateway", "old gateway\n"),
        ] {
            std::fs::write(bin_dir.join(name), body).unwrap();
            std::fs::write(from.join(name), body.replace("old", "new")).unwrap();
        }
        // Make the second replacement impossible: rename(2) over a non-empty directory fails, and by
        // then `eclipse` has already been swapped.
        std::fs::remove_file(bin_dir.join("eclipse-web")).unwrap();
        std::fs::create_dir(bin_dir.join("eclipse-web")).unwrap();
        std::fs::write(bin_dir.join("eclipse-web/keep"), "x").unwrap();

        let err = swap(&bin_dir, &from).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("eclipse-web"),
            "the error names the binary: {msg}"
        );
        assert!(
            msg.contains("undone"),
            "and says the install was put back: {msg}"
        );
        assert_eq!(
            std::fs::read_to_string(bin_dir.join("eclipse")).unwrap(),
            "old eclipse\n",
            "the binary that was already swapped is the old one again"
        );
        assert_eq!(
            std::fs::read_to_string(bin_dir.join("eclipse-gateway")).unwrap(),
            "old gateway\n",
            "and the one that was never reached is untouched"
        );
        assert!(
            !bin_dir.join(".eclipse.new").exists(),
            "no staging copy is left behind"
        );
        assert!(
            !bin_dir.join("eclipse.old").exists(),
            "the .old was consumed by the rollback, so nothing points at a binary that is now the target"
        );
    }

    /// `#599`: the marker is written last, so a marker that cannot be written used to leave three
    /// new binaries beside a record naming the old version — the one state this file's own comment
    /// calls un-upgradeable-out-of. The swap goes back with it, and so does a binary the swap
    /// introduced: this install had two, and a third left behind is a mixed install by another name.
    #[test]
    fn a_marker_that_cannot_be_written_takes_the_new_binaries_back_with_it() {
        let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
        // The record is written to `install.json.<pid>.tmp` and renamed over the marker, so a
        // directory at that exact path is a write that fails after the swap has already happened.
        let blocked = i
            .marker
            .with_extension(format!("json.{}.tmp", std::process::id()));
        std::fs::create_dir(&blocked).unwrap();

        let (verdict, _out, _err) = i.go(UPGRADE);
        let msg = refusal(verdict);
        assert!(
            msg.contains("install.json"),
            "the failure names the record: {msg}"
        );
        assert!(msg.contains("undone"), "and says the swap went back: {msg}");
        assert_eq!(
            i.binary(),
            "old eclipse\n",
            "the binary that ran before is the one in place"
        );
        assert_eq!(
            std::fs::read_to_string(i.prefix.join("bin/eclipse-web")).unwrap(),
            "old web\n"
        );
        assert!(
            !i.prefix.join("bin/eclipse-gateway").exists(),
            "the binary the swap introduced is gone again — this install had two, not three"
        );
        assert_eq!(
            i.marker_json()["version"],
            "0.2.0",
            "and the record still names the version that is running"
        );
        assert!(
            !i.prefix.join("bin/eclipse.old").exists(),
            "the rollback consumed the copy it made, so nothing points at a binary that is now the target"
        );
    }

    /// A backup that cannot be kept is a refusal while the install is still whole: every `.old` is
    /// taken before the first rename, so `nothing was replaced` is a promise about the tree rather
    /// than only about the message. Without that, this same failure was found after `eclipse` had
    /// already been renamed and put back — a swap that happened and left no trace a reader can see.
    #[test]
    fn a_backup_that_cannot_be_kept_refuses_before_any_binary_is_replaced() {
        let dir = tempfile::tempdir().unwrap();
        let (bin_dir, from) = (dir.path().join("bin"), dir.path().join("unpacked"));
        std::fs::create_dir_all(&bin_dir).unwrap();
        std::fs::create_dir_all(&from).unwrap();
        for name in BINARIES {
            std::fs::write(bin_dir.join(name), format!("old {name}\n")).unwrap();
            std::fs::write(from.join(name), format!("new {name}\n")).unwrap();
        }
        // A directory where the last binary's `.old` belongs: that backup cannot be kept.
        std::fs::create_dir(bin_dir.join("eclipse-gateway.old")).unwrap();

        let err = swap(&bin_dir, &from).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("nothing was replaced"),
            "the refusal says the install is whole: {msg}"
        );
        for name in BINARIES {
            assert_eq!(
                std::fs::read_to_string(bin_dir.join(name)).unwrap(),
                format!("old {name}\n"),
                "{name} is the one that was there"
            );
        }
        assert!(
            !bin_dir.join(".eclipse.new").exists(),
            "no staging copy is left behind"
        );
    }

    /// `#601`: `--dry-run` is documented as running nothing that changes anything, and the
    /// up-to-date branch returns *before* the dry-run check — so a plan printed a migration it then
    /// performed. The sibling above proves the migration is wanted when nothing is being installed;
    /// this one proves a plan is a plan.
    #[test]
    fn a_dry_run_of_an_up_to_date_install_migrates_nothing() {
        let i = Install::new("0.3.0", "v0.3.0", "0.3.0");
        let script = i.prefix.join("bin/eclipse");
        std::fs::write(
            &script,
            format!(
                "#!/bin/sh\necho \"$@\" >> {}\n",
                i.prefix.join("bin/calls").display()
            ),
        )
        .unwrap();
        chmod_x(&script);

        let (verdict, out, err) = i.go(PLAN);
        assert_eq!(verdict.unwrap(), Verdict::Current, "err: {err}");
        assert!(out.contains("already up to date"), "{out}");
        assert!(
            !i.prefix.join("bin/calls").exists(),
            "a dry run ran the migration: {}",
            i.calls()
        );
    }

    /// The rollback the upgrade prints used to name only the binary: rename `eclipse.old` back and
    /// the record still said 0.3.0, so `upgrade` answered "already up to date" for ever and the
    /// release it had just refused was never offered again. Both halves are kept now, and the
    /// recipe is followed here exactly as it is printed.
    #[test]
    fn the_printed_rollback_restores_the_record_too_so_the_release_is_offered_again() {
        let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
        let (verdict, out, err) = i.go(UPGRADE);
        assert_eq!(verdict.unwrap(), Verdict::Upgraded, "err: {err}");
        assert!(i.binary().contains("eclipse 0.3.0"), "{:?}", i.binary());

        let kept = i.state.join("install.json.old");
        assert!(
            kept.is_file(),
            "the record the upgrade replaced is kept beside it: {out}"
        );
        assert!(
            out.contains("install.json.old") && out.contains("rename each"),
            "the recipe names both halves: {out}"
        );

        // Do what it says: every `<name>.old` back over its target, and the record with them.
        for name in BINARIES {
            let old = i.prefix.join("bin").join(format!("{name}.old"));
            if old.is_file() {
                std::fs::rename(&old, i.prefix.join("bin").join(name)).unwrap();
            }
        }
        std::fs::rename(&kept, &i.marker).unwrap();

        assert_eq!(
            i.binary(),
            "old eclipse\n",
            "the rollback puts the old binary back"
        );
        assert_eq!(i.marker_json()["version"], "0.2.0");
        // The freeze this issue is about: the next run has to offer the release again.
        let (verdict, out, err) = i.go(CHECK);
        assert_eq!(verdict.unwrap(), Verdict::Behind, "err: {err}");
        assert!(out.contains("v0.3.0"), "{out}");
    }

    #[test]
    fn an_upgrade_installs_the_tag_keeps_the_old_binary_and_records_the_new_version() {
        let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
        let (verdict, out, err) = i.go(UPGRADE);
        assert_eq!(verdict.unwrap(), Verdict::Upgraded, "err: {err}");
        assert!(out.contains("upgraded:"), "{out}");
        assert!(
            i.binary().contains("eclipse 0.3.0"),
            "the new binary is in place: {:?}",
            i.binary()
        );
        assert_eq!(
            std::fs::read_to_string(i.prefix.join("bin/eclipse.old")).unwrap(),
            "old eclipse\n",
            "the old one is kept for a rollback"
        );
        assert_ne!(i.state.join("upgrade-0"), i.prefix, "nothing else moved");
        let marker = i.marker_json();
        assert_eq!(marker["channel"], "release");
        assert_eq!(marker["version"], "0.3.0");
        assert!(marker["commit"].is_null());
        assert!(marker["workspace"].is_null());
        let at = marker["installed_at"].as_str().unwrap();
        assert_eq!(at.len(), 20, "RFC 3339 UTC: {at}");
        assert_eq!(i.asked_for("SHA256SUMS"), 1, "the digests were fetched");
        // The scratch tree is scaffolding: it does not outlive the upgrade.
        let leftovers: Vec<_> = std::fs::read_dir(&i.state)
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        assert!(
            leftovers.iter().all(|n| !n.starts_with("upgrade-")),
            "{leftovers:?}"
        );
    }

    #[test]
    fn a_checksum_that_does_not_match_is_refused_and_nothing_is_replaced() {
        let wrong = "0".repeat(64);
        let i = Install::with_digest_of("0.2.0", "v0.3.0", "0.3.0", Some(wrong.clone()));
        let msg = refusal(i.go(UPGRADE).0);
        assert!(msg.contains(&wrong), "it prints what the file said: {msg}");
        assert!(msg.contains("0000") || msg.contains("SHA256"), "{msg}");
        assert_eq!(i.binary(), "old eclipse\n", "the binary is untouched");
        assert!(
            !i.prefix.join("bin/eclipse.old").exists(),
            "and there is nothing to roll back from"
        );
        assert_eq!(
            i.marker_json()["version"],
            "0.2.0",
            "the record is untouched"
        );
    }

    /// The release channel has its own "already current" return, so the source-channel fix does not
    /// reach it: a machine that took 0.10.1's binaries from `install.sh` has the new build and an
    /// old file, and this is the channel it upgrades on. Found by running the released binary.
    #[test]
    fn an_upgrade_with_nothing_to_install_migrates_the_config_on_the_release_channel() {
        let i = Install::new("0.3.0", "v0.3.0", "0.3.0");
        // A stand-in for the installed build, since the fixture's is not executable.
        let script = i.prefix.join("bin/eclipse");
        std::fs::write(
            &script,
            format!(
                "#!/bin/sh\necho \"$@\" >> {}\necho 'migrated: wrote something'\n",
                i.prefix.join("bin/calls").display()
            ),
        )
        .unwrap();
        chmod_x(&script);

        let (verdict, out, err) = i.go(UPGRADE);
        assert_eq!(verdict.unwrap(), Verdict::Current, "err: {err}");
        assert!(out.contains("already up to date"), "{out}");
        assert_eq!(
            i.calls().trim(),
            "config migrate",
            "the config catches up even when no binary moved"
        );

        // `--check` is a question and writes nothing.
        std::fs::remove_file(i.prefix.join("bin/calls")).unwrap();
        let (verdict, _out, err) = i.go(CHECK);
        assert_eq!(verdict.unwrap(), Verdict::Current, "err: {err}");
        assert!(
            !i.prefix.join("bin/calls").exists(),
            "--check must not run the migration"
        );
    }

    /// And after a real upgrade the same step runs, through the tarball's binary — which is what the
    /// source channel does too.
    #[test]
    fn a_release_upgrade_migrates_the_config_after_the_swap() {
        let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
        let (verdict, out, err) = i.go(UPGRADE);
        assert_eq!(verdict.unwrap(), Verdict::Upgraded, "out: {out} err: {err}");
        assert_eq!(
            i.calls().trim(),
            "config migrate",
            "the binary that was just installed is asked to bring the file forward: {out}"
        );
    }

    #[test]
    fn a_tarball_whose_binary_does_not_name_the_tag_is_refused_before_the_swap() {
        let i = Install::new("0.2.0", "v0.3.0", "9.9.9");
        let msg = refusal(i.go(UPGRADE).0);
        assert!(msg.contains("9.9.9") && msg.contains("0.3.0"), "{msg}");
        assert_eq!(i.binary(), "old eclipse\n");
        assert_eq!(i.marker_json()["version"], "0.2.0");
    }

    #[test]
    fn check_names_the_newer_tag_and_downloads_nothing() {
        let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
        let (verdict, out, err) = i.go(CHECK);
        assert_eq!(verdict.unwrap(), Verdict::Behind, "err: {err}");
        assert!(out.contains("v0.3.0") && out.contains("0.2.0"), "{out}");
        assert_eq!(i.asked_for("/dl/"), 0, "only the question, no assets");
        assert_eq!(i.binary(), "old eclipse\n");
    }

    #[test]
    fn a_current_install_says_so_and_downloads_nothing() {
        let i = Install::new("0.3.0", "v0.3.0", "0.3.0");
        for opts in [UPGRADE, CHECK] {
            let (verdict, out, _err) = i.go(opts);
            assert_eq!(verdict.unwrap(), Verdict::Current);
            assert!(out.contains("already up to date"), "{out}");
        }
        assert_eq!(i.asked_for("/dl/"), 0);
        assert_eq!(i.binary(), "old eclipse\n");
    }

    #[test]
    fn a_dry_run_prints_the_plan_and_downloads_nothing() {
        let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
        let (verdict, out, _err) = i.go(PLAN);
        assert_eq!(verdict.unwrap(), Verdict::Planned);
        for needle in ["sha256sum", "tar -xzf", "--version", "eclipse.old"] {
            assert!(out.contains(needle), "plan names {needle}: {out}");
        }
        assert_eq!(i.asked_for("/dl/"), 0);
        assert_eq!(i.binary(), "old eclipse\n");
    }

    #[test]
    fn a_major_jump_with_nobody_to_ask_is_refused_rather_than_assumed() {
        // `cargo test` gives the binary no terminal, which is the case this guards.
        let i = Install::new("0.9.0", "v1.0.0", "1.0.0");
        let msg = refusal(i.go(UPGRADE).0);
        assert!(msg.contains("major"), "{msg}");
        assert!(msg.contains("v1.0.0"), "{msg}");
        assert_eq!(i.binary(), "old eclipse\n");
        assert_eq!(
            i.asked_for("/dl/"),
            0,
            "nothing is downloaded to ask a question"
        );
    }

    #[test]
    fn a_marker_from_before_versions_were_recorded_is_refused_naming_the_fix() {
        let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
        std::fs::write(
            &i.marker,
            format!(
                r#"{{"channel":"release","prefix":{},"installed_at":"t"}}"#,
                serde_json::to_string(&i.prefix).unwrap()
            ),
        )
        .unwrap();
        let msg = refusal(i.go(UPGRADE).0);
        assert!(msg.contains("does not say which version"), "{msg}");
        assert!(msg.contains("install.sh"), "{msg}");
        assert_eq!(i.asked_for("/latest"), 0, "a refusal costs no request");
    }

    #[test]
    fn a_checksum_file_is_read_by_name_and_nothing_unparsable_is_believed() {
        let dir = tempfile::tempdir().unwrap();
        let sums = dir.path().join(update::SUMS_NAME);
        let hex = "a".repeat(64);
        let other = "b".repeat(64);
        std::fs::write(
            &sums,
            format!(
                "{hex}  eclipse-v0.2.0-x86_64-unknown-linux-gnu.tar.gz\n{other} *eclipse-v0.3.0-x86_64-unknown-linux-gnu.tar.gz\n"
            ),
        )
        .unwrap();
        assert_eq!(
            expected_digest(&sums, "eclipse-v0.3.0-x86_64-unknown-linux-gnu.tar.gz").unwrap(),
            other,
            "the binary-mode marker is not part of the name"
        );
        let missing = expected_digest(&sums, "eclipse-v0.9.0-x86_64-unknown-linux-gnu.tar.gz")
            .unwrap_err()
            .to_string();
        assert!(missing.contains("no SHA256"), "{missing}");

        // A short or non-hex digest next to the right name is a refusal, not a pass.
        std::fs::write(&sums, "deadbeef  eclipse.tar.gz\n").unwrap();
        assert!(expected_digest(&sums, "eclipse.tar.gz").is_err());
    }
}