krypt-core 0.2.0

Core engine for the `krypt` dotfiles manager: config, paths, copy, manifest, runner.
Documentation
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
//! Orchestration for `krypt update`.
//!
//! Fetches the dotfiles repo from origin (HTTPS only — gix 0.83 has no SSH
//! transport; see the follow-up issue for the tracking item), fast-forward-
//! advances the local branch, updates the working tree, then re-runs `link`
//! to deploy any new files.
//!
//! A dirty working tree is always an error: commit, stash, or discard changes
//! before running `krypt update`.  Auto-stash was removed pending gix gaining
//! stash support; see the follow-up issue for re-adding it.
//!
//! # HTTPS-only note
//!
//! gix 0.83 does not have an SSH transport, so only HTTPS URLs are supported.
//! SSH-based remote URLs will fail with a connection error from gix.  This
//! limitation will be lifted once gitoxide ships SSH support.

// `UpdateError` wraps gix errors (already boxed) and `ToolConfigError`;
// on Windows the combined enum exceeds clippy's 128-byte threshold.
// The variants are already as compact as the upstream types allow.
#![allow(clippy::result_large_err)]

use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;

use thiserror::Error;

use crate::config::Config;
use crate::deploy::{DeployError, DeployOpts, LinkReport, link};
use crate::predicate::{DefaultPredicateEnv, default_predicate_evaluator, eval};
use crate::runner::{Context, Notifier, ProcessExec, Prompter, RunnerError, execute_hook};
use crate::tool_config::{ToolConfig, ToolConfigError};

// ─── Errors ─────────────────────────────────────────────────────────────────

/// Errors from [`update`].
#[derive(Debug, Error)]
pub enum UpdateError {
    /// Tool config is missing — the user needs to run `krypt init` first.
    #[error("tool config not found at {path:?} — run `krypt init` first")]
    ToolConfigMissing {
        /// Path that was checked.
        path: PathBuf,
    },

    /// Loading the tool config failed.
    #[error("loading tool config: {0}")]
    ToolConfig(#[from] ToolConfigError),

    /// The working tree has uncommitted changes.
    ///
    /// A dirty dotfiles repo before `krypt update` is a smell, not a normal
    /// state.  The right answer is to commit, stash, or discard changes first.
    /// Auto-stash was removed while gix lacks a stash API; when gix ships
    /// stash support the auto-stash flow with a `--no-stash` opt-out will be
    /// restored.
    #[error(
        "working tree has uncommitted changes — commit, stash, or discard them \
         and re-run `krypt update`"
    )]
    DirtyWorkingTree,

    /// Opening the git repository failed.
    #[error("opening git repo at {path:?}: {source}")]
    OpenRepo {
        /// Path that was opened.
        path: PathBuf,
        /// Underlying gix error (boxed to keep the enum variant small).
        #[source]
        source: Box<gix::open::Error>,
    },

    /// Checking dirty status failed.
    #[error("checking git status: {0}")]
    GitStatus(#[source] Box<gix::status::is_dirty::Error>),

    /// No default remote found.
    #[error("no default fetch remote configured in {path:?}")]
    NoRemote {
        /// The repo path.
        path: PathBuf,
    },

    /// Connecting to the remote failed.
    #[error("connecting to remote: {0}")]
    Connect(#[source] Box<gix::remote::connect::Error>),

    /// Preparing the fetch failed.
    #[error("preparing fetch: {0}")]
    PrepareFetch(#[source] Box<gix::remote::fetch::prepare::Error>),

    /// The fetch itself failed.
    #[error("fetching from remote: {0}")]
    Fetch(#[source] Box<gix::remote::fetch::Error>),

    /// HEAD is detached (or the operation that needs HEAD failed).
    #[error("HEAD is detached or could not be resolved — cannot fast-forward")]
    DetachedHead,

    /// No remote-tracking ref found for the local branch.
    #[error("no remote-tracking ref for branch {branch:?}")]
    NoTrackingRef {
        /// The local branch name.
        branch: String,
    },

    /// Computing the merge-base failed (needed for FF check).
    #[error("merge-base computation: {0}")]
    MergeBase(#[source] gix::repository::merge_base::Error),

    /// The remote has commits that are not a fast-forward of the local HEAD.
    #[error("remote is not a fast-forward of local HEAD — cannot pull without merging")]
    NotFastForward,

    /// Advancing the local branch reference failed.
    #[error("advancing local branch ref: {0}")]
    RefEdit(#[source] gix::reference::edit::Error),

    /// Rebuilding the index from the new tree failed.
    #[error("rebuilding index from new commit tree: {0}")]
    IndexFromTree(#[source] gix::repository::index_from_tree::Error),

    /// Checking out the new working-tree state failed.
    #[error("checking out new working tree: {0}")]
    Checkout(#[source] Box<gix::worktree::state::checkout::Error>),

    /// Writing the updated index to disk failed.
    #[error("writing index: {0}")]
    WriteIndex(#[source] gix::index::file::write::Error),

    /// Resolving the checkout options failed.
    #[error("checkout options: {0}")]
    CheckoutOptions(#[source] Box<gix::config::checkout_options::Error>),

    /// Converting the object store to an `Arc` failed.
    #[error("converting object store to Arc: {0}")]
    OdbArc(#[source] std::io::Error),

    /// Peeling a reference to its target OID failed.
    #[error("looking up ref OID: {0}")]
    PeelRef(#[source] gix::reference::peel::Error),

    /// `link` step failed.
    #[error("deploy link: {0}")]
    Deploy(#[from] DeployError),

    /// A post-update hook failed and `ignore_failure` was not set.
    ///
    /// `RunnerError` is boxed to keep the enum variant ≤ 128 bytes on Windows.
    #[error("hook {name:?} failed: {source}")]
    Hook {
        /// The hook's `name` field.
        name: String,
        /// The underlying runner error.
        #[source]
        source: Box<RunnerError>,
    },
}

// ─── Options & report ───────────────────────────────────────────────────────

/// Inputs to [`update`].
///
/// The working tree **must** be clean before calling `update`.  If it is not,
/// [`update`] returns [`UpdateError::DirtyWorkingTree`] immediately.
/// There is no auto-stash option; commit, stash, or discard changes first.
/// Auto-stash will be re-added once gix gains stash support.
pub struct UpdateOpts {
    /// Path to the tool config (`${XDG_CONFIG}/krypt/config.toml`).
    pub tool_config_path: PathBuf,

    /// Override the path to `.krypt.toml`. Defaults to `<repo_path>/.krypt.toml`.
    pub config_path: Option<PathBuf>,

    /// Path for the deployment manifest.
    pub manifest_path: PathBuf,

    /// Pass `dry_run = true` to the link step.
    pub dry_run: bool,

    /// Skip all post-update hooks.
    pub skip_hooks: bool,

    /// Pass `force = true` to the link step.
    pub force: bool,
}

/// Summary of `post-update` hook execution.
#[derive(Debug, Default)]
pub struct HookSummary {
    /// Total `post-update` hooks found in the config.
    pub total: usize,
    /// Hooks successfully run to completion.
    pub ran: usize,
    /// Hooks skipped because `r#if` predicate evaluated false.
    pub skipped_by_predicate: usize,
    /// Hooks skipped because `--skip-hooks` was set.
    pub skipped_by_flag: usize,
    /// Hooks that failed but had `ignore_failure: true`.
    pub failed_ignored: usize,
    /// Set when `--dry-run` was used; `ran`/`skipped` counters stay 0.
    pub dry_run: bool,
}

/// Summary returned by a successful [`update`].
#[derive(Debug)]
pub struct UpdateReport {
    /// Whether `git fetch` advanced the repo (i.e. there were new commits).
    pub pulled: bool,

    /// Report from the `link` step.
    pub link: LinkReport,

    /// Version warning if our binary is older than `[meta] krypt_min`.
    pub version_warning: Option<String>,

    /// Summary of `post-update` hook execution.
    pub hooks: HookSummary,
}

// ─── Implementation ──────────────────────────────────────────────────────────

/// Pull the dotfiles repo and re-deploy.
///
/// Errors immediately if the working tree is dirty.  There is no auto-stash;
/// that feature was removed pending gix gaining stash support.
pub fn update(opts: &UpdateOpts) -> Result<UpdateReport, UpdateError> {
    let tool_cfg = ToolConfig::load(&opts.tool_config_path)?.ok_or_else(|| {
        UpdateError::ToolConfigMissing {
            path: opts.tool_config_path.clone(),
        }
    })?;

    let repo_path = &tool_cfg.repo.path;
    let config_path = opts
        .config_path
        .clone()
        .unwrap_or_else(|| repo_path.join(".krypt.toml"));

    let pulled = gix_ff_pull(repo_path)?;

    let krypt_cfg = crate::include::load_with_includes(&config_path).ok();

    let version_warning = krypt_cfg
        .as_ref()
        .and_then(|c| c.meta.krypt_min.as_deref())
        .and_then(version_warning_if_older);

    let link_report = link(&DeployOpts {
        config_path,
        manifest_path: opts.manifest_path.clone(),
        platform: None,
        dry_run: opts.dry_run,
        force: opts.force,
    })?;

    // Execute post-update hooks using real production dependencies.
    let notifier = crate::notify::AutoNotifier::new(
        krypt_cfg
            .as_ref()
            .and_then(|c| c.meta.notify_backend.as_deref()),
    );
    let mut prompter = crate::runner::RealPrompter;
    let hooks_summary = run_post_update_hooks_inner(
        krypt_cfg.as_ref(),
        opts.skip_hooks,
        opts.dry_run,
        &notifier,
        &mut prompter,
    )?;

    Ok(UpdateReport {
        pulled,
        link: link_report,
        version_warning,
        hooks: hooks_summary,
    })
}

// ─── Hook runner helper ───────────────────────────────────────────────────────

/// Execute `post-update` hooks from `cfg`.
///
/// This inner helper accepts injected dependencies so that tests can supply
/// `MockProcessExec`, `MockNotifier`, and `MockPrompter` without spinning up a
/// full git repo.  Production calls this with real implementations.
///
/// Returns a [`HookSummary`] on success.  If a hook fails and its
/// `ignore_failure` is `false`, returns `Err(UpdateError::Hook { ... })` and
/// stops processing further hooks.
pub(crate) fn run_post_update_hooks_inner(
    cfg: Option<&Config>,
    skip: bool,
    dry_run: bool,
    notifier: &dyn Notifier,
    prompter: &mut dyn Prompter,
) -> Result<HookSummary, UpdateError> {
    run_post_update_hooks_with_exec(
        cfg,
        skip,
        dry_run,
        &crate::runner::RealProcessExec,
        notifier,
        prompter,
    )
}

/// Same as [`run_post_update_hooks_inner`] but additionally accepts an injected
/// `ProcessExec` — the seam that test code uses to inject `MockProcessExec`.
pub(crate) fn run_post_update_hooks_with_exec(
    cfg: Option<&Config>,
    skip: bool,
    dry_run: bool,
    process: &dyn ProcessExec,
    notifier: &dyn Notifier,
    prompter: &mut dyn Prompter,
) -> Result<HookSummary, UpdateError> {
    let Some(cfg) = cfg else {
        return Ok(HookSummary::default());
    };

    // Only post-update hooks today; future phases will add pre-link / post-link / etc.
    let post_update_hooks: Vec<_> = cfg
        .hooks
        .iter()
        .filter(|h| h.when == "post-update")
        .collect();

    let total = post_update_hooks.len();
    let mut summary = HookSummary {
        total,
        dry_run,
        ..Default::default()
    };

    if total == 0 {
        return Ok(summary);
    }

    // Build predicate evaluator with [paths] overrides from config.
    let mut resolver = crate::paths::Resolver::new();
    resolver = resolver.with_overrides(cfg.paths.clone().into_iter().collect());
    let env = DefaultPredicateEnv::with_resolver(resolver);
    let eval_predicate = default_predicate_evaluator(env);

    if skip {
        summary.skipped_by_flag = total;
        return Ok(summary);
    }

    if dry_run {
        // Dry-run: evaluate predicates but don't execute. Print a hook plan.
        println!("hooks (dry-run):");

        // We need a fresh evaluator for each hook's predicate check in dry-run.
        // Re-build it since the closure above moved `env`.
        let mut resolver2 = crate::paths::Resolver::new();
        resolver2 = resolver2.with_overrides(cfg.paths.clone().into_iter().collect());
        let env2 = DefaultPredicateEnv::with_resolver(resolver2);

        for hook in &post_update_hooks {
            let predicate_result = if let Some(ref pred) = hook.r#if {
                match eval(pred, &env2) {
                    Ok(true) => "ok",
                    Ok(false) => "would-skip",
                    Err(_) => "predicate-error",
                }
            } else {
                "ok"
            };
            let run_preview = hook.run.first().map(String::as_str).unwrap_or("<empty>");
            println!(
                "  hook {:?}: {}{}",
                hook.name, predicate_result, run_preview
            );
        }
        // counters stay 0 in dry-run
        return Ok(summary);
    }

    // Live execution.
    let ctx = Context {
        captures: std::collections::BTreeMap::new(),
        args: Vec::new(),
        stdin: None,
    };

    for hook in &post_update_hooks {
        // Evaluate predicate first (skip silently if false).
        if hook
            .r#if
            .as_deref()
            .is_some_and(|pred| !eval_predicate(pred, &ctx))
        {
            summary.skipped_by_predicate += 1;
            continue;
        }

        // Execute the hook.
        match execute_hook(hook, process, notifier, prompter, &eval_predicate) {
            Ok(report) if report.steps_failed_ignored > 0 => {
                // The hook's ignore_failure absorbed the error inside the runner.
                tracing::warn!(
                    hook = %hook.name,
                    "post-update hook failed (ignore_failure = true) — continuing"
                );
                summary.failed_ignored += 1;
            }
            Ok(_) => {
                summary.ran += 1;
            }
            Err(e) => {
                // ignore_failure = false (the runner would have returned Err only then).
                return Err(UpdateError::Hook {
                    name: hook.name.clone(),
                    source: Box::new(e),
                });
            }
        }
    }

    Ok(summary)
}

// ─── Internals ───────────────────────────────────────────────────────────────

/// Open the repo, check it is clean, fetch from origin, and fast-forward the
/// local branch to the remote-tracking commit.
///
/// Returns `true` if new commits were received, `false` if already up to date.
///
/// # Why not shell out to `git pull --ff-only`?
///
/// We use gix as the sole git backend (no process spawning, no libgit2) so
/// the binary has zero runtime dependency on a system `git` and links only
/// rustls — no OpenSSL, no libssh2.  The trade-off is that we must implement
/// the pull logic ourselves:
///
/// 1. `repo.is_dirty()` — bail if uncommitted changes exist.
/// 2. `remote.connect(Fetch).prepare_fetch().receive()` — download new objects
///    and update `refs/remotes/origin/<branch>`.
/// 3. Confirm `merge_base(HEAD, remote_tracking) == HEAD` — i.e. remote is
///    strictly ahead (fast-forward safe).
/// 4. Advance the local branch ref and check out the new tree.
///
/// gix 0.83 has no stash API, so auto-stash was removed; see the follow-up
/// issue to restore it once gitoxide ships stash support.
fn gix_ff_pull(repo_path: &Path) -> Result<bool, UpdateError> {
    let repo = gix::open(repo_path).map_err(|e| UpdateError::OpenRepo {
        path: repo_path.to_path_buf(),
        source: Box::new(e),
    })?;

    // ── 1. Dirty check ───────────────────────────────────────────────────────
    if repo
        .is_dirty()
        .map_err(|e| UpdateError::GitStatus(Box::new(e)))?
    {
        return Err(UpdateError::DirtyWorkingTree);
    }

    // ── 2. Fetch from the default remote ────────────────────────────────────
    let interrupt = AtomicBool::new(false);

    let remote = repo
        .find_default_remote(gix::remote::Direction::Fetch)
        .ok_or_else(|| UpdateError::NoRemote {
            path: repo_path.to_path_buf(),
        })?
        .map_err(|_| UpdateError::NoRemote {
            path: repo_path.to_path_buf(),
        })?;

    remote
        .connect(gix::remote::Direction::Fetch)
        .map_err(|e| UpdateError::Connect(Box::new(e)))?
        .prepare_fetch(gix::progress::Discard, Default::default())
        .map_err(|e| UpdateError::PrepareFetch(Box::new(e)))?
        .receive(gix::progress::Discard, &interrupt)
        .map_err(|e| UpdateError::Fetch(Box::new(e)))?;

    // ── 3. Resolve local branch and remote-tracking ref ──────────────────────
    let head_ref = repo
        .head_ref()
        .map_err(|_| UpdateError::DetachedHead)?
        .ok_or(UpdateError::DetachedHead)?;

    let tracking_name = repo
        .branch_remote_tracking_ref_name(head_ref.name(), gix::remote::Direction::Fetch)
        .ok_or_else(|| UpdateError::NoTrackingRef {
            branch: head_ref.name().shorten().to_string(),
        })?
        .map_err(|_| UpdateError::NoTrackingRef {
            branch: head_ref.name().shorten().to_string(),
        })?;

    let mut tracking_ref =
        repo.find_reference(tracking_name.as_ref())
            .map_err(|_| UpdateError::NoTrackingRef {
                branch: head_ref.name().shorten().to_string(),
            })?;

    let new_oid = tracking_ref
        .peel_to_id()
        .map_err(UpdateError::PeelRef)?
        .detach();

    // ── 4. Already up to date? ───────────────────────────────────────────────
    let head_oid = repo
        .head_id()
        .map_err(|_| UpdateError::DetachedHead)?
        .detach();

    if head_oid == new_oid {
        return Ok(false);
    }

    // ── 5. Fast-forward check ────────────────────────────────────────────────
    //
    // A fast-forward is safe iff the current HEAD is an ancestor of the new
    // remote commit, i.e. merge_base(HEAD, new) == HEAD.
    let base = repo
        .merge_base(head_oid, new_oid)
        .map_err(UpdateError::MergeBase)?
        .detach();

    if base != head_oid {
        return Err(UpdateError::NotFastForward);
    }

    // ── 6. Advance the local branch ref ──────────────────────────────────────
    use gix::refs::{
        Target,
        transaction::{Change, LogChange, PreviousValue, RefEdit, RefLog},
    };

    repo.edit_reference(RefEdit {
        change: Change::Update {
            log: LogChange {
                mode: RefLog::AndReference,
                force_create_reflog: false,
                message: "krypt update: fast-forward".into(),
            },
            expected: PreviousValue::MustExistAndMatch(Target::Object(head_oid)),
            new: Target::Object(new_oid),
        },
        name: head_ref.name().to_owned(),
        deref: false,
    })
    .map_err(UpdateError::RefEdit)?;

    // ── 7. Update the working tree to match the new commit ───────────────────
    //
    // The working tree is guaranteed clean (step 1), so rebuilding the index
    // from the new tree and checking out is equivalent to `git reset --hard`.
    // Files removed from the new tree must be explicitly unlinked: we compare
    // the old and new indices and delete anything that disappeared.
    let new_commit = repo
        .find_object(new_oid)
        .map_err(|_| UpdateError::DetachedHead)?;
    let new_tree = new_commit
        .peel_to_tree()
        .map_err(|_| UpdateError::DetachedHead)?;
    let new_tree_id = new_tree.id;

    // Build new index from new tree (high-level helper on Repository).
    let mut new_index = repo
        .index_from_tree(new_tree_id.as_ref())
        .map_err(UpdateError::IndexFromTree)?;

    let new_paths: std::collections::HashSet<Vec<u8>> = new_index
        .entries()
        .iter()
        .map(|e| {
            let p: &[u8] = e.path(&new_index);
            p.to_vec()
        })
        .collect();

    // Load the previous index to discover deleted files.
    let old_index = repo
        .index_or_load_from_head()
        .map_err(|_| UpdateError::DetachedHead)?;

    let workdir = repo.workdir().ok_or(UpdateError::DetachedHead)?;

    for entry in old_index.entries() {
        let rel: &[u8] = entry.path(&old_index);
        if !new_paths.contains(rel)
            && let Ok(rel_str) = std::str::from_utf8(rel)
        {
            let _ = std::fs::remove_file(workdir.join(std::path::Path::new(rel_str)));
        }
    }

    // Check out the new index into the working directory.
    let checkout_opts = repo
        .checkout_options(gix::worktree::stack::state::attributes::Source::IdMapping)
        .map_err(|e| UpdateError::CheckoutOptions(Box::new(e)))?;

    let interrupt2 = AtomicBool::new(false);
    let files = gix::progress::Discard;
    let bytes = gix::progress::Discard;

    gix::worktree::state::checkout(
        &mut new_index,
        workdir,
        repo.objects
            .clone()
            .into_arc()
            .map_err(UpdateError::OdbArc)?,
        &files,
        &bytes,
        &interrupt2,
        checkout_opts,
    )
    .map_err(|e| UpdateError::Checkout(Box::new(e)))?;

    new_index
        .write(Default::default())
        .map_err(UpdateError::WriteIndex)?;

    Ok(true)
}

/// Returns a warning string when our binary version is older than `min_version`.
fn version_warning_if_older(min_version: &str) -> Option<String> {
    let our_version = env!("CARGO_PKG_VERSION");
    if version_less_than(our_version, min_version) {
        Some(format!(
            "warning: this repo requires krypt >= {min_version}, but you have {our_version}; \
             please upgrade"
        ))
    } else {
        None
    }
}

/// Returns true if `a` is strictly less than `b` using semver-style comparison.
///
/// Parsing failures fall through to lexicographic comparison so the binary
/// never hard-fails on a malformed `krypt_min` value.
fn version_less_than(a: &str, b: &str) -> bool {
    match (parse_version(a), parse_version(b)) {
        (Some(av), Some(bv)) => av < bv,
        _ => a < b,
    }
}

/// Parse a `MAJOR.MINOR.PATCH` string into a comparable tuple.
fn parse_version(v: &str) -> Option<(u64, u64, u64)> {
    let mut parts = v.splitn(3, '.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    let patch = parts
        .next()?
        .trim_end_matches(|c: char| !c.is_ascii_digit())
        .parse()
        .ok()?;
    Some((major, minor, patch))
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runner::{MockNotifier, MockProcessExec, MockPrompter};
    use std::fs;
    use tempfile::tempdir;

    // ── gix test helpers ────────────────────────────────────────────────────

    fn test_sig_raw() -> &'static str {
        // Raw git signature format: "Name <email> seconds tz"
        "Test <test@test.test> 0 +0000"
    }

    /// Write a commit directly via gix's high-level `commit_as` API.
    fn write_commit(repo: &gix::Repository, message: &str, files: &[(&str, &[u8])]) {
        // Build and write blob objects, then build tree.
        let mut tree_entries: Vec<gix::objs::tree::Entry> = files
            .iter()
            .map(|(name, content)| {
                let blob_id = repo.write_blob(content).expect("write blob").detach();
                gix::objs::tree::Entry {
                    mode: gix::objs::tree::EntryKind::Blob.into(),
                    filename: (*name).into(),
                    oid: blob_id,
                }
            })
            .collect();
        tree_entries.sort_by(|a, b| a.filename.cmp(&b.filename));

        let tree = gix::objs::Tree {
            entries: tree_entries,
        };
        let tree_id = repo.write_object(&tree).expect("write tree").detach();

        let sig = gix::actor::SignatureRef::from_bytes(test_sig_raw().as_bytes())
            .expect("valid test sig");
        let parent: Vec<gix::hash::ObjectId> = repo
            .head_id()
            .ok()
            .map(|id| id.detach())
            .into_iter()
            .collect();

        // commit_as updates HEAD automatically (deref through symbolic HEAD).
        repo.commit_as(sig, sig, "HEAD", message, tree_id, parent)
            .expect("write commit");
    }

    /// Init a new repo with a single empty commit.
    fn init_with_commit(dir: &Path) -> gix::Repository {
        let repo = gix::init(dir).expect("gix::init");
        write_commit(&repo, "initial", &[]);
        repo
    }

    fn make_tool_config(repo_path: &Path, tc_dir: &tempfile::TempDir) -> PathBuf {
        let tc_path = tc_dir.path().join("krypt").join("config.toml");
        let cfg = crate::tool_config::ToolConfig {
            repo: crate::tool_config::RepoConfig {
                path: repo_path.to_path_buf(),
                url: None,
            },
        };
        cfg.save(&tc_path).unwrap();
        tc_path
    }

    // ── Hook helper tests (no full git setup needed) ─────────────────────────

    fn make_cfg_with_hooks(toml: &str) -> Config {
        toml::from_str(toml).expect("parse config")
    }

    // ── 1. No hooks ──────────────────────────────────────────────────────────

    #[test]
    fn no_hooks_returns_zero_summary() {
        let cfg = make_cfg_with_hooks("");
        let notifier = MockNotifier::default();
        let mut prompter = MockPrompter::default();

        let summary = run_post_update_hooks_with_exec(
            Some(&cfg),
            false,
            false,
            &MockProcessExec::new([]),
            &notifier,
            &mut prompter,
        )
        .unwrap();

        assert_eq!(summary.total, 0);
        assert_eq!(summary.ran, 0);
        assert_eq!(summary.skipped_by_predicate, 0);
        assert_eq!(summary.skipped_by_flag, 0);
        assert_eq!(summary.failed_ignored, 0);
        assert!(!summary.dry_run);
    }

    // ── 2. One hook, succeeds ────────────────────────────────────────────────

    #[test]
    fn one_hook_succeeds() {
        use crate::runner::ProcessResult;

        let cfg = make_cfg_with_hooks(
            r#"
[[hook]]
name = "my-hook"
when = "post-update"
run  = ["echo", "hi"]
"#,
        );

        let process = MockProcessExec::new([Ok(ProcessResult {
            status: 0,
            stdout: "hi\n".to_owned(),
            stderr: String::new(),
        })]);
        let notifier = MockNotifier::default();
        let mut prompter = MockPrompter::default();

        let summary = run_post_update_hooks_with_exec(
            Some(&cfg),
            false,
            false,
            &process,
            &notifier,
            &mut prompter,
        )
        .unwrap();

        assert_eq!(summary.total, 1);
        assert_eq!(summary.ran, 1);
        assert_eq!(summary.skipped_by_predicate, 0);
        assert_eq!(summary.failed_ignored, 0);
        // Verify the process was actually called.
        let calls = process.calls.borrow();
        assert_eq!(calls[0].0, "echo");
    }

    // ── 3. Predicate false → skipped_by_predicate ────────────────────────────

    #[test]
    fn hook_with_false_predicate_skipped() {
        // Use `env:KRYPT_TEST_IMPOSSIBLE_VAR_NEVER_SET` — an env var that is
        // guaranteed not to exist on any CI runner, so the predicate is always
        // false on Linux, macOS, and Windows alike.
        let cfg = make_cfg_with_hooks(
            r#"
[[hook]]
name  = "impossible-env"
when  = "post-update"
if    = "env:KRYPT_TEST_IMPOSSIBLE_VAR_NEVER_SET"
run   = ["echo", "nope"]
"#,
        );

        let process = MockProcessExec::new([]);
        let notifier = MockNotifier::default();
        let mut prompter = MockPrompter::default();

        let summary = run_post_update_hooks_with_exec(
            Some(&cfg),
            false,
            false,
            &process,
            &notifier,
            &mut prompter,
        )
        .unwrap();

        assert_eq!(summary.total, 1);
        assert_eq!(summary.ran, 0);
        assert_eq!(summary.skipped_by_predicate, 1);
        // Process must never have been called.
        assert!(process.calls.borrow().is_empty());
    }

    // ── 4. Hook fails, ignore_failure = true → failed_ignored ────────────────

    #[test]
    fn hook_fails_ignore_failure_true_continues() {
        use crate::runner::ProcessResult;

        let cfg = make_cfg_with_hooks(
            r#"
[[hook]]
name           = "lenient"
when           = "post-update"
run            = ["false-cmd"]
ignore_failure = true
"#,
        );

        let process = MockProcessExec::new([Ok(ProcessResult {
            status: 1,
            stdout: String::new(),
            stderr: "error".to_owned(),
        })]);
        let notifier = MockNotifier::default();
        let mut prompter = MockPrompter::default();

        let result = run_post_update_hooks_with_exec(
            Some(&cfg),
            false,
            false,
            &process,
            &notifier,
            &mut prompter,
        );

        let summary = result.expect("should return Ok despite hook failure");
        assert_eq!(summary.failed_ignored, 1);
        assert_eq!(summary.ran, 0);
    }

    // ── 5. Hook fails, ignore_failure = false → Err(UpdateError::Hook) ───────

    #[test]
    fn hook_fails_ignore_failure_false_returns_err() {
        use crate::runner::ProcessResult;

        let cfg = make_cfg_with_hooks(
            r#"
[[hook]]
name = "strict"
when = "post-update"
run  = ["bad-cmd"]
"#,
        );

        let process = MockProcessExec::new([Ok(ProcessResult {
            status: 1,
            stdout: String::new(),
            stderr: "boom".to_owned(),
        })]);
        let notifier = MockNotifier::default();
        let mut prompter = MockPrompter::default();

        let err = run_post_update_hooks_with_exec(
            Some(&cfg),
            false,
            false,
            &process,
            &notifier,
            &mut prompter,
        )
        .unwrap_err();

        assert!(
            matches!(&err, UpdateError::Hook { name, .. } if name == "strict"),
            "expected UpdateError::Hook {{ name: \"strict\", .. }}, got {err:?}"
        );
    }

    // ── 6. --skip-hooks → skipped_by_flag == total ───────────────────────────

    #[test]
    fn skip_hooks_flag_skips_all() {
        let cfg = make_cfg_with_hooks(
            r#"
[[hook]]
name = "h1"
when = "post-update"
run  = ["echo", "one"]

[[hook]]
name = "h2"
when = "post-update"
run  = ["echo", "two"]
"#,
        );

        let process = MockProcessExec::new([]);
        let notifier = MockNotifier::default();
        let mut prompter = MockPrompter::default();

        let summary = run_post_update_hooks_with_exec(
            Some(&cfg),
            true, // skip = true
            false,
            &process,
            &notifier,
            &mut prompter,
        )
        .unwrap();

        assert_eq!(summary.total, 2);
        assert_eq!(summary.skipped_by_flag, 2);
        assert_eq!(summary.ran, 0);
        // Process must never have been called.
        assert!(process.calls.borrow().is_empty());
    }

    // ── 7. --dry-run → HookSummary.dry_run = true, counters = 0 ─────────────

    #[test]
    fn dry_run_sets_flag_no_execution() {
        let cfg = make_cfg_with_hooks(
            r#"
[[hook]]
name = "deploy"
when = "post-update"
run  = ["echo", "deploying"]
"#,
        );

        let process = MockProcessExec::new([]);
        let notifier = MockNotifier::default();
        let mut prompter = MockPrompter::default();

        let summary = run_post_update_hooks_with_exec(
            Some(&cfg),
            false,
            true, // dry_run = true
            &process,
            &notifier,
            &mut prompter,
        )
        .unwrap();

        assert!(summary.dry_run);
        assert_eq!(summary.ran, 0);
        assert_eq!(summary.skipped_by_predicate, 0);
        assert_eq!(summary.skipped_by_flag, 0);
        assert_eq!(summary.failed_ignored, 0);
        // No process spawned.
        assert!(process.calls.borrow().is_empty());
    }

    // ── Tests ────────────────────────────────────────────────────────────────

    /// A modified index entry (tree-vs-index mismatch) causes `DirtyWorkingTree`.
    ///
    /// gix's `is_dirty()` does not flag *untracked* files (matching git's
    /// `--ignore-untracked` semantics).  For a dotfiles repo this is correct:
    /// a stray untracked file in the repo root should not block a pull.
    ///
    /// We trigger a tree-vs-index mismatch by staging a blob that is different
    /// from what the HEAD commit contains.
    #[test]
    fn dirty_tree_always_errors() {
        let local = tempdir().unwrap();

        // Commit a tracked file.
        write_commit(
            &init_with_commit(local.path()),
            "add file",
            &[("tracked.txt", b"original")],
        );

        // Make the index dirty: write the file with different content to disk
        // AND update the index to point to a blob with different content than
        // the HEAD tree has.  We do this by staging via gix's index APIs.
        //
        // The simplest approach: after commit, the index (if it exists on disk)
        // should match HEAD.  We rebuild it from the current HEAD tree, then
        // write different content to disk so that the index SHA != worktree SHA.
        {
            let repo = gix::open(local.path()).expect("open");
            let head_tree_id = repo
                .head_commit()
                .expect("head commit")
                .tree_id()
                .expect("tree");
            let mut idx = repo
                .index_from_tree(head_tree_id.as_ref())
                .expect("index from tree");
            // Write the index to disk so gix can compare it with the worktree.
            idx.write(Default::default()).expect("write index");
        }
        // Now modify the file on disk so it differs from what the index records.
        fs::write(local.path().join("tracked.txt"), b"modified").unwrap();

        let tc_dir = tempdir().unwrap();
        let tc_path = make_tool_config(local.path(), &tc_dir);
        let state = tempdir().unwrap();

        let err = update(&UpdateOpts {
            tool_config_path: tc_path,
            config_path: Some(local.path().join(".krypt.toml")),
            manifest_path: state.path().join("manifest.json"),
            dry_run: false,
            skip_hooks: false,
            force: false,
        })
        .unwrap_err();

        assert!(
            matches!(err, UpdateError::DirtyWorkingTree),
            "expected DirtyWorkingTree, got {err:?}"
        );
    }

    #[test]
    fn tool_config_missing_gives_clear_error() {
        let tc_dir = tempdir().unwrap();
        let tc_path = tc_dir.path().join("nonexistent.toml");
        let state = tempdir().unwrap();

        let err = update(&UpdateOpts {
            tool_config_path: tc_path.clone(),
            config_path: None,
            manifest_path: state.path().join("manifest.json"),
            dry_run: false,
            skip_hooks: false,
            force: false,
        })
        .unwrap_err();

        assert!(
            matches!(err, UpdateError::ToolConfigMissing { ref path } if path == &tc_path),
            "expected ToolConfigMissing, got {err:?}"
        );
    }

    #[test]
    fn version_warning_fires_when_older() {
        assert!(version_less_than("0.0.2", "99.0.0"));
        let warn = version_warning_if_older("99.0.0");
        assert!(warn.is_some());
        assert!(warn.unwrap().contains("99.0.0"));
    }

    #[test]
    fn version_warning_absent_when_current() {
        let our = env!("CARGO_PKG_VERSION");
        assert!(version_warning_if_older(our).is_none());
    }

    #[test]
    fn parse_version_basic() {
        assert_eq!(parse_version("1.2.3"), Some((1, 2, 3)));
        assert_eq!(parse_version("0.0.0"), Some((0, 0, 0)));
        assert!(parse_version("bad").is_none());
    }
}