sley 0.3.0

Ergonomic facade over the sley engine, a native-Rust reimplementation of Git's plumbing.
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
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
//! Source-aware config snapshots and byte-preserving edit plans.

use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

use sley_config::raw_edit::{
    ConfigFileWriteError, ConfigFileWriteOptions, RawConfigEditor, RawEditOutcome,
    SectionEditOutcome, rename_or_remove_section, write_config_file_locked,
};
use sley_config::{ConfigOriginKind, ConfigScope, ConfigStack};

use crate::{GitError, Repository};

/// One config value with the physical source it was read from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigValue {
    /// Canonical `section[.subsection].name`.
    pub key: String,
    /// Parsed value. `None` represents a bare boolean-true key.
    pub value: Option<String>,
    /// Scope/source metadata suitable for deciding whether the value can be edited.
    pub source: ConfigSource,
}

/// A flattened effective config stream, lowest precedence first.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ConfigSnapshot {
    pub values: Vec<ConfigValue>,
}

impl ConfigSnapshot {
    /// Highest-precedence value for `key`.
    pub fn get(&self, key: &str) -> Result<Option<&ConfigValue>, ConfigEditError> {
        let key = ParsedConfigKey::parse(key)?;
        Ok(self.values.iter().rev().find(|value| value.key == key.full))
    }

    /// All values for `key`, in precedence order.
    pub fn get_all(&self, key: &str) -> Result<Vec<&ConfigValue>, ConfigEditError> {
        let key = ParsedConfigKey::parse(key)?;
        Ok(self
            .values
            .iter()
            .filter(|value| value.key == key.full)
            .collect())
    }
}

/// Worktree config inclusion policy for [`ConfigStackOptions`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WorktreeConfig {
    Never,
    Always,
    WhenEnabled,
}

/// Options for building an effective, source-attributed Git config stack.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConfigStackOptions {
    follow_includes: bool,
    worktree_config: WorktreeConfig,
    track_origins: bool,
}

impl ConfigStackOptions {
    /// Git's repository config behavior: follow includes and include worktree
    /// config only when `extensions.worktreeConfig` enables it.
    pub fn git_default() -> Self {
        Self {
            follow_includes: true,
            worktree_config: WorktreeConfig::WhenEnabled,
            track_origins: true,
        }
    }

    pub fn follow_includes(mut self, follow_includes: bool) -> Self {
        self.follow_includes = follow_includes;
        self
    }

    pub fn worktree_config(mut self, worktree_config: WorktreeConfig) -> Self {
        self.worktree_config = worktree_config;
        self
    }

    pub fn track_origins(mut self, track_origins: bool) -> Self {
        self.track_origins = track_origins;
        self
    }

    pub fn includes_followed(self) -> bool {
        self.follow_includes
    }

    pub fn worktree_config_policy(self) -> WorktreeConfig {
        self.worktree_config
    }

    pub fn origins_tracked(self) -> bool {
        self.track_origins
    }
}

impl Default for ConfigStackOptions {
    fn default() -> Self {
        Self::git_default()
    }
}

/// Stable id for a source-backed logical config section in a
/// [`ConfigStackView`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ConfigSectionId(usize);

/// A source-attributed effective config stack with helper lookups for remotes.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ConfigStackView {
    pub values: ConfigSnapshot,
    pub remotes: RemoteConfigSnapshot,
    section_sources: Vec<RemoteConfigSource>,
}

impl ConfigStackView {
    pub fn values(&self) -> &ConfigSnapshot {
        &self.values
    }

    pub fn remotes(&self) -> &RemoteConfigSnapshot {
        &self.remotes
    }

    /// Return a configured remote with the source section selected for editing.
    pub fn remote(&self, name: &str) -> Result<ConfigRemote, ConfigEditError> {
        let Some(remote) = self.remotes.get(name).cloned() else {
            return Err(ConfigEditError::SectionNotFound {
                section: "remote".to_string(),
                subsection: Some(name.to_string()),
            });
        };
        let Some(source) = remote.sources.last().cloned() else {
            return Err(ConfigEditError::NoEditableSource);
        };
        let section_id = self
            .section_sources
            .iter()
            .position(|candidate| candidate == &source)
            .ok_or(ConfigEditError::NoEditableSource)?;
        Ok(ConfigRemote {
            remote,
            section_id: ConfigSectionId(section_id),
        })
    }

    /// Physical file that can safely edit the section identified by `section_id`.
    pub fn editable_section_file(
        &self,
        section_id: ConfigSectionId,
    ) -> Result<PathBuf, ConfigEditError> {
        let source = self
            .section_sources
            .get(section_id.0)
            .ok_or(ConfigEditError::NoEditableSource)?;
        if source.editable
            && let Some(path) = &source.target_path
        {
            return Ok(path.clone());
        }
        match &source.refusal {
            Some(RemoteConfigRefusal::ExternalInclude { path }) => {
                Err(ConfigEditError::RefusesExternalInclude { path: path.clone() })
            }
            Some(RemoteConfigRefusal::SyntheticSource) | None => {
                Err(ConfigEditError::NoEditableSource)
            }
        }
    }
}

/// A remote returned from [`ConfigStackView::remote`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigRemote {
    remote: RemoteConfig,
    section_id: ConfigSectionId,
}

impl ConfigRemote {
    pub fn section_id(&self) -> ConfigSectionId {
        self.section_id
    }

    pub fn remote(&self) -> &RemoteConfig {
        &self.remote
    }

    pub fn name(&self) -> &str {
        &self.remote.name
    }
}

/// Source-attributed remote configuration, lowest precedence first.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RemoteConfigSnapshot {
    pub remotes: Vec<RemoteConfig>,
}

impl RemoteConfigSnapshot {
    pub fn get(&self, name: &str) -> Option<&RemoteConfig> {
        self.remotes.iter().find(|remote| remote.name == name)
    }
}

/// One logical `[remote "<name>"]` assembled from the effective config stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteConfig {
    pub name: String,
    pub values: Vec<RemoteConfigValue>,
    pub sources: Vec<RemoteConfigSource>,
}

impl RemoteConfig {
    pub fn urls(&self) -> Vec<&str> {
        self.values_for("url")
    }

    pub fn push_urls(&self) -> Vec<&str> {
        self.values_for("pushurl")
    }

    pub fn fetch_refspecs(&self) -> Vec<&str> {
        self.values_for("fetch")
    }

    pub fn values_for(&self, name: &str) -> Vec<&str> {
        self.values
            .iter()
            .filter(|value| value.name.eq_ignore_ascii_case(name))
            .filter_map(|value| value.value.as_deref())
            .collect()
    }
}

/// One key/value inside a remote section with its physical source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteConfigValue {
    pub name: String,
    pub value: Option<String>,
    pub source: ConfigSource,
}

/// A physical source contributing to a remote, plus editability metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteConfigSource {
    pub source: ConfigSource,
    pub editable: bool,
    pub target_path: Option<PathBuf>,
    pub refusal: Option<RemoteConfigRefusal>,
}

/// Why a remote source cannot be edited by default.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RemoteConfigRefusal {
    ExternalInclude { path: PathBuf },
    SyntheticSource,
}

/// The physical or synthetic origin of a config value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigSource {
    Local {
        path: PathBuf,
    },
    Worktree {
        path: PathBuf,
    },
    Global {
        path: PathBuf,
    },
    System {
        path: PathBuf,
    },
    Included {
        path: PathBuf,
        included_from: Option<PathBuf>,
    },
    Env,
    CommandLine,
    Blob {
        spec: String,
    },
    Stdin,
}

/// Scope/target selection for planning a config edit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigEditScope {
    /// Edit `<common_git_dir>/config`.
    Local,
    /// Edit `<git_dir>/config.worktree`.
    Worktree,
    /// Edit the highest-precedence global config file discovered for this process.
    Global,
    /// Edit the system config file discovered for this process.
    System,
    /// Edit the highest-precedence existing value's physical source.
    ExistingValue { allow_external_includes: bool },
    /// Edit an explicit physical path.
    Path(PathBuf),
}

/// A byte-preserving edit plan for one physical config file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigEditPlan {
    pub target_path: PathBuf,
    pub operations: Vec<ConfigEdit>,
    pub fsync: bool,
}

impl ConfigEditPlan {
    pub fn new(target_path: impl Into<PathBuf>) -> Self {
        Self {
            target_path: target_path.into(),
            operations: Vec::new(),
            fsync: false,
        }
    }

    pub fn with_operation(mut self, operation: ConfigEdit) -> Self {
        self.operations.push(operation);
        self
    }

    pub fn with_fsync(mut self, fsync: bool) -> Self {
        self.fsync = fsync;
        self
    }
}

/// One key/value written into a config section operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigSectionEntry {
    pub name: String,
    pub value: Option<String>,
}

impl ConfigSectionEntry {
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: Some(value.into()),
        }
    }

    pub fn bare(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: None,
        }
    }
}

/// One edit within a [`ConfigEditPlan`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigEdit {
    Set {
        section: String,
        subsection: Option<String>,
        name: String,
        value: String,
    },
    Unset {
        section: String,
        subsection: Option<String>,
        name: String,
    },
    ReplaceSection {
        section: String,
        subsection: Option<String>,
        entries: Vec<ConfigSectionEntry>,
    },
    RemoveSection {
        section: String,
        subsection: Option<String>,
    },
}

impl ConfigEdit {
    pub fn set(key: &str, value: impl Into<String>) -> Result<Self, ConfigEditError> {
        let key = ParsedConfigKey::parse(key)?;
        Ok(Self::Set {
            section: key.section,
            subsection: key.subsection,
            name: key.name,
            value: value.into(),
        })
    }

    pub fn unset(key: &str) -> Result<Self, ConfigEditError> {
        let key = ParsedConfigKey::parse(key)?;
        Ok(Self::Unset {
            section: key.section,
            subsection: key.subsection,
            name: key.name,
        })
    }

    pub fn replace_section(
        section: impl Into<String>,
        subsection: Option<String>,
        entries: Vec<ConfigSectionEntry>,
    ) -> Self {
        Self::ReplaceSection {
            section: section.into(),
            subsection,
            entries,
        }
    }

    pub fn remove_section(section: impl Into<String>, subsection: Option<String>) -> Self {
        Self::RemoveSection {
            section: section.into(),
            subsection,
        }
    }
}

/// A whole-section replacement for `[remote "<name>"]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteConfigSet {
    pub name: String,
    pub entries: Vec<ConfigSectionEntry>,
}

impl RemoteConfigSet {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            entries: Vec::new(),
        }
    }

    pub fn with_entry(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.entries.push(ConfigSectionEntry::new(name, value));
        self
    }

    pub fn with_url(self, url: impl Into<String>) -> Self {
        self.with_entry("url", url)
    }

    pub fn with_push_url(self, url: impl Into<String>) -> Self {
        self.with_entry("pushurl", url)
    }

    pub fn with_fetch_refspec(self, refspec: impl Into<String>) -> Self {
        self.with_entry("fetch", refspec)
    }
}

/// A whole-section removal for `[remote "<name>"]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteConfigRemove {
    pub name: String,
}

impl RemoteConfigRemove {
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }
}

/// Source-aware config planning/apply errors.
#[derive(Debug)]
pub enum ConfigEditError {
    NoEditableSource,
    AmbiguousSource(Vec<ConfigSource>),
    RefusesExternalInclude {
        path: PathBuf,
    },
    IncludeIfNotSatisfied,
    SectionNotFound {
        section: String,
        subsection: Option<String>,
    },
    Parse(String),
    Locked {
        path: PathBuf,
    },
    Io(std::io::Error),
}

impl fmt::Display for ConfigEditError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoEditableSource => f.write_str("no editable config source"),
            Self::AmbiguousSource(sources) => {
                write!(f, "ambiguous config source among {} sources", sources.len())
            }
            Self::RefusesExternalInclude { path } => {
                write!(
                    f,
                    "refusing to edit external included config {}",
                    path.display()
                )
            }
            Self::IncludeIfNotSatisfied => f.write_str("includeIf condition is not satisfied"),
            Self::SectionNotFound {
                section,
                subsection,
            } => match subsection {
                Some(subsection) => {
                    write!(f, "config section not found: {section}.{subsection}")
                }
                None => write!(f, "config section not found: {section}"),
            },
            Self::Parse(message) => write!(f, "config parse error: {message}"),
            Self::Locked { path } => write!(f, "config lock already exists: {}", path.display()),
            Self::Io(err) => write!(f, "io error: {err}"),
        }
    }
}

impl std::error::Error for ConfigEditError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(err) => Some(err),
            _ => None,
        }
    }
}

impl Repository {
    /// Return the effective config as a source-attributed flat stream.
    pub fn config_with_sources(&self) -> Result<ConfigSnapshot, ConfigEditError> {
        let stack = self.config_stack_with_sources()?;
        Ok(self.config_snapshot_from_stack(stack))
    }

    /// Build an effective Git config stack with editable-origin metadata.
    pub fn config_stack(
        &self,
        options: ConfigStackOptions,
    ) -> Result<ConfigStackView, ConfigEditError> {
        let stack = self.config_stack_with_options(options)?;
        let values = self.config_snapshot_from_stack(stack.clone());
        let remotes = self.remote_config_snapshot_from_stack(stack);
        let mut section_sources = Vec::new();
        for remote in &remotes.remotes {
            for source in &remote.sources {
                if !section_sources.contains(source) {
                    section_sources.push(source.clone());
                }
            }
        }
        Ok(ConfigStackView {
            values,
            remotes,
            section_sources,
        })
    }

    fn config_snapshot_from_stack(&self, stack: ConfigStack) -> ConfigSnapshot {
        let bases = ConfigSourceBases::for_repository(self);
        let values = stack
            .entries
            .into_iter()
            .map(|entry| ConfigValue {
                key: config_entry_key(&entry.section, entry.subsection.as_deref(), &entry.key),
                value: entry.value,
                source: bases.source_for(entry.scope, &entry.origin, entry.included_from.as_ref()),
            })
            .collect();
        ConfigSnapshot { values }
    }

    /// Return configured remotes with physical source and editability metadata.
    pub fn remote_config_with_sources(&self) -> Result<RemoteConfigSnapshot, ConfigEditError> {
        let stack = self.config_stack_with_sources()?;
        Ok(self.remote_config_snapshot_from_stack(stack))
    }

    fn remote_config_snapshot_from_stack(&self, stack: ConfigStack) -> RemoteConfigSnapshot {
        let bases = ConfigSourceBases::for_repository(self);
        let mut remotes: Vec<RemoteConfig> = Vec::new();
        for entry in stack.entries {
            if !entry.section.eq_ignore_ascii_case("remote") {
                continue;
            }
            let Some(remote_name) = entry.subsection else {
                continue;
            };
            let source = bases.source_for(entry.scope, &entry.origin, entry.included_from.as_ref());
            let value = RemoteConfigValue {
                name: entry.key,
                value: entry.value,
                source: source.clone(),
            };
            let idx = match remotes.iter().position(|remote| remote.name == remote_name) {
                Some(idx) => idx,
                None => {
                    remotes.push(RemoteConfig {
                        name: remote_name.clone(),
                        values: Vec::new(),
                        sources: Vec::new(),
                    });
                    remotes.len() - 1
                }
            };
            let remote = &mut remotes[idx];
            if !remote.sources.iter().any(|item| item.source == source) {
                remote.sources.push(self.remote_source_metadata(source));
            }
            remote.values.push(value);
        }
        RemoteConfigSnapshot { remotes }
    }

    /// Plan the physical config file that should be edited for `key` and `scope`.
    ///
    /// The returned plan has no operations; callers may add operations directly
    /// or use [`Repository::plan_config_set`] / [`Repository::plan_config_unset`].
    pub fn plan_config_edit(
        &self,
        key: &str,
        scope: ConfigEditScope,
    ) -> Result<ConfigEditPlan, ConfigEditError> {
        let key = ParsedConfigKey::parse(key)?;
        let target_path = self.config_edit_target_path(&key, scope)?;
        Ok(ConfigEditPlan::new(target_path))
    }

    /// Plan a `set` operation for `key`.
    pub fn plan_config_set(
        &self,
        key: &str,
        value: impl Into<String>,
        scope: ConfigEditScope,
    ) -> Result<ConfigEditPlan, ConfigEditError> {
        Ok(self
            .plan_config_edit(key, scope)?
            .with_operation(ConfigEdit::set(key, value)?))
    }

    /// Plan an `unset` operation for `key`.
    pub fn plan_config_unset(
        &self,
        key: &str,
        scope: ConfigEditScope,
    ) -> Result<ConfigEditPlan, ConfigEditError> {
        Ok(self
            .plan_config_edit(key, scope)?
            .with_operation(ConfigEdit::unset(key)?))
    }

    /// Plan a whole-section replacement for `[remote "<name>"]`.
    ///
    /// The applied edit removes every matching remote section from the selected
    /// physical config file and appends one canonical replacement section.
    pub fn plan_remote_set(
        &self,
        set: RemoteConfigSet,
        scope: ConfigEditScope,
    ) -> Result<ConfigEditPlan, ConfigEditError> {
        validate_remote_name(&set.name)?;
        validate_section_entries("remote", Some(&set.name), &set.entries)?;
        let target_path = self.remote_config_edit_target_path(&set.name, scope)?;
        Ok(
            ConfigEditPlan::new(target_path).with_operation(ConfigEdit::replace_section(
                "remote",
                Some(set.name),
                set.entries,
            )),
        )
    }

    /// Plan removal of all `[remote "<name>"]` sections in the selected file.
    pub fn plan_remote_remove(
        &self,
        remove: RemoteConfigRemove,
        scope: ConfigEditScope,
    ) -> Result<ConfigEditPlan, ConfigEditError> {
        validate_remote_name(&remove.name)?;
        let target_path = self.remote_config_edit_target_path(&remove.name, scope)?;
        Ok(ConfigEditPlan::new(target_path)
            .with_operation(ConfigEdit::remove_section("remote", Some(remove.name))))
    }

    /// Apply a config edit plan through `<target>.lock` and atomic rename.
    pub fn apply_config_edit_plan(&self, plan: ConfigEditPlan) -> Result<(), ConfigEditError> {
        if plan.operations.is_empty() {
            return Ok(());
        }
        let mut contents = match fs::read(&plan.target_path) {
            Ok(bytes) => bytes,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Vec::new(),
            Err(err) => return Err(ConfigEditError::Io(err)),
        };
        for operation in plan.operations {
            let (section, subsection, name, value) = match operation {
                ConfigEdit::Set {
                    section,
                    subsection,
                    name,
                    value,
                } => (section, subsection, name, Some(value)),
                ConfigEdit::Unset {
                    section,
                    subsection,
                    name,
                } => (section, subsection, name, None),
                ConfigEdit::ReplaceSection {
                    section,
                    subsection,
                    entries,
                } => {
                    contents =
                        replace_section(contents, &section, subsection.as_deref(), &entries)?;
                    continue;
                }
                ConfigEdit::RemoveSection {
                    section,
                    subsection,
                } => {
                    contents = remove_section(contents, &section, subsection.as_deref())?;
                    continue;
                }
            };
            let mut editor = RawConfigEditor::new(contents, &section, subsection.as_deref(), &name);
            match editor.set_multivar(value.as_deref(), None, None, true) {
                RawEditOutcome::Changed => contents = editor.into_bytes(),
                RawEditOutcome::NothingSet => return Err(ConfigEditError::NoEditableSource),
            }
        }
        write_config_file_locked(
            &plan.target_path,
            &contents,
            ConfigFileWriteOptions { fsync: plan.fsync },
        )
        .map_err(ConfigEditError::from_config_write)
    }

    fn config_stack_with_sources(&self) -> Result<ConfigStack, ConfigEditError> {
        self.config_stack_with_options(ConfigStackOptions::git_default())
    }

    fn config_stack_with_options(
        &self,
        options: ConfigStackOptions,
    ) -> Result<ConfigStack, ConfigEditError> {
        let context = sley_config::ConfigIncludeContext::new(
            Some(self.config_include_git_dir()),
            self.config_include_branch(),
        );
        let mut stack = ConfigStack::new();
        for (path, scope) in sley_config::default_config_layer_paths() {
            stack
                .push_file(&path, scope, options.follow_includes, &context)
                .map_err(ConfigEditError::from_git_error)?;
        }
        stack
            .push_file(
                &self.common_dir().join("config"),
                ConfigScope::Local,
                options.follow_includes,
                &context,
            )
            .map_err(ConfigEditError::from_git_error)?;
        let include_worktree = match options.worktree_config {
            WorktreeConfig::Never => false,
            WorktreeConfig::Always => true,
            WorktreeConfig::WhenEnabled => self.worktree_config_enabled()?,
        };
        if include_worktree {
            stack
                .push_file(
                    &self.git_dir().join("config.worktree"),
                    ConfigScope::Worktree,
                    options.follow_includes,
                    &context,
                )
                .map_err(ConfigEditError::from_git_error)?;
        }
        Ok(stack)
    }

    fn worktree_config_enabled(&self) -> Result<bool, ConfigEditError> {
        let path = self.common_dir().join("config");
        match crate::GitConfig::read(&path) {
            Ok(config) => Ok(config
                .get_bool("extensions", None, "worktreeConfig")
                .unwrap_or(false)),
            Err(GitError::Io(_)) | Err(GitError::NotFound(_)) => Ok(false),
            Err(err) => Err(ConfigEditError::from_git_error(err)),
        }
    }

    fn config_edit_target_path(
        &self,
        key: &ParsedConfigKey,
        scope: ConfigEditScope,
    ) -> Result<PathBuf, ConfigEditError> {
        match scope {
            ConfigEditScope::Local => Ok(self.common_dir().join("config")),
            ConfigEditScope::Worktree => Ok(self.git_dir().join("config.worktree")),
            ConfigEditScope::Global => sley_config::default_config_layer_paths()
                .into_iter()
                .filter_map(|(path, scope)| (scope == ConfigScope::Global).then_some(path))
                .next_back()
                .ok_or(ConfigEditError::NoEditableSource),
            ConfigEditScope::System => sley_config::default_config_layer_paths()
                .into_iter()
                .find_map(|(path, scope)| (scope == ConfigScope::System).then_some(path))
                .ok_or(ConfigEditError::NoEditableSource),
            ConfigEditScope::Path(path) => Ok(path),
            ConfigEditScope::ExistingValue {
                allow_external_includes,
            } => {
                let snapshot = self.config_with_sources()?;
                let Some(value) = snapshot
                    .values
                    .iter()
                    .rev()
                    .find(|value| value.key == key.full)
                else {
                    return Err(ConfigEditError::NoEditableSource);
                };
                self.edit_path_for_source(&value.source, allow_external_includes)
            }
        }
    }

    fn remote_config_edit_target_path(
        &self,
        name: &str,
        scope: ConfigEditScope,
    ) -> Result<PathBuf, ConfigEditError> {
        match scope {
            ConfigEditScope::ExistingValue {
                allow_external_includes,
            } => {
                let stack = self.config_stack_with_sources()?;
                let bases = ConfigSourceBases::for_repository(self);
                for entry in stack.entries.iter().rev() {
                    if entry.section.eq_ignore_ascii_case("remote")
                        && entry.subsection.as_deref() == Some(name)
                    {
                        let source = bases.source_for(
                            entry.scope,
                            &entry.origin,
                            entry.included_from.as_ref(),
                        );
                        return self.edit_path_for_source(&source, allow_external_includes);
                    }
                }
                Err(ConfigEditError::NoEditableSource)
            }
            other => {
                let key = ParsedConfigKey::parse(&format!("remote.{name}.url"))?;
                self.config_edit_target_path(&key, other)
            }
        }
    }

    fn edit_path_for_source(
        &self,
        source: &ConfigSource,
        allow_external_includes: bool,
    ) -> Result<PathBuf, ConfigEditError> {
        match source {
            ConfigSource::Local { path }
            | ConfigSource::Worktree { path }
            | ConfigSource::Global { path }
            | ConfigSource::System { path } => Ok(path.clone()),
            ConfigSource::Included { path, .. } => {
                if allow_external_includes || self.config_path_is_inside_repository(path) {
                    Ok(path.clone())
                } else {
                    Err(ConfigEditError::RefusesExternalInclude { path: path.clone() })
                }
            }
            ConfigSource::Env
            | ConfigSource::CommandLine
            | ConfigSource::Blob { .. }
            | ConfigSource::Stdin => Err(ConfigEditError::NoEditableSource),
        }
    }

    fn config_path_is_inside_repository(&self, path: &Path) -> bool {
        let mut roots = self
            .workdir()
            .into_iter()
            .chain(std::iter::once(self.common_dir().to_path_buf()));
        roots.any(|root| path_starts_with(path, &root))
    }

    fn remote_source_metadata(&self, source: ConfigSource) -> RemoteConfigSource {
        match self.edit_path_for_source(&source, false) {
            Ok(path) => RemoteConfigSource {
                source,
                editable: true,
                target_path: Some(path),
                refusal: None,
            },
            Err(ConfigEditError::RefusesExternalInclude { path }) => RemoteConfigSource {
                source,
                editable: false,
                target_path: None,
                refusal: Some(RemoteConfigRefusal::ExternalInclude { path }),
            },
            Err(_) => RemoteConfigSource {
                source,
                editable: false,
                target_path: None,
                refusal: Some(RemoteConfigRefusal::SyntheticSource),
            },
        }
    }
}

struct ConfigSourceBases {
    local: PathBuf,
    worktree: PathBuf,
    globals: Vec<PathBuf>,
    system: Option<PathBuf>,
}

impl ConfigSourceBases {
    fn for_repository(repo: &Repository) -> Self {
        let mut globals = Vec::new();
        let mut system = None;
        for (path, scope) in sley_config::default_config_layer_paths() {
            match scope {
                ConfigScope::System => system = Some(path),
                ConfigScope::Global => globals.push(path),
                _ => {}
            }
        }
        Self {
            local: repo.common_dir().join("config"),
            worktree: repo.git_dir().join("config.worktree"),
            globals,
            system,
        }
    }

    fn source_for(
        &self,
        scope: ConfigScope,
        origin: &sley_config::ConfigOrigin,
        included_from: Option<&sley_config::ConfigOrigin>,
    ) -> ConfigSource {
        match origin.kind {
            ConfigOriginKind::File => {
                let path = PathBuf::from(&origin.name);
                match scope {
                    ConfigScope::Local if paths_equivalent(&path, &self.local) => {
                        ConfigSource::Local { path }
                    }
                    ConfigScope::Worktree if paths_equivalent(&path, &self.worktree) => {
                        ConfigSource::Worktree { path }
                    }
                    ConfigScope::Global
                        if self
                            .globals
                            .iter()
                            .any(|base| paths_equivalent(&path, base)) =>
                    {
                        ConfigSource::Global { path }
                    }
                    ConfigScope::System
                        if self
                            .system
                            .as_ref()
                            .is_some_and(|base| paths_equivalent(&path, base)) =>
                    {
                        ConfigSource::System { path }
                    }
                    _ => ConfigSource::Included {
                        path,
                        included_from: included_from.and_then(file_origin_path),
                    },
                }
            }
            ConfigOriginKind::Blob => ConfigSource::Blob {
                spec: origin.name.clone(),
            },
            ConfigOriginKind::Stdin => ConfigSource::Stdin,
            ConfigOriginKind::CommandLine => ConfigSource::CommandLine,
        }
    }
}

fn file_origin_path(origin: &sley_config::ConfigOrigin) -> Option<PathBuf> {
    (origin.kind == ConfigOriginKind::File).then(|| PathBuf::from(&origin.name))
}

#[derive(Debug, Clone)]
struct ParsedConfigKey {
    full: String,
    section: String,
    subsection: Option<String>,
    name: String,
}

impl ParsedConfigKey {
    fn parse(key: &str) -> Result<Self, ConfigEditError> {
        let full = sley_config::canonicalize_config_key(key)
            .map_err(|err| ConfigEditError::Parse(err.message()))?;
        let first_dot = full
            .find('.')
            .ok_or_else(|| ConfigEditError::Parse(format!("invalid config key: {key}")))?;
        let last_dot = full
            .rfind('.')
            .ok_or_else(|| ConfigEditError::Parse(format!("invalid config key: {key}")))?;
        let section = full[..first_dot].to_string();
        let name = full[last_dot + 1..].to_string();
        let subsection = (first_dot != last_dot).then(|| full[first_dot + 1..last_dot].to_string());
        Ok(Self {
            full,
            section,
            subsection,
            name,
        })
    }
}

fn config_entry_key(section: &str, subsection: Option<&str>, name: &str) -> String {
    let section = section.to_ascii_lowercase();
    let name = name.to_ascii_lowercase();
    match subsection {
        Some(subsection) => format!("{section}.{subsection}.{name}"),
        None => format!("{section}.{name}"),
    }
}

fn validate_remote_name(name: &str) -> Result<(), ConfigEditError> {
    if name.is_empty() {
        return Err(ConfigEditError::Parse(
            "remote name must not be empty".into(),
        ));
    }
    ParsedConfigKey::parse(&format!("remote.{name}.url")).map(|_| ())
}

fn validate_section_entries(
    section: &str,
    subsection: Option<&str>,
    entries: &[ConfigSectionEntry],
) -> Result<(), ConfigEditError> {
    for entry in entries {
        if entry.name.is_empty() {
            return Err(ConfigEditError::Parse(
                "config entry name must not be empty".into(),
            ));
        }
        let key = match subsection {
            Some(subsection) => format!("{section}.{subsection}.{}", entry.name),
            None => format!("{section}.{}", entry.name),
        };
        ParsedConfigKey::parse(&key)?;
    }
    Ok(())
}

fn replace_section(
    contents: Vec<u8>,
    section: &str,
    subsection: Option<&str>,
    entries: &[ConfigSectionEntry],
) -> Result<Vec<u8>, ConfigEditError> {
    let contents = match remove_section_if_present(&contents, section, subsection)? {
        Some(contents) => contents,
        None => contents,
    };
    Ok(append_section(contents, section, subsection, entries))
}

fn remove_section(
    contents: Vec<u8>,
    section: &str,
    subsection: Option<&str>,
) -> Result<Vec<u8>, ConfigEditError> {
    match remove_section_if_present(&contents, section, subsection)? {
        Some(contents) => Ok(contents),
        None => Err(ConfigEditError::SectionNotFound {
            section: section.to_string(),
            subsection: subsection.map(str::to_string),
        }),
    }
}

fn remove_section_if_present(
    contents: &[u8],
    section: &str,
    subsection: Option<&str>,
) -> Result<Option<Vec<u8>>, ConfigEditError> {
    let name = normalised_section_name(section, subsection);
    match rename_or_remove_section(contents, &name, None) {
        SectionEditOutcome::Changed(contents) => Ok(Some(contents)),
        SectionEditOutcome::NotFound => Ok(None),
        SectionEditOutcome::LineTooLong(line) => Err(ConfigEditError::Parse(format!(
            "config line {line} exceeds maximum line length"
        ))),
    }
}

fn append_section(
    mut contents: Vec<u8>,
    section: &str,
    subsection: Option<&str>,
    entries: &[ConfigSectionEntry],
) -> Vec<u8> {
    if !contents.is_empty() && !contents.ends_with(b"\n") {
        contents.push(b'\n');
    }
    render_section(&mut contents, section, subsection, entries);
    contents
}

fn render_section(
    out: &mut Vec<u8>,
    section: &str,
    subsection: Option<&str>,
    entries: &[ConfigSectionEntry],
) {
    out.push(b'[');
    out.extend_from_slice(section.as_bytes());
    if let Some(subsection) = subsection {
        out.extend_from_slice(b" \"");
        for ch in subsection.chars() {
            if ch == '"' || ch == '\\' {
                out.push(b'\\');
            }
            let mut buf = [0; 4];
            out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
        }
        out.push(b'"');
    }
    out.extend_from_slice(b"]\n");
    for entry in entries {
        out.push(b'\t');
        out.extend_from_slice(entry.name.as_bytes());
        if let Some(value) = &entry.value {
            out.extend_from_slice(b" = ");
            out.extend_from_slice(quote_config_value(value).as_bytes());
        }
        out.push(b'\n');
    }
}

fn quote_config_value(value: &str) -> String {
    let needs_quotes = value.starts_with(' ')
        || value.ends_with(' ')
        || value.contains('\r')
        || value.bytes().any(|byte| matches!(byte, b'#' | b';'));
    let mut out = String::new();
    if needs_quotes {
        out.push('"');
    }
    for ch in value.chars() {
        match ch {
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            other => out.push(other),
        }
    }
    if needs_quotes {
        out.push('"');
    }
    out
}

fn normalised_section_name(section: &str, subsection: Option<&str>) -> String {
    match subsection {
        Some(subsection) => format!("{}.{subsection}", section.to_ascii_lowercase()),
        None => section.to_ascii_lowercase(),
    }
}

fn paths_equivalent(left: &Path, right: &Path) -> bool {
    left == right
        || match (fs::canonicalize(left), fs::canonicalize(right)) {
            (Ok(left), Ok(right)) => left == right,
            _ => false,
        }
}

fn path_starts_with(path: &Path, root: &Path) -> bool {
    if path.starts_with(root) {
        return true;
    }
    match (fs::canonicalize(path), fs::canonicalize(root)) {
        (Ok(path), Ok(root)) => path.starts_with(root),
        _ => false,
    }
}

impl ConfigEditError {
    fn from_git_error(err: GitError) -> Self {
        match err {
            GitError::Io(message) => Self::Io(std::io::Error::other(message)),
            GitError::InvalidFormat(message)
            | GitError::InvalidPath(message)
            | GitError::InvalidObject(message)
            | GitError::InvalidObjectId(message)
            | GitError::Unsupported(message) => Self::Parse(message),
            other => Self::Parse(other.to_string()),
        }
    }

    fn from_config_write(err: ConfigFileWriteError) -> Self {
        match err {
            ConfigFileWriteError::ExistingLock(path) => Self::Locked { path },
            ConfigFileWriteError::Io { source, .. } => Self::Io(source),
        }
    }
}