treeboot-core 0.4.1

Reusable worktree bootstrap engine for the treeboot CLI.
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
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
use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};

use serde::de::{self, MapAccess, Visitor, value::MapAccessDeserializer};
use serde::{Deserialize, Serialize};
use toml::Spanned;

use crate::context;
use crate::discovery;
use crate::{Error, Result, Worktree, WorktreeOptions};

/// Options for inspecting a treeboot config.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConfigOptions {
    /// Directory from which config discovery starts.
    pub cwd: Option<PathBuf>,
    /// Overrides the root checkout used for resolved source paths.
    pub root: Option<PathBuf>,
    /// Uses one specific config file instead of discovery.
    pub config: Option<PathBuf>,
}

/// Loaded treeboot config selected for a worktree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadedConfig {
    /// Runtime context used while resolving config paths.
    pub context: Worktree,
    /// Config file path.
    pub path: PathBuf,
    /// Parsed and normalized config.
    pub config: Config,
}

/// Result summary for a `treeboot config` invocation.
pub type ConfigReport = LoadedConfig;

/// Parsed and normalized treeboot config.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Config {
    /// Runtime options declared by the config.
    #[serde(flatten)]
    pub options: ConfigRuntimeOptions,
    /// Ordered file operations.
    pub files: Vec<FileOperation>,
    /// Ordered command operations.
    pub commands: Vec<CommandOperation>,
}

impl Config {
    /// Loads and parses a treeboot config from disk.
    ///
    /// Relative paths inside the config are normalized against the supplied
    /// worktree context.
    ///
    /// # Errors
    ///
    /// Returns an error if the config cannot be read or TOML parsing and
    /// normalization fails.
    pub fn load(path: &Path, context: &Worktree) -> Result<Self> {
        let content = std::fs::read_to_string(path).map_err(|source| Error::ConfigIo {
            path: path.to_path_buf(),
            source,
        })?;

        Self::parse(path, &content, context)
    }

    /// Parses a treeboot config string.
    ///
    /// The path is used for diagnostics. Relative paths inside the config are
    /// normalized against the supplied worktree context.
    ///
    /// # Errors
    ///
    /// Returns an error if TOML parsing or normalization fails.
    pub fn parse(path: &Path, content: &str, context: &Worktree) -> Result<Self> {
        parse_config(path, content, context)
    }

    /// Discovers the selected treeboot config path for a worktree.
    ///
    /// When `requested_config` is provided, it is resolved relative to the
    /// worktree path and must exist. When omitted, standard treeboot config
    /// paths are searched in precedence order.
    ///
    /// # Errors
    ///
    /// Returns an error when a requested config path does not exist.
    pub fn discover_path(
        context: &Worktree,
        requested_config: Option<&Path>,
    ) -> Result<Option<PathBuf>> {
        discovery::discover_config(&context.worktree_path, requested_config)
    }

    /// Discovers, loads, and parses the selected treeboot config.
    ///
    /// Returns `Ok(None)` when no config was requested and no standard config
    /// path exists.
    ///
    /// # Errors
    ///
    /// Returns an error if a requested config path does not exist, the selected
    /// config cannot be read, or TOML parsing and normalization fails.
    pub fn load_discovered(
        context: &Worktree,
        requested_config: Option<&Path>,
    ) -> Result<Option<LoadedConfig>> {
        let Some(path) = Self::discover_path(context, requested_config)? else {
            return Ok(None);
        };
        let config = Self::load(&path, context)?;

        Ok(Some(LoadedConfig {
            context: context.clone(),
            path,
            config,
        }))
    }
}

/// A normalized file operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FileOperation {
    /// File operation kind.
    pub operation: FileOperationKind,
    /// Declared source path.
    pub source: PathBuf,
    /// Declared target path.
    pub target: PathBuf,
    /// Source path resolved from the root checkout.
    pub source_path: PathBuf,
    /// Target path resolved from the current worktree.
    pub target_path: PathBuf,
    /// Whether a missing source should fail validation.
    pub required: bool,
    /// Sync comparison mode.
    pub compare: Option<SyncCompare>,
    /// Whether sync should delete target-only files.
    pub delete: Option<bool>,
    /// How copy and sync should treat source symlinks.
    pub symlinks: Option<SymlinkMode>,
    /// Source location for the operation declaration.
    pub declaration: SourceSpan,
}

/// File operation kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FileOperationKind {
    /// Copy source content to the target.
    Copy,
    /// Create a target symlink to the source.
    Symlink,
    /// Reconcile target content with source content.
    Sync,
}

impl FileOperationKind {
    /// Returns the stable lowercase operation name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Copy => "copy",
            Self::Symlink => "symlink",
            Self::Sync => "sync",
        }
    }
}

impl fmt::Display for FileOperationKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Sync comparison mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SyncCompare {
    /// Compare size and modified time.
    Metadata,
    /// Compare file contents.
    Checksum,
}

/// Copy or sync symlink handling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SymlinkMode {
    /// Recreate safe source symlinks as symlinks.
    Preserve,
}

/// A normalized command operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CommandOperation {
    /// Optional display name.
    pub name: Option<String>,
    /// Command invocation.
    pub command: CommandKind,
    /// Declared working directory.
    pub cwd: Option<PathBuf>,
    /// Working directory resolved from the current worktree.
    pub cwd_path: Option<PathBuf>,
    /// Extra environment variables for this command.
    pub env: BTreeMap<String, String>,
    /// Whether a non-zero exit status should be non-fatal.
    pub allow_failure: bool,
    /// Source location for the command declaration.
    pub declaration: SourceSpan,
}

/// Command invocation kind.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CommandKind {
    /// Shell command invocation.
    Shell {
        /// Shell command string.
        run: String,
    },
    /// Direct program invocation.
    Direct {
        /// Program executable.
        program: String,
        /// Program arguments.
        args: Vec<String>,
    },
}

/// Runtime options declared by a config file.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
pub struct ConfigRuntimeOptions {
    /// Enables strict declarative validation and conflict handling.
    pub strict: bool,
    /// Allows file operation sources outside the root checkout.
    pub dangerously_allow_sources_outside_root: bool,
    /// Allows file operation targets outside the current worktree.
    pub dangerously_allow_targets_outside_worktree: bool,
}

/// Environment overrides for config runtime options.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RuntimeOptionOverrides {
    /// Strict mode environment override.
    pub strict: Option<bool>,
    /// Source-boundary environment override.
    pub dangerously_allow_sources_outside_root: Option<bool>,
    /// Target-boundary environment override.
    pub dangerously_allow_targets_outside_worktree: Option<bool>,
}

impl RuntimeOptionOverrides {
    /// Reads treeboot runtime option overrides from the process environment.
    ///
    /// # Errors
    ///
    /// Returns an error when an environment value is not a supported boolean.
    pub fn from_env() -> Result<Self> {
        Ok(Self {
            strict: env_bool("TREEBOOT_STRICT")?,
            dangerously_allow_sources_outside_root: env_bool(
                "TREEBOOT_DANGEROUSLY_ALLOW_SOURCES_OUTSIDE_ROOT",
            )?,
            dangerously_allow_targets_outside_worktree: env_bool(
                "TREEBOOT_DANGEROUSLY_ALLOW_TARGETS_OUTSIDE_WORKTREE",
            )?,
        })
    }

    /// Returns strict mode before config discovery.
    #[must_use]
    pub const fn pre_config_strict(self, cli_strict: bool) -> bool {
        cli_strict || matches!(self.strict, Some(true))
    }

    /// Resolves runtime options using defaults, config, environment, then CLI.
    #[must_use]
    pub fn resolve(self, config: &ConfigRuntimeOptions, cli_strict: bool) -> ConfigRuntimeOptions {
        let mut resolved = *config;

        if let Some(strict) = self.strict {
            resolved.strict = strict;
        }
        if let Some(allow) = self.dangerously_allow_sources_outside_root {
            resolved.dangerously_allow_sources_outside_root = allow;
        }
        if let Some(allow) = self.dangerously_allow_targets_outside_worktree {
            resolved.dangerously_allow_targets_outside_worktree = allow;
        }
        if cli_strict {
            resolved.strict = true;
        }

        resolved
    }
}

/// Byte and line location for a declaration in a config file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct SourceSpan {
    /// Starting byte offset.
    pub start: usize,
    /// Ending byte offset.
    pub end: usize,
    /// One-based starting line.
    pub line: usize,
    /// One-based starting column.
    pub column: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct FileOperationSettingsInput {
    pub(crate) compare: Option<SyncCompare>,
    pub(crate) delete: Option<bool>,
    pub(crate) symlinks: Option<SymlinkMode>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct FileOperationSettings {
    pub(crate) compare: Option<SyncCompare>,
    pub(crate) delete: Option<bool>,
    pub(crate) symlinks: Option<SymlinkMode>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum InvalidFileOperationField {
    Compare,
    Delete,
    Symlinks,
}

impl InvalidFileOperationField {
    pub(crate) const fn name(self) -> &'static str {
        match self {
            Self::Compare => "compare",
            Self::Delete => "delete",
            Self::Symlinks => "symlinks",
        }
    }

    pub(crate) const fn allowed_operations(self) -> &'static str {
        match self {
            Self::Compare | Self::Delete => "sync",
            Self::Symlinks => "copy and sync",
        }
    }
}

pub(crate) fn normalize_file_operation_settings(
    operation: FileOperationKind,
    input: FileOperationSettingsInput,
) -> std::result::Result<FileOperationSettings, InvalidFileOperationField> {
    let compare = match operation {
        FileOperationKind::Sync => Some(input.compare.unwrap_or(SyncCompare::Metadata)),
        FileOperationKind::Copy | FileOperationKind::Symlink => {
            if input.compare.is_some() {
                return Err(InvalidFileOperationField::Compare);
            }
            None
        }
    };
    let delete = match operation {
        FileOperationKind::Sync => Some(input.delete.unwrap_or(false)),
        FileOperationKind::Copy | FileOperationKind::Symlink => {
            if input.delete.is_some() {
                return Err(InvalidFileOperationField::Delete);
            }
            None
        }
    };
    let symlinks = match operation {
        FileOperationKind::Copy | FileOperationKind::Sync => {
            Some(input.symlinks.unwrap_or(SymlinkMode::Preserve))
        }
        FileOperationKind::Symlink => {
            if input.symlinks.is_some() {
                return Err(InvalidFileOperationField::Symlinks);
            }
            None
        }
    };

    Ok(FileOperationSettings {
        compare,
        delete,
        symlinks,
    })
}

/// Parses, normalizes, and returns the selected config file.
///
/// # Errors
///
/// Returns an error if context discovery fails, no config exists, the requested
/// config path does not exist, the config cannot be read, or TOML parsing and
/// normalization fails.
pub fn inspect_config(options: ConfigOptions) -> Result<ConfigReport> {
    let worktree_options = WorktreeOptions {
        cwd: options.cwd,
        root: options.root,
    };
    let context = context::resolve(&worktree_options)?;
    Config::load_discovered(&context, options.config.as_deref())?
        .ok_or(Error::NoConfigDetectedStrict)
}

fn parse_config(path: &Path, content: &str, context: &Worktree) -> Result<Config> {
    let raw: RawConfig = toml::from_str(content).map_err(|source| {
        let message = parse_error_message(content, &source);
        Error::ConfigParse {
            path: path.to_path_buf(),
            message,
        }
    })?;

    let mut files = Vec::new();
    normalize_file_group(
        path,
        content,
        context,
        &mut files,
        FileOperationKind::Copy,
        raw.copy,
    )?;
    normalize_file_group(
        path,
        content,
        context,
        &mut files,
        FileOperationKind::Symlink,
        raw.symlink,
    )?;
    normalize_file_group(
        path,
        content,
        context,
        &mut files,
        FileOperationKind::Sync,
        raw.sync,
    )?;
    normalize_mixed_files(path, content, context, &mut files, raw.files)?;
    normalize_file_tables(path, content, context, &mut files, raw.file)?;

    let mut commands = Vec::new();
    normalize_command_entries(path, content, context, &mut commands, raw.commands)?;
    normalize_command_tables(path, content, context, &mut commands, raw.command)?;

    Ok(Config {
        options: ConfigRuntimeOptions {
            strict: raw.strict,
            dangerously_allow_sources_outside_root: raw.dangerously_allow_sources_outside_root,
            dangerously_allow_targets_outside_worktree: raw
                .dangerously_allow_targets_outside_worktree,
        },
        files,
        commands,
    })
}

fn normalize_file_group(
    path: &Path,
    content: &str,
    context: &Worktree,
    files: &mut Vec<FileOperation>,
    operation: FileOperationKind,
    entries: Vec<Spanned<RawFileEntry>>,
) -> Result<()> {
    for entry in entries {
        let span = entry_span(content, &entry);
        let entry = entry.into_inner();
        let object = match entry {
            RawFileEntry::Path(source) => RawFileObject {
                operation: None,
                source: Some(source),
                target: None,
                required: false,
                compare: None,
                delete: None,
                symlinks: None,
            },
            RawFileEntry::Object(object) => object,
        };

        if object.operation.is_some() {
            return invalid_config(
                path,
                content,
                span,
                "`operation` is only valid in `files` and `[[file]]` entries",
            );
        }

        files.push(normalize_file_object(
            path, content, context, operation, object, span,
        )?);
    }

    Ok(())
}

fn normalize_mixed_files(
    path: &Path,
    content: &str,
    context: &Worktree,
    files: &mut Vec<FileOperation>,
    entries: Vec<Spanned<RawFileObject>>,
) -> Result<()> {
    for entry in entries {
        let span = entry_span(content, &entry);
        let object = entry.into_inner();
        let operation = required_operation(path, content, span, object.operation)?;
        files.push(normalize_file_object(
            path, content, context, operation, object, span,
        )?);
    }

    Ok(())
}

fn normalize_file_tables(
    path: &Path,
    content: &str,
    context: &Worktree,
    files: &mut Vec<FileOperation>,
    entries: Vec<Spanned<RawFileObject>>,
) -> Result<()> {
    normalize_mixed_files(path, content, context, files, entries)
}

fn normalize_file_object(
    path: &Path,
    content: &str,
    context: &Worktree,
    operation: FileOperationKind,
    object: RawFileObject,
    span: SourceSpan,
) -> Result<FileOperation> {
    let source = object.source.ok_or_else(|| {
        invalid_config_error(
            path,
            content,
            span,
            "file operation is missing required `source`",
        )
    })?;
    let target = object.target.unwrap_or_else(|| source.clone());
    let settings = normalize_file_operation_settings(
        operation,
        FileOperationSettingsInput {
            compare: object.compare,
            delete: object.delete,
            symlinks: object.symlinks,
        },
    )
    .map_err(|field| {
        invalid_config_error(
            path,
            content,
            span,
            format!(
                "`{}` is only valid for {} file operations",
                field.name(),
                field.allowed_operations()
            ),
        )
    })?;

    Ok(FileOperation {
        operation,
        source_path: resolve_path(&context.root_path, Path::new(&source)),
        target_path: resolve_path(&context.worktree_path, Path::new(&target)),
        source: PathBuf::from(source),
        target: PathBuf::from(target),
        required: object.required,
        compare: settings.compare,
        delete: settings.delete,
        symlinks: settings.symlinks,
        declaration: span,
    })
}

fn required_operation(
    path: &Path,
    content: &str,
    span: SourceSpan,
    operation: Option<FileOperationKind>,
) -> Result<FileOperationKind> {
    operation.ok_or_else(|| {
        invalid_config_error(
            path,
            content,
            span,
            "file operation is missing required `operation`",
        )
    })
}

fn normalize_command_entries(
    path: &Path,
    content: &str,
    context: &Worktree,
    commands: &mut Vec<CommandOperation>,
    entries: Vec<Spanned<RawCommandEntry>>,
) -> Result<()> {
    for entry in entries {
        let span = entry_span(content, &entry);
        let object = match entry.into_inner() {
            RawCommandEntry::Run(run) => RawCommandObject {
                name: None,
                run: Some(run),
                program: None,
                args: None,
                cwd: None,
                env: BTreeMap::new(),
                allow_failure: false,
            },
            RawCommandEntry::Object(object) => object,
        };

        commands.push(normalize_command_object(
            path, content, context, object, span,
        )?);
    }

    Ok(())
}

fn normalize_command_tables(
    path: &Path,
    content: &str,
    context: &Worktree,
    commands: &mut Vec<CommandOperation>,
    entries: Vec<Spanned<RawCommandObject>>,
) -> Result<()> {
    for entry in entries {
        let span = entry_span(content, &entry);
        commands.push(normalize_command_object(
            path,
            content,
            context,
            entry.into_inner(),
            span,
        )?);
    }

    Ok(())
}

fn normalize_command_object(
    path: &Path,
    content: &str,
    context: &Worktree,
    object: RawCommandObject,
    span: SourceSpan,
) -> Result<CommandOperation> {
    let command = match (object.run, object.program) {
        (Some(_), Some(_)) => {
            return invalid_config(
                path,
                content,
                span,
                "`run` and `program` are mutually exclusive",
            );
        }
        (Some(_), None) if object.args.is_some() => {
            return invalid_config(path, content, span, "`args` requires `program`");
        }
        (Some(run), None) => CommandKind::Shell { run },
        (None, Some(program)) => CommandKind::Direct {
            program,
            args: object.args.unwrap_or_default(),
        },
        (None, None) => {
            return invalid_config(
                path,
                content,
                span,
                "command is missing required `run` or `program`",
            );
        }
    };
    let cwd_path = object
        .cwd
        .as_ref()
        .map(|cwd| resolve_path(&context.worktree_path, Path::new(cwd)));

    Ok(CommandOperation {
        name: object.name,
        command,
        cwd: object.cwd.map(PathBuf::from),
        cwd_path,
        env: object.env,
        allow_failure: object.allow_failure,
        declaration: span,
    })
}

fn resolve_path(base: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        base.join(path)
    }
}

fn parse_error_message(content: &str, error: &toml::de::Error) -> String {
    match error.span() {
        Some(span) => format!("{} {}", error.message(), location_suffix(content, &span)),
        None => error.message().to_owned(),
    }
}

fn invalid_config<T>(
    path: &Path,
    content: &str,
    span: SourceSpan,
    message: impl Into<String>,
) -> Result<T> {
    Err(invalid_config_error(path, content, span, message))
}

fn invalid_config_error(
    path: &Path,
    content: &str,
    span: SourceSpan,
    message: impl Into<String>,
) -> Error {
    Error::ConfigInvalid {
        path: path.to_path_buf(),
        message: format!(
            "{} {}",
            message.into(),
            location_suffix(content, &(span.start..span.end))
        ),
    }
}

fn entry_span<T>(content: &str, entry: &Spanned<T>) -> SourceSpan {
    SourceSpan::from_range(content, entry.span())
}

fn location_suffix(content: &str, range: &std::ops::Range<usize>) -> String {
    let span = SourceSpan::from_range(content, range.clone());
    format!("at line {}, column {}", span.line, span.column)
}

impl SourceSpan {
    fn from_range(content: &str, range: std::ops::Range<usize>) -> Self {
        let (line, column) = line_column(content, range.start);

        Self {
            start: range.start,
            end: range.end,
            line,
            column,
        }
    }
}

fn line_column(content: &str, offset: usize) -> (usize, usize) {
    let mut line = 1;
    let mut column = 1;

    for character in content[..offset.min(content.len())].chars() {
        if character == '\n' {
            line += 1;
            column = 1;
        } else {
            column += 1;
        }
    }

    (line, column)
}

#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RawConfig {
    strict: bool,
    dangerously_allow_sources_outside_root: bool,
    dangerously_allow_targets_outside_worktree: bool,
    copy: Vec<Spanned<RawFileEntry>>,
    symlink: Vec<Spanned<RawFileEntry>>,
    sync: Vec<Spanned<RawFileEntry>>,
    files: Vec<Spanned<RawFileObject>>,
    file: Vec<Spanned<RawFileObject>>,
    commands: Vec<Spanned<RawCommandEntry>>,
    command: Vec<Spanned<RawCommandObject>>,
}

#[derive(Debug)]
enum RawFileEntry {
    Path(String),
    Object(RawFileObject),
}

impl<'de> Deserialize<'de> for RawFileEntry {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct RawFileEntryVisitor;

        impl<'de> Visitor<'de> for RawFileEntryVisitor {
            type Value = RawFileEntry;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a path string or file operation object")
            }

            fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(RawFileEntry::Path(value.to_owned()))
            }

            fn visit_string<E>(self, value: String) -> std::result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(RawFileEntry::Path(value))
            }

            fn visit_map<M>(self, map: M) -> std::result::Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                RawFileObject::deserialize(MapAccessDeserializer::new(map))
                    .map(RawFileEntry::Object)
            }
        }

        deserializer.deserialize_any(RawFileEntryVisitor)
    }
}

#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RawFileObject {
    operation: Option<FileOperationKind>,
    source: Option<String>,
    target: Option<String>,
    required: bool,
    compare: Option<SyncCompare>,
    delete: Option<bool>,
    symlinks: Option<SymlinkMode>,
}

#[derive(Debug)]
enum RawCommandEntry {
    Run(String),
    Object(RawCommandObject),
}

impl<'de> Deserialize<'de> for RawCommandEntry {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct RawCommandEntryVisitor;

        impl<'de> Visitor<'de> for RawCommandEntryVisitor {
            type Value = RawCommandEntry;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a shell command string or command object")
            }

            fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(RawCommandEntry::Run(value.to_owned()))
            }

            fn visit_string<E>(self, value: String) -> std::result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(RawCommandEntry::Run(value))
            }

            fn visit_map<M>(self, map: M) -> std::result::Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                RawCommandObject::deserialize(MapAccessDeserializer::new(map))
                    .map(RawCommandEntry::Object)
            }
        }

        deserializer.deserialize_any(RawCommandEntryVisitor)
    }
}

#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RawCommandObject {
    name: Option<String>,
    run: Option<String>,
    program: Option<String>,
    args: Option<Vec<String>>,
    cwd: Option<String>,
    env: BTreeMap<String, String>,
    allow_failure: bool,
}

fn env_bool(name: &'static str) -> Result<Option<bool>> {
    let Some(value) = std::env::var_os(name) else {
        return Ok(None);
    };

    let Some(value) = value.to_str() else {
        return Err(Error::InvalidBooleanEnv {
            name,
            value: value.to_string_lossy().into_owned(),
        });
    };

    parse_bool(value)
        .ok_or_else(|| Error::InvalidBooleanEnv {
            name,
            value: value.to_owned(),
        })
        .map(Some)
}

fn parse_bool(value: &str) -> Option<bool> {
    match value.to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" => Some(false),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;

    use super::*;

    fn context() -> Worktree {
        Worktree {
            root_path: PathBuf::from("/repo"),
            worktree_path: PathBuf::from("/repo-worktree"),
            default_branch: "main".to_owned(),
            environment: BTreeMap::from([(
                "TREEBOOT_ROOT_PATH".to_owned(),
                OsString::from("/repo"),
            )]),
        }
    }

    fn parse(content: &str) -> Config {
        parse_config(Path::new(".treeboot.toml"), content, &context()).expect("config should parse")
    }

    fn parse_error(content: &str) -> String {
        parse_config(Path::new(".treeboot.toml"), content, &context())
            .expect_err("config should fail")
            .to_string()
    }

    fn assert_parse_error_contains(content: &str, expected: &str) {
        let error = parse_error(content);

        assert!(
            error.contains(expected),
            "expected error to contain {expected:?}, got {error:?}"
        );
    }

    #[test]
    fn parse_config_should_normalize_file_operations_in_spec_order() {
        let config = parse(
            r#"
sync = ["sync-dir"]
copy = [".env"]
symlink = [{ source = "shared/bin", target = "bin" }]
files = [{ operation = "copy", source = ".npmrc" }]

[[file]]
operation = "sync"
source = "editor"
target = ".editor"
"#,
        );

        let operations = config
            .files
            .iter()
            .map(|operation| (operation.operation, operation.source.as_path()))
            .collect::<Vec<_>>();

        assert_eq!(
            operations,
            vec![
                (FileOperationKind::Copy, Path::new(".env")),
                (FileOperationKind::Symlink, Path::new("shared/bin")),
                (FileOperationKind::Sync, Path::new("sync-dir")),
                (FileOperationKind::Copy, Path::new(".npmrc")),
                (FileOperationKind::Sync, Path::new("editor")),
            ]
        );
    }

    #[test]
    fn parse_config_should_apply_file_defaults() {
        let config = parse(
            r#"
copy = [{ source = ".env.local" }]
sync = ["shared/config"]
"#,
        );

        let copy = &config.files[0];
        let sync = &config.files[1];

        assert_eq!(copy.target, PathBuf::from(".env.local"));
        assert!(!copy.required);
        assert_eq!(copy.symlinks, Some(SymlinkMode::Preserve));
        assert_eq!(sync.compare, Some(SyncCompare::Metadata));
        assert_eq!(sync.delete, Some(false));
    }

    #[test]
    fn parse_config_should_preserve_explicit_sync_options() {
        let config = parse(
            r#"
sync = [{
  source = "shared/config",
  compare = "checksum",
  delete = true,
  symlinks = "preserve",
}]
"#,
        );

        let sync = &config.files[0];

        assert_eq!(sync.compare, Some(SyncCompare::Checksum));
        assert_eq!(sync.delete, Some(true));
        assert_eq!(sync.symlinks, Some(SymlinkMode::Preserve));
    }

    #[test]
    fn parse_config_should_apply_runtime_options() {
        let config = parse(
            r#"
strict = true
dangerously_allow_sources_outside_root = true
dangerously_allow_targets_outside_worktree = true
"#,
        );

        assert!(config.options.strict);
        assert!(config.options.dangerously_allow_sources_outside_root);
        assert!(config.options.dangerously_allow_targets_outside_worktree);
    }

    #[test]
    fn parse_config_should_reject_nested_validation_options() {
        assert_parse_error_contains(
            r#"
[validation]
dangerously_allow_sources_outside_root = true
"#,
            "unknown field",
        );
    }

    #[test]
    fn parse_bool_should_accept_supported_true_values() {
        for value in ["1", "true", "TRUE", "yes", "on"] {
            assert_eq!(parse_bool(value), Some(true), "value {value:?}");
        }
    }

    #[test]
    fn parse_bool_should_accept_supported_false_values() {
        for value in ["0", "false", "FALSE", "no", "off"] {
            assert_eq!(parse_bool(value), Some(false), "value {value:?}");
        }
    }

    #[test]
    fn parse_bool_should_reject_unsupported_values() {
        assert_eq!(parse_bool("sometimes"), None);
    }

    #[test]
    fn parse_config_should_resolve_absolute_paths_without_rebasing() {
        let config = parse(
            r#"
copy = [{ source = "/shared/.env", target = "/worktree/.env" }]
commands = [{ program = "make", cwd = "/worktree/app" }]
"#,
        );

        assert_eq!(config.files[0].source_path, PathBuf::from("/shared/.env"));
        assert_eq!(config.files[0].target_path, PathBuf::from("/worktree/.env"));
        assert_eq!(
            config.commands[0].cwd_path,
            Some(PathBuf::from("/worktree/app"))
        );
    }

    #[test]
    fn parse_config_should_normalize_command_forms() {
        let config = parse(
            r#"
commands = [
  "mise install",
  { run = "bundle install" },
]

[[command]]
program = "npm"
args = ["install"]
cwd = "web"
allow_failure = true
"#,
        );

        assert_eq!(config.commands.len(), 3);
        assert_eq!(
            config.commands[0].command,
            CommandKind::Shell {
                run: "mise install".to_owned()
            }
        );
        assert_eq!(
            config.commands[2].command,
            CommandKind::Direct {
                program: "npm".to_owned(),
                args: vec!["install".to_owned()]
            }
        );
        assert_eq!(
            config.commands[2].cwd_path,
            Some(PathBuf::from("/repo-worktree/web"))
        );
    }

    #[test]
    fn parse_config_should_normalize_command_metadata_and_defaults() {
        let config = parse(
            r#"
commands = [{
  name = "Install",
  program = "npm",
  env = { NODE_ENV = "development" },
}]
"#,
        );

        let command = &config.commands[0];

        assert_eq!(command.name.as_deref(), Some("Install"));
        assert_eq!(command.env["NODE_ENV"], "development");
        assert!(!command.allow_failure);
    }

    #[test]
    fn parse_config_should_reject_async_command_field() {
        assert_parse_error_contains(
            r#"commands = [{ run = "npm install", async = true }]"#,
            "unknown field",
        );
        assert_parse_error_contains(
            r#"commands = [{ run = "npm install", async = false }]"#,
            "unknown field",
        );
    }

    #[test]
    fn parse_config_should_allow_program_without_args() {
        let config = parse(r#"commands = [{ program = "mise" }]"#);

        assert_eq!(
            config.commands[0].command,
            CommandKind::Direct {
                program: "mise".to_owned(),
                args: Vec::new()
            }
        );
    }

    #[test]
    fn parse_config_should_reject_mutually_exclusive_command_fields() {
        assert_parse_error_contains(
            r#"commands = [{ run = "npm install", program = "npm" }]"#,
            "mutually exclusive",
        );
    }

    #[test]
    fn parse_config_should_reject_args_without_program() {
        assert_parse_error_contains(
            r#"commands = [{ run = "npm install", args = [] }]"#,
            "`args` requires `program`",
        );
    }

    #[test]
    fn parse_config_should_reject_missing_command_invocation() {
        assert_parse_error_contains(
            r#"commands = [{ name = "Install" }]"#,
            "missing required `run` or `program`",
        );
    }

    #[test]
    fn parse_config_should_reject_unknown_fields() {
        assert_parse_error_contains(
            r#"copy = [{ source = ".env", unknown = true }]"#,
            "unknown field",
        );
    }

    #[test]
    fn parse_config_should_reject_missing_file_operation() {
        assert_parse_error_contains(
            r#"files = [{ source = ".env" }]"#,
            "missing required `operation`",
        );
    }

    #[test]
    fn parse_config_should_reject_missing_file_source() {
        assert_parse_error_contains(
            r#"copy = [{ target = ".env" }]"#,
            "missing required `source`",
        );
    }

    #[test]
    fn parse_config_should_reject_operation_in_specific_file_groups() {
        assert_parse_error_contains(
            r#"copy = [{ operation = "copy", source = ".env" }]"#,
            "`operation` is only valid in `files` and `[[file]]` entries",
        );
    }

    #[test]
    fn parse_config_should_reject_compare_on_copy_file_operations() {
        assert_parse_error_contains(
            r#"copy = [{ source = ".env", compare = "checksum" }]"#,
            "`compare` is only valid for sync file operations",
        );
    }

    #[test]
    fn parse_config_should_reject_delete_on_symlink_file_operations() {
        assert_parse_error_contains(
            r#"symlink = [{ source = ".env", delete = true }]"#,
            "`delete` is only valid for sync file operations",
        );
    }

    #[test]
    fn parse_config_should_reject_legacy_delete_extra_field() {
        assert_parse_error_contains(
            r#"sync = [{ source = "shared", delete_extra = true }]"#,
            "unknown field `delete_extra`",
        );
    }

    #[test]
    fn parse_config_should_reject_symlinks_on_symlink_file_operations() {
        assert_parse_error_contains(
            r#"symlink = [{ source = ".env", symlinks = "preserve" }]"#,
            "`symlinks` is only valid for copy and sync file operations",
        );
    }

    #[test]
    fn parse_config_should_report_invalid_toml_location() {
        assert_parse_error_contains("commands = [\n", "line 1, column");
    }
}