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
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
//! `eclipse upgrade` and `eclipse upgrade --check`: bring a self-hosted install up to date
//! without a manual clone, and say what changed.
//!
//! What an upgrade replaces is the binaries. Config and sessions are never opened for writing.
//! Which half runs is the install record's decision, not a guess from the disk: a `source`
//! install is rebuilt from the checkout it names, through the same `install.sh` that put it
//! there; a `release` install is handed to [`crate::release`], which downloads and verifies a
//! tag's tarball. A checkout with local edits is refused before anything is fetched: there is
//! no `stash`, no `reset --hard`, no `checkout` over a file here.
//!
//! Every process this module starts goes through [`Runner`], so the tests can watch exactly what
//! a `--dry-run` runs (nothing that changes anything) without a real build.

use crate::ui::Style;
use anyhow::{bail, Result};
use eclipse_core::config::{Track, UpdateConfig};
use eclipse_core::session::{held_locks, HeldLock};
use eclipse_core::update::{Channel, InstallMarker};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

/// Commits listed before "and N more". Twenty fits a terminal beside its header, keeps a cron
/// mail short, and the count line above the list is always the true total.
pub const LOG_CAP: usize = 20;

#[derive(Debug, Clone, Copy, Default)]
pub struct Opts {
    /// Report only; exit status says whether an upgrade would take anything.
    pub check: bool,
    /// Print every command that would run and run none that changes anything.
    pub dry_run: bool,
    /// Leave the gateway process alone. It holds the old build in memory, so without this the
    /// upgrade ends with one command that the person did not have to remember to run.
    pub no_restart: bool,
}

/// Where the facts live, resolved by the caller so tests can point them anywhere.
pub struct Setup {
    pub marker: PathBuf,
    /// Every directory a run could hold a session lock in.
    pub session_dirs: Vec<PathBuf>,
    /// Where the release channel asks for a newer tag. Unused by the source channel, kept here
    /// so both channels read one place.
    pub update: UpdateConfig,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
    /// Nothing to take.
    Current,
    /// `--check` found commits (or a stale build) an upgrade would take.
    Behind,
    /// The binaries were replaced.
    Upgraded,
    /// `--dry-run` printed its plan.
    Planned,
}

/// One process to start.
#[derive(Debug, Clone)]
pub struct Cmd {
    pub program: String,
    pub args: Vec<String>,
    pub dir: Option<PathBuf>,
    /// Let the child write to this terminal (the build), instead of capturing its output.
    pub stream: bool,
    /// Do not let git stop and ask for a password: for the unattended `--check`.
    pub no_prompt: bool,
}

impl Cmd {
    fn git(ws: &Path, args: &[&str]) -> Cmd {
        let mut full = vec!["-C".to_string(), ws.display().to_string()];
        full.extend(args.iter().map(|a| a.to_string()));
        Cmd {
            program: "git".into(),
            args: full,
            dir: None,
            stream: false,
            no_prompt: false,
        }
    }

    pub fn display(&self) -> String {
        std::iter::once(self.program.as_str())
            .chain(self.args.iter().map(String::as_str))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

#[derive(Debug, Clone, Default)]
pub struct Out {
    pub success: bool,
    pub stdout: String,
    pub stderr: String,
}

pub trait Runner {
    fn run(&self, cmd: &Cmd) -> std::io::Result<Out>;
}

pub struct SystemRunner;

impl Runner for SystemRunner {
    fn run(&self, cmd: &Cmd) -> std::io::Result<Out> {
        let mut c = Command::new(&cmd.program);
        c.args(&cmd.args).stdin(Stdio::null());
        if let Some(dir) = &cmd.dir {
            c.current_dir(dir);
        }
        if cmd.no_prompt {
            c.env("GIT_TERMINAL_PROMPT", "0");
        }
        if cmd.stream {
            let status = c.status()?;
            return Ok(Out {
                success: status.success(),
                ..Out::default()
            });
        }
        let out = c.output()?;
        Ok(Out {
            success: out.status.success(),
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
        })
    }
}

/// The directories to look for live runs in: the configured sessions directory (when the config
/// could be read), the default profile's, and every named profile's — `<root>/profiles/<name>/state
/// /sessions`, beside that profile's config — because the binary being replaced is shared by all of
/// them.
///
/// `#376`: this used to build `<state>/profiles/<name>/sessions` from the *state* directory, a
/// layout that stopped existing when a profile became `<root>/profiles/<name>` with its own
/// `state/` inside. The guard that stops an upgrade replacing the binary under a live turn
/// therefore saw only the profile the upgrade itself was run from, and silently did nothing for
/// every other one. The test made the old shape by hand, so it passed while the real one was
/// uncovered.
pub fn session_dirs(root: &Path, configured: Option<PathBuf>) -> Vec<PathBuf> {
    let mut dirs: Vec<PathBuf> = configured.into_iter().collect();
    dirs.push(root.join("state").join("sessions"));
    if let Ok(profiles) = std::fs::read_dir(root.join("profiles")) {
        let mut found: Vec<PathBuf> = profiles
            .flatten()
            .map(|p| p.path().join("state").join("sessions"))
            .collect();
        found.sort();
        dirs.extend(found);
    }
    let mut seen = Vec::new();
    dirs.retain(|d| {
        let new = !seen.contains(d);
        seen.push(d.clone());
        new
    });
    dirs
}

pub struct Term<'a> {
    pub out: &'a mut dyn Write,
    pub err: &'a mut dyn Write,
    pub style: Style,
    pub err_style: Style,
}

fn short(id: &str) -> &str {
    id.get(..7).unwrap_or(id)
}

/// A checkout, as the git commands see it.
struct Repo<'a> {
    runner: &'a dyn Runner,
    ws: &'a Path,
    no_prompt: bool,
}

impl Repo<'_> {
    fn cmd(&self, args: &[&str]) -> Cmd {
        let mut c = Cmd::git(self.ws, args);
        c.no_prompt = self.no_prompt;
        c
    }

    fn output(&self, args: &[&str]) -> Result<Out> {
        let cmd = self.cmd(args);
        self.runner
            .run(&cmd)
            .map_err(|e| anyhow::anyhow!("could not run `{}`: {e}", cmd.display()))
    }

    /// Untrimmed stdout of a git command that must succeed; its own words if it does not.
    fn capture_raw(&self, args: &[&str]) -> Result<String> {
        let out = self.output(args)?;
        if !out.success {
            bail!("`git {}` failed: {}", args.join(" "), out.stderr.trim());
        }
        Ok(out.stdout)
    }

    fn capture(&self, args: &[&str]) -> Result<String> {
        Ok(self.capture_raw(args)?.trim().to_string())
    }

    fn count(&self, range: &str) -> Result<usize> {
        let text = self.capture(&["rev-list", "--count", range])?;
        text.parse()
            .map_err(|_| anyhow::anyhow!("`git rev-list --count {range}` printed {text:?}"))
    }
}

/// Tracked files with local changes, as `XY path`. Untracked files are not edits to lose, and
/// git itself refuses a pull that would overwrite one.
fn dirty_files(repo: &Repo) -> Result<Vec<String>> {
    let out = repo.capture_raw(&["status", "--porcelain", "-z", "--untracked-files=no"])?;
    let mut files = Vec::new();
    let mut entries = out.split('\0').filter(|e| !e.is_empty());
    while let Some(entry) = entries.next() {
        let (code, path) = entry.split_at(entry.len().min(2));
        files.push(format!("{code} {}", path.trim_start()));
        // A rename or copy carries its source as a second entry.
        if code.contains('R') || code.contains('C') {
            entries.next();
        }
    }
    Ok(files)
}

/// The install record, or the refusal that says how to make one.
fn load_marker(setup: &Setup) -> Result<InstallMarker> {
    match InstallMarker::load(&setup.marker)? {
        Some(m) => Ok(m),
        None => bail!(
            "no install record at {}: `eclipse upgrade` only upgrades an install made by \
             install.sh, which writes that file. Run install.sh once from your checkout (with \
             --prefix DIR if you used one) and try again",
            setup.marker.display()
        ),
    }
}

/// The checkout a source install is rebuilt from. Checked before anything is fetched: a record
/// that points at a tree which is gone is a refusal, not a reason to install somewhere new.
fn locate_checkout(setup: &Setup, marker: &InstallMarker) -> Result<PathBuf> {
    let Some(workspace) = marker.workspace.clone() else {
        bail!(
            "{} does not say which checkout the install was built from (it was written by an \
             older install.sh). Run install.sh once from your checkout to record it",
            setup.marker.display()
        );
    };
    if !workspace.join("install.sh").is_file() {
        bail!(
            "{} says the install was built from {}, but there is no install.sh there any more. \
             Run install.sh from the checkout you use now to record it",
            setup.marker.display(),
            workspace.display()
        );
    }
    Ok(workspace)
}

/// Refuse while a run holds a session: replacing the binary under it could lose the session.
pub(crate) fn no_run_in_progress(setup: &Setup) -> Result<()> {
    let runs: Vec<HeldLock> = setup
        .session_dirs
        .iter()
        .flat_map(|d| held_locks(d))
        .collect();
    if let Some(first) = runs.first() {
        bail!(
            "a run is in progress (session {} is held by {}): replacing the binary under it \
             could lose the session. Wait for it to finish, or stop it, then run \
             `eclipse upgrade` again",
            first.id,
            first.holder
        );
    }
    Ok(())
}

/// The branch an upgrade follows, and the refusal when the checkout is not on it.
///
/// The ref comes from `[update] track`, never from `@{u}`: a checkout parked on a feature branch
/// has an upstream too, and pulling it would make that branch an update channel nobody chose.
/// Nothing is fetched or pulled before this returns.
fn followed_branch(repo: &Repo, workspace: &Path, track: Track) -> Result<String> {
    let wanted = track.branch();
    let out = repo.output(&["rev-parse", "--abbrev-ref", "HEAD"])?;
    let found = out.stdout.trim();
    if !out.success || found.is_empty() {
        bail!(
            "could not tell which branch the checkout at {} is on ({}). `eclipse upgrade` \
             follows `{wanted}`, and it will not pull into a checkout it cannot identify",
            workspace.display(),
            out.stderr.trim()
        );
    }
    if found != wanted {
        let on = if found == "HEAD" {
            "a detached HEAD (not on a branch)".to_string()
        } else {
            format!("`{found}`")
        };
        bail!(
            "the checkout at {} is on {on}, and `[update] track = \"{}\"` follows `{wanted}`. \
             Nothing was fetched: an upgrade only ever pulls the track's branch. Check the \
             checkout out onto it (`git -C {} switch {wanted}`), or set the track to the branch \
             you are on (`eclipse config set update.track {}`)",
            workspace.display(),
            track.label(),
            workspace.display(),
            track.label()
        );
    }
    Ok(found.to_string())
}

/// Run `eclipse upgrade` (or `--check`). The returned verdict decides the exit status; an `Err`
/// is a refusal or a failure whose message is the whole explanation.
///
/// Two channels, one entry point: a checkout is pulled and rebuilt, a release tarball is
/// downloaded and swapped. The choice is the marker's, never a guess from what is on disk.
pub fn run(opts: &Opts, setup: &Setup, runner: &dyn Runner, term: &mut Term) -> Result<Verdict> {
    let marker = load_marker(setup)?;
    let binary = marker.prefix.join("bin").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, run install.sh again (with --prefix DIR for the new place) to record it",
            setup.marker.display(),
            marker.prefix.display(),
            binary.display()
        );
    }
    if marker.channel == Channel::Release {
        // A track names a branch, and a release install has none: `release.yml` builds a tag and
        // attaches its artefacts to it, so there is no develop build to download. Answering with
        // "release" there would make one word mean two things.
        if setup.update.track == Track::Develop {
            bail!(
                "this is a release install, and `[update] track = \"develop\"` has nothing to \
                 follow: the release workflow builds tags only, so there is no develop build to \
                 download. Set the track back with `eclipse config set update.track release`, or \
                 install from a clone of the repository (install.sh --track develop) to follow \
                 develop"
            );
        }
        return crate::release::run(opts, setup, &marker, runner, term);
    }
    let workspace = locate_checkout(setup, &marker)?;
    let repo = Repo {
        runner,
        ws: &workspace,
        no_prompt: opts.check,
    };

    let inside = repo.output(&["rev-parse", "--is-inside-work-tree"])?;
    if !inside.success {
        bail!(
            "{} is not a git checkout ({}), so there is nothing to fetch. Run install.sh from \
             a clone of github.com/mmhorda/eclipse to record one",
            workspace.display(),
            inside.stderr.trim()
        );
    }

    let dirty = dirty_files(&repo)?;
    if !dirty.is_empty() {
        let list = dirty
            .iter()
            .map(|f| format!("  {f}"))
            .collect::<Vec<_>>()
            .join("\n");
        if !opts.check {
            bail!(
                "{} has local changes, and an upgrade will not stash, reset or check out over \
                 them. Commit or discard these, then run it again:\n{list}",
                workspace.display()
            );
        }
        writeln!(
            term.err,
            "{} {} has local changes ({} file(s)); `eclipse upgrade` would refuse until they are \
             committed or discarded:\n{list}",
            term.err_style.yellow("warning:"),
            workspace.display(),
            dirty.len()
        )?;
    }

    if !opts.check {
        no_run_in_progress(setup)?;
    }

    let branch = followed_branch(&repo, &workspace, setup.update.track)?;
    let target = format!("origin/{branch}");

    let mut install = vec![
        workspace.join("install.sh").display().to_string(),
        "--upgrade".to_string(),
        "--prefix".to_string(),
        marker.prefix.display().to_string(),
    ];
    if marker.build.as_deref() == Some("debug") {
        install.push("--debug".to_string());
    }
    let install_cmd = Cmd {
        program: install.remove(0),
        args: install,
        dir: Some(workspace.clone()),
        stream: true,
        no_prompt: false,
    };

    let head_range = format!("HEAD..{target}");
    let log_cmd = repo.cmd(&["log", "--oneline", "-n", &LOG_CAP.to_string(), &head_range]);

    if opts.dry_run {
        let mut plan = vec![
            repo.cmd(&["fetch"]),
            log_cmd,
            repo.cmd(&["merge", "--ff-only", &target]),
            install_cmd,
        ];
        // A plan that stops at the install would leave out the half of the upgrade the reader
        // has to notice: the process that keeps the old build until it is restarted.
        if !opts.no_restart && crate::gateway_cli::installed_unit().is_some() {
            plan.push(systemctl(&["restart", crate::gateway_cli::SERVICE_NAME]));
        }
        writeln!(
            term.out,
            "dry run: nothing below is run. An upgrade would run:"
        )?;
        for c in &plan {
            writeln!(term.out, "  {}", c.display())?;
        }
        writeln!(
            term.out,
            "Sessions are never touched. The config's values are not changed either: \
             `config migrate` runs afterwards to add a setting this build reads, and \
             `eclipse config migrate --dry-run` shows that list before you upgrade."
        )?;
        return Ok(Verdict::Planned);
    }

    let fetch = repo.output(&["fetch"])?;
    if !fetch.success {
        bail!(
            "could not fetch {} for the checkout at {}: {}. The remote may be unreachable; \
             nothing was changed",
            target,
            workspace.display(),
            fetch.stderr.trim()
        );
    }
    // The fetch brought the remote's branches; the track's one has to be among them. A checkout
    // fed by a remote that is not called `origin`, or one that does not carry this branch, has
    // nothing on this track — naming it is better than pulling a ref that is not there.
    if !repo
        .output(&[
            "rev-parse",
            "--verify",
            "--quiet",
            &format!("{target}^{{commit}}"),
        ])?
        .success
    {
        bail!(
            "the checkout at {} has no `{target}` after `git fetch`, so there is nothing on the \
             `{}` track to follow. Its remote may carry no {branch}, or may not be called \
             `origin`; `git -C {} fetch origin {branch}` creates it",
            workspace.display(),
            setup.update.track.label(),
            workspace.display()
        );
    }

    let head = repo.capture(&["rev-parse", "HEAD"])?;
    let installed = marker.commit.clone().filter(|c| !c.is_empty());
    // What the install is missing is measured from the build that is installed, not from the
    // checkout: after a manual `git pull`, or a build that failed halfway through an upgrade,
    // the checkout is current and the binaries are not.
    let stale = installed.as_deref().is_some_and(|c| c != head);
    let base = installed
        .as_deref()
        .filter(|c| {
            repo.output(&["cat-file", "-e", &format!("{c}^{{commit}}")])
                .is_ok_and(|o| o.success)
        })
        .unwrap_or("HEAD")
        .to_string();
    let range = format!("{base}..{target}");
    let incoming = repo.count(&range)?;
    let to_pull = repo.count(&head_range)?;

    if to_pull == 0 && !stale {
        writeln!(
            term.out,
            "{} {} on {target}",
            term.style.green("already up to date:"),
            short(&head)
        )?;
        // Nothing to install, but the config can still be a shape behind: a machine upgraded by
        // `install.sh` (or one that took a build before this command existed) has the new binaries
        // and the old file. Without this, the only way to migrate is to remember `config migrate`,
        // and an upgrade is the moment a person expects their file to catch up. `--check` stays a
        // read-only question and does not.
        if !opts.check {
            migrate_config(term, &marker.prefix)?;
        }
        return Ok(Verdict::Current);
    }

    if incoming > 0 {
        writeln!(
            term.out,
            "{incoming} new commit{} on {target}:",
            if incoming == 1 { "" } else { "s" }
        )?;
        let log = repo.capture(&["log", "--oneline", "-n", &LOG_CAP.to_string(), &range])?;
        for line in log.lines() {
            writeln!(term.out, "  {line}")?;
        }
        if incoming > LOG_CAP {
            writeln!(
                term.out,
                "  \u{2026} and {} more (`git -C {} log --oneline {range}`)",
                incoming - LOG_CAP,
                workspace.display()
            )?;
        }
    }
    if stale {
        writeln!(
            term.out,
            "the installed build ({}) is not the checkout ({}); `eclipse upgrade` rebuilds it",
            short(installed.as_deref().unwrap_or("?")),
            short(&head)
        )?;
    }
    if opts.check {
        return Ok(Verdict::Behind);
    }

    writeln!(
        term.out,
        "{}",
        term.style.dim(
            "Sessions are never touched. The config's values are not changed either: \
             `config migrate` runs afterwards to add a setting this build reads, and \
             `eclipse config migrate --dry-run` shows that list before you upgrade."
        )
    )?;
    if to_pull > 0 {
        let pull = repo.output(&["merge", "--ff-only", &target])?;
        if !pull.success {
            bail!(
                "`git merge --ff-only {target}` failed in {}: {}. An upgrade only ever \
                 fast-forwards: it will not merge or rebase your commits. Nothing was installed; \
                 resolve the checkout by hand and run `eclipse upgrade` again",
                workspace.display(),
                pull.stderr.trim()
            );
        }
    }
    let now = repo.capture(&["rev-parse", "HEAD"])?;
    writeln!(
        term.out,
        "checkout at {}; rebuilding and reinstalling",
        short(&now)
    )?;
    term.out.flush()?;
    let built = runner
        .run(&install_cmd)
        .map_err(|e| anyhow::anyhow!("could not run `{}`: {e}", install_cmd.display()))?;
    if !built.success {
        bail!(
            "`{}` failed (its output is above). The checkout is at {} but the installed \
             binaries are still the old ones; fix the build and run `eclipse upgrade` again, \
             which rebuilds from the checkout",
            install_cmd.display(),
            short(&now)
        );
    }
    writeln!(
        term.out,
        "{} {} \u{2192} {}.",
        term.style.green("upgraded:"),
        short(installed.as_deref().unwrap_or(&head)),
        short(&now)
    )?;
    // The binaries are new; the process is not. Say it and do it — the line that used to stand
    // here told the reader to remember to restart, which is the one thing a command should not do.
    // `#404`: a restart that cannot run is a warning, not a failed upgrade.
    if let Err(e) = after_the_binaries(term, runner, opts) {
        writeln!(
            term.out,
            "{}",
            term.style
                .dim(&format!("the gateway was not restarted ({e})"))
        )?;
    }
    migrate_config(term, &marker.prefix)?;
    refresh_manual(term)?;
    Ok(Verdict::Upgraded)
}

/// Bring the config forward, with the **new** binary.
///
/// It has to be a subprocess: the process running this function is the build being replaced, and a
/// migration decided by the old binary would add the old build's settings to a file the new build
/// is about to read. `<prefix>/bin/eclipse config migrate` is both the honest version and the one
/// command `doctor` names when an install was upgraded by `install.sh` instead of by `eclipse
/// upgrade` — the two paths converge on one implementation.
///
/// Never fatal: an upgrade that swapped the binaries has succeeded, and a config that is one shape
/// behind still loads. A failure is reported in the output and the exit code stays 0.
pub(crate) fn migrate_config(term: &mut Term, prefix: &std::path::Path) -> Result<()> {
    let binary = prefix.join("bin").join("eclipse");
    if !binary.is_file() {
        return Ok(());
    }
    let output = std::process::Command::new(&binary)
        .arg("config")
        .arg("migrate")
        .output();
    match output {
        Ok(out) if out.status.success() => {
            let text = String::from_utf8_lossy(&out.stdout);
            // Only say something when the file actually moved: "already current" every time makes
            // an upgrade's output noise, and this runs on every upgrade.
            if text.contains("migrated:") {
                for line in text.lines().filter(|l| !l.trim().is_empty()) {
                    writeln!(term.out, "  {line}")?;
                }
            }
        }
        Ok(out) => writeln!(
            term.out,
            "{} `config migrate` failed ({}); the config is unchanged and still loads: {}",
            term.style.yellow("warning:"),
            out.status,
            String::from_utf8_lossy(&out.stderr).trim()
        )?,
        Err(e) => writeln!(
            term.out,
            "{} could not run {} config migrate: {e}",
            term.style.yellow("warning:"),
            binary.display()
        )?,
    }
    Ok(())
}

/// Rewrite the manual beside the config, because it describes *this* build and the build just
/// changed. Written whether or not a page is already there: the manual ships with the install, and
/// an install old enough to predate it (`~/.eclipse/docs/` did not exist before 0.10) is the one that
/// needs it most — it is the model on that box that has to answer "what does this key accept", and
/// expecting it to know that `config docs` exists first is the wrong way round.
///
/// Best effort by design — an upgrade that swapped the binaries must not report a failure because
/// a documentation page could not be written.
fn refresh_manual(term: &mut Term) -> Result<()> {
    let env = |key: &str| std::env::var(key).ok().filter(|v| !v.is_empty());
    let Some(config_path) = eclipse_core::config::config_path(&env) else {
        return Ok(());
    };
    let page = crate::docs_cli::page_path(&config_path);
    let Ok(cfg) = eclipse_core::config::Config::load_with(Some(&config_path), &env) else {
        return Ok(());
    };
    match crate::docs_cli::write_page(&config_path, &cfg, env!("CARGO_PKG_VERSION")) {
        Ok(_) => writeln!(term.out, "{} {}", term.style.dim("manual:"), page.display())?,
        Err(e) => writeln!(
            term.out,
            "{} could not rewrite {}: {e}",
            term.style.yellow("warning:"),
            page.display()
        )?,
    }
    Ok(())
}

/// `systemctl --user …` for the gateway, in the shape the rest of this module runs commands in.
pub(crate) fn systemctl(args: &[&str]) -> Cmd {
    let mut full: Vec<String> = vec!["--user".to_string()];
    full.extend(args.iter().map(|a| a.to_string()));
    Cmd {
        program: "systemctl".into(),
        args: full,
        dir: None,
        stream: false,
        no_prompt: false,
    }
}

/// What an upgrade owes the machine once the binaries are in place: the gateway process holds the
/// old build in memory, and nothing else is going to replace it.
pub(crate) fn after_the_binaries(term: &mut Term, runner: &dyn Runner, opts: &Opts) -> Result<()> {
    if crate::gateway_cli::installed_unit().is_none() {
        // No unit, no daemon to be stale — the common case on a machine that only runs the CLI,
        // and it should say nothing at all.
        return Ok(());
    }
    if opts.no_restart {
        writeln!(
            term.out,
            "{}",
            term.style.dim(
                "--no-restart: the gateway still holds the old build; `eclipse gateway restart` \
                 when you want it on the new one"
            )
        )?;
        return Ok(());
    }
    let active = runner.run(&systemctl(&["is-active", crate::gateway_cli::SERVICE_NAME]))?;
    if !(active.success && crate::gateway_cli::is_active_text(&active.stdout)) {
        writeln!(
            term.out,
            "{}",
            term.style.dim(
                "the gateway is installed but not running; `eclipse gateway start` brings up the \
                 new build"
            )
        )?;
        return Ok(());
    }
    let restarted = runner.run(&systemctl(&["restart", crate::gateway_cli::SERVICE_NAME]))?;
    if !restarted.success {
        // The upgrade itself succeeded, so this is a warning and not a failure: the binaries are
        // in place and the next restart picks them up. Failing here would report an upgrade that
        // did happen as one that did not.
        writeln!(
            term.err,
            "{} the gateway did not restart ({}). It is still serving the old build; \
             `eclipse gateway restart` says why",
            term.err_style.yellow("warning:"),
            restarted.stderr.trim()
        )?;
        return Ok(());
    }
    writeln!(
        term.out,
        "{} the new binary is the one serving now",
        term.style.green("gateway restarted:")
    )?;
    Ok(())
}

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

    /// Runs everything for real and remembers what it ran, in order.
    struct Recording {
        calls: RefCell<Vec<String>>,
    }

    impl Recording {
        fn new() -> Self {
            Recording {
                calls: RefCell::new(Vec::new()),
            }
        }
        fn ran(&self, needle: &str) -> bool {
            self.calls.borrow().iter().any(|c| c.contains(needle))
        }
    }

    impl Runner for Recording {
        fn run(&self, cmd: &Cmd) -> std::io::Result<Out> {
            self.calls.borrow_mut().push(cmd.display());
            SystemRunner.run(cmd)
        }
    }

    fn sh(dir: &Path, program: &str, args: &[&str]) -> String {
        let out = Command::new(program)
            .current_dir(dir)
            .args(args)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .output()
            .unwrap();
        assert!(out.status.success(), "{program} {args:?}: {out:?}");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    /// A bare `origin`, a checkout cloned from it (holding a stub `install.sh` that records how
    /// it was called), an install prefix with an `eclipse` in it, and a marker tying them
    /// together. Nothing here touches the network or a real build.
    struct Fixture {
        _root: tempfile::TempDir,
        _serial: std::sync::MutexGuard<'static, ()>,
        origin: PathBuf,
        ws: PathBuf,
        prefix: PathBuf,
        marker: PathBuf,
        state: PathBuf,
        /// The install root: `<root>/state` is `state`, and a profile's sessions are
        /// `<root>/profiles/<name>/state/sessions` — which is what `session_dirs` now takes.
        root: PathBuf,
    }

    impl Fixture {
        fn new() -> Fixture {
            let serial = crate::repl::serial();
            let root = tempfile::tempdir().unwrap();
            let base = root.path().to_path_buf();
            let origin = base.join("origin.git");
            let seed = base.join("seed");
            let ws = base.join("checkout");
            let prefix = base.join("prefix");
            let state = base.join("state");
            std::fs::create_dir_all(&origin).unwrap();
            std::fs::create_dir_all(&seed).unwrap();
            std::fs::create_dir_all(prefix.join("bin")).unwrap();
            std::fs::create_dir_all(&state).unwrap();
            std::fs::write(prefix.join("bin/eclipse"), "old binary").unwrap();

            sh(&origin, "git", &["init", "-q", "--bare", "-b", "main"]);
            sh(&seed, "git", &["init", "-q", "-b", "main"]);
            // The stub fails while `fail-build` exists, and otherwise records its arguments.
            std::fs::write(
                seed.join("install.sh"),
                "#!/bin/sh\ncd \"$(dirname \"$0\")\"\n\
                 [ ! -e fail-build ] || { echo 'cargo exploded' >&2; exit 1; }\n\
                 echo \"$@\" >> install-calls\n",
            )
            .unwrap();
            std::fs::write(seed.join("README"), "one\n").unwrap();
            sh(&seed, "chmod", &["+x", "install.sh"]);
            sh(&seed, "git", &["add", "."]);
            sh(&seed, "git", &["commit", "-q", "-m", "first"]);
            sh(
                &seed,
                "git",
                &["remote", "add", "origin", origin.to_str().unwrap()],
            );
            sh(&seed, "git", &["push", "-q", "origin", "main"]);
            sh(
                &base,
                "git",
                &["clone", "-q", origin.to_str().unwrap(), "checkout"],
            );

            let f = Fixture {
                _root: root,
                _serial: serial,
                origin,
                ws,
                prefix,
                marker: state.join("install.json"),
                state,
                root: base.clone(),
            };
            f.write_marker("source", Some(&f.head()), None);
            f
        }

        fn head(&self) -> String {
            sh(&self.ws, "git", &["rev-parse", "HEAD"])
        }

        fn write_marker(&self, channel: &str, commit: Option<&str>, build: Option<&str>) {
            let json = serde_json::json!({
                "channel": channel,
                "prefix": self.prefix,
                "workspace": self.ws,
                "commit": commit,
                "installed_at": "2026-01-01T00:00:00Z",
                "build": build,
            });
            std::fs::write(&self.marker, json.to_string()).unwrap();
        }

        /// A commit on the remote that the checkout has not fetched.
        fn publish(&self, subject: &str) {
            let seed = self.ws.parent().unwrap().join("seed");
            sh(
                &seed,
                "git",
                &["commit", "-q", "--allow-empty", "-m", subject],
            );
            sh(&seed, "git", &["push", "-q", "origin", "main"]);
        }

        /// A commit on `branch` of the remote, which the checkout has not fetched. The seed is
        /// moved there detached and put back on `main`, so the other branch never gains it.
        fn publish_to(&self, branch: &str, subject: &str) {
            let seed = self.ws.parent().unwrap().join("seed");
            let at = format!("origin/{branch}");
            sh(&seed, "git", &["fetch", "-q", "origin", branch]);
            sh(&seed, "git", &["checkout", "-q", "--detach", &at]);
            sh(
                &seed,
                "git",
                &["commit", "-q", "--allow-empty", "-m", subject],
            );
            sh(
                &seed,
                "git",
                &["push", "-q", "origin", &format!("HEAD:refs/heads/{branch}")],
            );
            sh(&seed, "git", &["checkout", "-q", "main"]);
        }

        /// A `develop` branch on the remote at `main`'s tip, and the checkout on it: what
        /// `install.sh --track develop` leaves behind.
        fn follow_develop(&self) {
            let seed = self.ws.parent().unwrap().join("seed");
            sh(&seed, "git", &["branch", "-f", "develop", "main"]);
            sh(&seed, "git", &["push", "-q", "origin", "develop"]);
            sh(&self.ws, "git", &["fetch", "-q", "origin"]);
            sh(
                &self.ws,
                "git",
                &[
                    "checkout",
                    "-q",
                    "-b",
                    "develop",
                    "--track",
                    "origin/develop",
                ],
            );
        }

        /// The same facts, with the track a test wants in force. `go` is this with the release
        /// track, which is what every test that does not name one means.
        fn setup_on(&self, track: Track) -> Setup {
            Setup {
                marker: self.marker.clone(),
                session_dirs: session_dirs(&self.root, None),
                update: UpdateConfig {
                    track,
                    ..UpdateConfig::default()
                },
            }
        }

        fn go(&self, opts: Opts, runner: &dyn Runner) -> (Result<Verdict>, String, String) {
            self.go_on(opts, runner, Track::Release)
        }

        fn go_on(
            &self,
            opts: Opts,
            runner: &dyn Runner,
            track: Track,
        ) -> (Result<Verdict>, String, String) {
            let (mut out, mut err) = (Vec::new(), Vec::new());
            let verdict = run(
                &opts,
                &self.setup_on(track),
                runner,
                &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(),
            )
        }
    }

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

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

    #[test]
    fn a_missing_marker_is_refused_naming_the_path_it_looked_for() {
        let f = Fixture::new();
        std::fs::remove_file(&f.marker).unwrap();
        let run = Recording::new();
        let msg = refusal(f.go(UPGRADE, &run).0);
        assert!(msg.contains(f.marker.to_str().unwrap()), "{msg}");
        assert!(
            msg.contains("install.sh") && msg.contains("--prefix"),
            "{msg}"
        );
        assert!(run.calls.borrow().is_empty(), "nothing ran");
    }

    #[test]
    fn a_release_marker_is_never_upgraded_from_its_checkout_and_says_what_recorded_it() {
        let f = Fixture::new();
        // Written by an install.sh from before the marker carried a version: a release install
        // with nothing to compare a tag against.
        f.write_marker("release", None, None);
        let run = Recording::new();
        let msg = refusal(f.go(UPGRADE, &run).0);
        assert!(msg.contains("does not say which version"), "{msg}");
        assert!(
            msg.contains("install.sh"),
            "the refusal says what records it: {msg}"
        );
        assert!(
            run.calls.borrow().is_empty(),
            "a release install runs no git and no build: {:?}",
            run.calls.borrow()
        );
    }

    #[test]
    fn a_prefix_with_no_binary_is_refused_rather_than_installed_somewhere_new() {
        let f = Fixture::new();
        std::fs::remove_file(f.prefix.join("bin/eclipse")).unwrap();
        let run = Recording::new();
        let msg = refusal(f.go(UPGRADE, &run).0);
        let bin = f.prefix.join("bin/eclipse");
        assert!(msg.contains(bin.to_str().unwrap()), "{msg}");
        assert!(
            msg.contains("nothing will be installed anywhere new"),
            "{msg}"
        );
        assert!(run.calls.borrow().is_empty(), "nothing ran");
    }

    #[test]
    fn a_dirty_tree_is_refused_naming_the_files_and_nothing_is_fetched_or_changed() {
        let f = Fixture::new();
        f.publish("second");
        std::fs::write(f.ws.join("README"), "my local edit\n").unwrap();
        let before = f.head();
        let run = Recording::new();
        let msg = refusal(f.go(UPGRADE, &run).0);
        assert!(
            msg.contains("README") && msg.contains("local changes"),
            "{msg}"
        );
        assert!(!run.ran(" fetch") && !run.ran(" pull") && !run.ran("install.sh"));
        assert_eq!(f.head(), before);
        assert_eq!(
            std::fs::read_to_string(f.ws.join("README")).unwrap(),
            "my local edit\n",
            "the edit survives"
        );
        assert!(!f.ws.join("install-calls").exists());
    }

    #[test]
    fn check_is_current_when_nothing_is_new_and_prints_one_line() {
        let f = Fixture::new();
        let (verdict, out, err) = f.go(CHECK, &SystemRunner);
        assert_eq!(verdict.unwrap(), Verdict::Current);
        assert_eq!(out.lines().count(), 1, "{out}");
        assert!(
            out.contains("already up to date") && err.is_empty(),
            "{out} / {err}"
        );
    }

    #[test]
    fn check_is_behind_and_lists_the_commits_when_the_remote_has_a_new_one() {
        let f = Fixture::new();
        f.publish("teach the agent to sing");
        let (verdict, out, _) = f.go(CHECK, &SystemRunner);
        assert_eq!(verdict.unwrap(), Verdict::Behind);
        assert!(
            out.contains("1 new commit") && out.contains("teach the agent to sing"),
            "{out}"
        );
        assert_eq!(
            sh(&f.ws, "git", &["log", "--oneline"]).lines().count(),
            1,
            "check fetches but never pulls"
        );
    }

    #[test]
    fn check_reports_an_unreachable_remote_as_an_error() {
        let f = Fixture::new();
        std::fs::remove_dir_all(&f.origin).unwrap();
        let msg = refusal(f.go(CHECK, &SystemRunner).0);
        assert!(
            msg.contains("could not fetch") && msg.contains("nothing was changed"),
            "{msg}"
        );
    }

    #[test]
    fn check_on_a_dirty_tree_warns_on_stderr_and_still_reports_what_is_behind() {
        let f = Fixture::new();
        f.publish("second");
        std::fs::write(f.ws.join("README"), "edited\n").unwrap();
        let (verdict, out, err) = f.go(CHECK, &SystemRunner);
        assert_eq!(
            verdict.unwrap(),
            Verdict::Behind,
            "a dirty tree is not an error here"
        );
        assert!(
            err.contains("README") && err.contains("local changes"),
            "{err}"
        );
        assert!(out.contains("second"), "{out}");
    }

    #[test]
    fn check_caps_a_long_list_and_still_prints_the_true_count() {
        let f = Fixture::new();
        for i in 0..(LOG_CAP + 5) {
            f.publish(&format!("change {i}"));
        }
        let (verdict, out, _) = f.go(CHECK, &SystemRunner);
        assert_eq!(verdict.unwrap(), Verdict::Behind);
        assert!(
            out.contains(&format!("{} new commits", LOG_CAP + 5)),
            "{out}"
        );
        assert!(out.contains("and 5 more"), "{out}");
        assert_eq!(out.matches("change ").count(), LOG_CAP);
    }

    #[test]
    fn dry_run_prints_every_command_and_runs_nothing_that_changes_anything() {
        let f = Fixture::new();
        f.publish("second");
        let before = f.head();
        let run = Recording::new();
        let opts = Opts {
            check: false,
            dry_run: true,
            no_restart: false,
        };
        let (verdict, out, _) = f.go(opts, &run);
        assert_eq!(verdict.unwrap(), Verdict::Planned);
        for needle in [
            " fetch",
            "log --oneline",
            "merge --ff-only origin/main",
            "install.sh --upgrade --prefix",
        ] {
            assert!(
                out.contains(needle),
                "{needle} missing from the plan:\n{out}"
            );
        }
        for mutating in [" fetch", " pull", "install.sh", "cargo"] {
            assert!(
                !run.ran(mutating),
                "dry run ran {mutating}: {:?}",
                run.calls.borrow()
            );
        }
        assert_eq!(f.head(), before);
        assert!(!f.ws.join("install-calls").exists());
        let tracking = sh(&f.ws, "git", &["rev-parse", "origin/main"]);
        assert_eq!(tracking, before, "nothing was fetched");
    }

    #[test]
    fn an_upgrade_takes_the_commits_rebuilds_through_install_sh_and_says_config_is_untouched() {
        let f = Fixture::new();
        f.publish("add the thing");
        let old = f.head();
        let (verdict, out, _) = f.go(UPGRADE, &SystemRunner);
        assert_eq!(verdict.unwrap(), Verdict::Upgraded, "{out}");
        assert!(
            out.contains("1 new commit") && out.contains("add the thing"),
            "{out}"
        );
        // The promise is narrower than it was before #294 and has to be exactly as narrow: the
        // values are untouched, but the migration after the install may add a key.
        assert_eq!(
            out.matches("Sessions are never touched").count(),
            1,
            "{out}"
        );
        assert!(out.contains("config migrate --dry-run"), "{out}");
        assert_ne!(f.head(), old, "the checkout moved");
        let calls = std::fs::read_to_string(f.ws.join("install-calls")).unwrap();
        assert_eq!(calls.lines().count(), 1, "{calls}");
        assert!(
            calls.contains(&format!("--upgrade --prefix {}", f.prefix.display())),
            "{calls}"
        );
        assert!(
            !calls.contains("--no-build"),
            "--no-build would install the OLD build: {calls}"
        );
    }

    #[test]
    fn a_second_upgrade_has_nothing_to_do() {
        let f = Fixture::new();
        f.publish("add the thing");
        assert_eq!(f.go(UPGRADE, &SystemRunner).0.unwrap(), Verdict::Upgraded);
        // install.sh would have recorded the new commit; the stub does not, so do it here.
        f.write_marker("source", Some(&f.head()), None);
        let (verdict, out, _) = f.go(UPGRADE, &SystemRunner);
        assert_eq!(verdict.unwrap(), Verdict::Current);
        assert!(out.contains("already up to date"), "{out}");
        let calls = std::fs::read_to_string(f.ws.join("install-calls")).unwrap();
        assert_eq!(calls.lines().count(), 1, "no second rebuild: {calls}");
    }

    #[test]
    fn a_debug_install_is_rebuilt_as_a_debug_install() {
        let f = Fixture::new();
        f.write_marker("source", Some(&f.head()), Some("debug"));
        f.publish("x");
        assert_eq!(f.go(UPGRADE, &SystemRunner).0.unwrap(), Verdict::Upgraded);
        let calls = std::fs::read_to_string(f.ws.join("install-calls")).unwrap();
        assert!(calls.contains("--debug"), "{calls}");
    }

    #[test]
    fn a_failed_build_is_reported_and_the_next_upgrade_rebuilds_even_though_the_checkout_is_current(
    ) {
        let f = Fixture::new();
        f.publish("breaks the build");
        std::fs::write(f.ws.join("fail-build"), "").unwrap();
        let msg = refusal(f.go(UPGRADE, &SystemRunner).0);
        assert!(
            msg.contains("still the old ones") && msg.contains("run `eclipse upgrade` again"),
            "{msg}"
        );

        // The marker still names the old commit, so the checkout being current is not "done".
        std::fs::remove_file(f.ws.join("fail-build")).unwrap();
        let (verdict, out, _) = f.go(UPGRADE, &SystemRunner);
        assert_eq!(verdict.unwrap(), Verdict::Upgraded, "{out}");
        assert!(out.contains("installed build"), "{out}");
        assert!(f.ws.join("install-calls").exists());
    }

    #[test]
    fn a_checkout_that_cannot_fast_forward_is_refused_without_merging() {
        let f = Fixture::new();
        sh(
            &f.ws,
            "git",
            &["commit", "-q", "--allow-empty", "-m", "mine"],
        );
        f.write_marker("source", Some(&f.head()), None);
        f.publish("theirs");
        let mine = f.head();
        let msg = refusal(f.go(UPGRADE, &SystemRunner).0);
        assert!(msg.contains("will not merge or rebase"), "{msg}");
        assert_eq!(f.head(), mine, "the checkout is where it was");
        assert!(!f.ws.join("install-calls").exists());
    }

    #[cfg(unix)]
    #[test]
    fn an_upgrade_inside_a_run_is_refused_and_names_the_session() {
        use std::os::unix::io::AsRawFd;
        let f = Fixture::new();
        f.publish("second");
        let sessions = f.state.join("sessions");
        std::fs::create_dir_all(&sessions).unwrap();
        let lock = std::fs::File::create(sessions.join("busy-1.lock")).unwrap();
        // SAFETY: `lock` owns a valid descriptor; this is the lock a real run takes.
        assert_eq!(unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) }, 0);

        let run = Recording::new();
        let msg = refusal(f.go(UPGRADE, &run).0);
        assert!(
            msg.contains("a run is in progress") && msg.contains("busy-1"),
            "{msg}"
        );
        assert!(!run.ran(" fetch") && !run.ran("install.sh"));

        // `--check` only reads, so a run in progress does not stop it.
        assert_eq!(f.go(CHECK, &SystemRunner).0.unwrap(), Verdict::Behind);
        drop(lock);
    }

    #[test]
    fn profiles_sessions_are_searched_for_runs_too() {
        let _serial = crate::repl::serial();
        let tmp = tempfile::tempdir().unwrap();
        // The *real* layout: a profile is `<root>/profiles/<name>` with its own `state/` inside,
        // not `<root>/state/profiles/<name>`. The old test built the second shape by hand, which is
        // why it passed while the guard saw nothing on a real install (`#376`).
        std::fs::create_dir_all(tmp.path().join("profiles/work/state/sessions")).unwrap();
        let dirs = session_dirs(tmp.path(), None);
        assert!(
            dirs.contains(&tmp.path().join("profiles/work/state/sessions")),
            "{dirs:?}"
        );
        assert!(
            dirs.contains(&tmp.path().join("state/sessions")),
            "{dirs:?}"
        );
        assert!(
            !dirs.contains(&tmp.path().join("profiles/work/sessions")),
            "the pre-0.9 shape is not a place to look: {dirs:?}"
        );
        // And a configured directory that *is* the default one is not listed twice.
        let dirs = session_dirs(Path::new("/s"), Some(PathBuf::from("/s/state/sessions")));
        assert_eq!(dirs, [PathBuf::from("/s/state/sessions")], "{dirs:?}");
    }

    /// The headline the issue asks for: the ref comes from the setting, so a checkout on
    /// `develop` is reported against `develop` and never against `main`.
    #[test]
    fn the_develop_track_follows_develop_and_never_main() {
        let f = Fixture::new();
        f.follow_develop();
        f.publish_to("develop", "tomorrow's commit");
        f.publish_to("main", "a release that is already out");
        let before = f.head();
        let (verdict, out, _) = f.go_on(CHECK, &SystemRunner, Track::Develop);
        assert_eq!(verdict.unwrap(), Verdict::Behind, "{out}");
        assert!(out.contains("origin/develop"), "{out}");
        assert!(out.contains("tomorrow's commit"), "{out}");
        assert!(
            !out.contains("a release that is already out"),
            "main's commits are not this install's news: {out}"
        );
        assert_eq!(f.head(), before, "--check pulls nothing");
    }

    /// And an upgrade takes exactly that: the merge names the ref, so it cannot pull whatever
    /// the checkout's upstream happens to be.
    #[test]
    fn an_upgrade_on_the_develop_track_fast_forwards_to_develop() {
        let f = Fixture::new();
        f.follow_develop();
        f.publish_to("develop", "tomorrow's commit");
        f.publish_to("main", "a release that is already out");
        let old = f.head();
        let (verdict, out, _) = f.go_on(UPGRADE, &SystemRunner, Track::Develop);
        assert_eq!(verdict.unwrap(), Verdict::Upgraded, "{out}");
        assert!(out.contains("origin/develop"), "{out}");
        assert_ne!(f.head(), old, "the checkout moved");
        assert_eq!(
            sh(&f.ws, "git", &["log", "-1", "--pretty=%s"]),
            "tomorrow's commit",
            "it moved to develop, not to main"
        );
        assert!(f.ws.join("install-calls").exists(), "it rebuilt");
    }

    /// A checkout on a branch the track does not name is refused, not pulled. The branch has an
    /// upstream of its own, which is exactly what `@{u}` used to follow.
    #[test]
    fn a_checkout_on_another_branch_is_refused_instead_of_being_pulled() {
        let f = Fixture::new();
        f.follow_develop();
        f.publish_to("develop", "tomorrow's commit");
        sh(&f.ws, "git", &["fetch", "-q", "origin"]);
        sh(&f.ws, "git", &["checkout", "-q", "-b", "feat/whatever"]);
        sh(
            &f.ws,
            "git",
            &["branch", "--set-upstream-to=origin/develop"],
        );
        let before = f.head();
        let run = Recording::new();
        let msg = refusal(f.go_on(UPGRADE, &run, Track::Develop).0);
        assert!(msg.contains("feat/whatever"), "{msg}");
        assert!(
            msg.contains("`develop`") && msg.contains("switch develop"),
            "the refusal names the track's branch and the command: {msg}"
        );
        assert!(
            !run.ran(" fetch") && !run.ran(" merge") && !run.ran("install.sh"),
            "nothing was fetched, merged or built: {:?}",
            run.calls.borrow()
        );
        assert_eq!(f.head(), before);
    }

    /// The other half of the same rule: the release track does not follow develop either.
    #[test]
    fn the_release_track_refuses_a_checkout_that_is_on_develop() {
        let f = Fixture::new();
        f.follow_develop();
        f.publish_to("develop", "tomorrow's commit");
        let run = Recording::new();
        let msg = refusal(f.go_on(UPGRADE, &run, Track::Release).0);
        assert!(msg.contains("on `develop`"), "{msg}");
        assert!(msg.contains("follows `main`"), "{msg}");
        assert!(
            !run.ran(" fetch") && !run.ran(" merge") && !run.ran("install.sh"),
            "{:?}",
            run.calls.borrow()
        );
    }

    /// A release install has no branch to follow, so the develop track is refused with the
    /// reason instead of answered with a tag from a branch that builds none.
    #[test]
    fn a_release_install_asked_for_the_develop_track_refuses_and_says_why() {
        let f = Fixture::new();
        f.write_marker("release", None, None);
        let run = Recording::new();
        let msg = refusal(f.go_on(UPGRADE, &run, Track::Develop).0);
        assert!(msg.contains("track = \"develop\""), "{msg}");
        assert!(
            msg.contains("tags only"),
            "the refusal says why there is nothing to download: {msg}"
        );
        assert!(
            msg.contains("update.track release"),
            "and how to put it back: {msg}"
        );
        assert!(run.calls.borrow().is_empty(), "nothing ran");
    }

    /// A remote that carries no `develop` has nothing on that track: the refusal names the ref
    /// it looked for rather than pulling one that is not there.
    #[test]
    fn the_develop_track_with_no_origin_develop_names_the_ref_it_could_not_find() {
        let f = Fixture::new();
        sh(&f.ws, "git", &["checkout", "-q", "-b", "develop"]);
        let run = Recording::new();
        let msg = refusal(f.go_on(CHECK, &run, Track::Develop).0);
        assert!(msg.contains("origin/develop"), "{msg}");
        assert!(msg.contains("track"), "{msg}");
        assert!(!run.ran(" merge") && !run.ran("install.sh"));
    }
}