sley-submodule 0.4.3

Submodule operations for sley.
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
//! Typed `.gitmodules` configuration — a Rust port of git's `submodule-config.c`.
//!
//! Today every consumer in sley re-derives submodule fields by hand-walking a
//! [`GitConfig`] (`section.name == "submodule"`, `find(|e| e.key == "path")`,
//! …), scattered across ~14 call sites. This module centralizes that into one
//! typed parser so the submodule command AND the tree-switch commands share a
//! single source of truth for what a `.gitmodules` entry means.
//!
//! Porting notes (git `submodule-config.c`):
//! - [`parse_config`] is the per-key dispatch; we drive it over a parsed
//!   [`GitConfig`] rather than git's streaming `git_config_from_mem` callback,
//!   but the per-key semantics (last-one-wins vs. first-one-wins, validation,
//!   value normalization) match faithfully.
//! - [`check_submodule_name`] / [`check_submodule_url`] port the security
//!   checks that reject `..`-bearing names and command-line-option-looking
//!   values.
//! - The recurse-mode and update-strategy enums port `submodule.h`.

use sley_config::{GitConfig, parse_config_bool};

/// `enum submodule_recurse_mode` (git `submodule.h`). Discriminants match git's
/// so the numeric values are stable across the wire / config.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RecurseMode {
    Only,
    Check,
    Error,
    #[default]
    None,
    OnDemand,
    Off,
    Default,
    On,
}

impl RecurseMode {
    /// Port of git's numeric discriminants for `submodule_recurse_mode`.
    pub fn as_i8(self) -> i8 {
        match self {
            RecurseMode::Only => -5,
            RecurseMode::Check => -4,
            RecurseMode::Error => -3,
            RecurseMode::None => -2,
            RecurseMode::OnDemand => -1,
            RecurseMode::Off => 0,
            RecurseMode::Default => 1,
            RecurseMode::On => 2,
        }
    }
}

/// Port of `parse_fetch_recurse` (git `submodule-config.c`). Returns
/// [`RecurseMode::Error`] on an unrecognized argument (the `die_on_error == 0`
/// branch); callers that want the fatal behavior check for `Error`.
pub fn parse_fetch_recurse(arg: &str) -> RecurseMode {
    match parse_config_bool(arg) {
        Some(true) => RecurseMode::On,
        Some(false) => RecurseMode::Off,
        None => {
            if arg == "on-demand" {
                RecurseMode::OnDemand
            } else {
                RecurseMode::Error
            }
        }
    }
}

/// `enum submodule_update_type` (git `submodule.h`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum UpdateType {
    #[default]
    Unspecified,
    Checkout,
    Rebase,
    Merge,
    None,
    Command,
}

/// `struct submodule_update_strategy` (git `submodule.h`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct UpdateStrategy {
    pub kind: UpdateType,
    /// Only populated when `kind == Command`: the command string (the part
    /// after the leading `!`).
    pub command: Option<String>,
}

/// Port of `parse_submodule_update_type` (git `submodule.c`).
pub fn parse_update_type(value: &str) -> UpdateType {
    match value {
        "none" => UpdateType::None,
        "checkout" => UpdateType::Checkout,
        "rebase" => UpdateType::Rebase,
        "merge" => UpdateType::Merge,
        _ if value.starts_with('!') => UpdateType::Command,
        _ => UpdateType::Unspecified,
    }
}

/// Port of `parse_submodule_update_strategy` (git `submodule.c`). Returns the
/// parsed strategy, or `None` for an unrecognized value (git's `-1`).
pub fn parse_update_strategy(value: &str) -> Option<UpdateStrategy> {
    let kind = parse_update_type(value);
    if kind == UpdateType::Unspecified {
        return None;
    }
    let command = if kind == UpdateType::Command {
        Some(value[1..].to_string())
    } else {
        None
    };
    Some(UpdateStrategy { kind, command })
}

/// Port of `submodule_update_type_to_string` (git `submodule.c`). Returns
/// `None` for the two types that have no string form (`Unspecified`,
/// `Command`), matching git's `BUG()` cases — callers handle those before
/// stringifying.
pub fn update_type_to_string(kind: UpdateType) -> Option<&'static str> {
    match kind {
        UpdateType::Checkout => Some("checkout"),
        UpdateType::Merge => Some("merge"),
        UpdateType::Rebase => Some("rebase"),
        UpdateType::None => Some("none"),
        UpdateType::Unspecified | UpdateType::Command => None,
    }
}

/// A single submodule's typed configuration, the analogue of git's
/// `struct submodule`. Built by [`SubmoduleConfigSet::parse`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Submodule {
    /// The `.gitmodules` subsection (the submodule "name").
    pub name: String,
    pub path: Option<String>,
    pub url: Option<String>,
    pub fetch_recurse: RecurseMode,
    pub ignore: Option<String>,
    pub branch: Option<String>,
    pub update_strategy: UpdateStrategy,
    /// `submodule.<name>.shallow`; `None` means unset (git's `-1` sentinel).
    pub recommend_shallow: Option<bool>,
}

/// A diagnostic emitted while parsing `.gitmodules`, mirroring git's
/// `warning(...)` calls in `parse_config`. Surfacing them lets a consumer
/// reproduce git's stderr without this crate owning an output channel.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseWarning {
    /// `warning(_("ignoring suspicious submodule name: %s"), ...)`.
    SuspiciousName { name: String },
    /// `warning(_("ignoring '%s' which may be interpreted as a command-line
    /// option: %s"), ...)`.
    CommandLineOption { var: String, value: String },
    /// `warning("...multiple configurations found for 'submodule.%s.%s'...")`.
    MultipleConfig { name: String, option: String },
    /// `warning("Invalid parameter '%s' for config option
    /// 'submodule.%s.ignore'")`.
    InvalidIgnore { name: String, value: String },
    /// git `die(_("invalid value for '%s'"))` while parsing
    /// `submodule.<name>.update` — either an unrecognized value or a `!command`
    /// (which is forbidden from `.gitmodules` for security). This crate has no
    /// fatal channel, so it surfaces here; the `submodule init`/`update` path
    /// turns it into the fatal git behavior.
    InvalidUpdate { name: String },
}

/// The parsed set of all submodules from one `.gitmodules`, the analogue of the
/// path/name-keyed `submodule_cache`. Lookups are by name or by bound path,
/// matching git's `submodule_from_name` / `submodule_from_path`.
#[derive(Debug, Clone, Default)]
pub struct SubmoduleConfigSet {
    submodules: Vec<Submodule>,
    /// Non-fatal diagnostics produced during parsing, in encounter order.
    pub warnings: Vec<ParseWarning>,
}

impl SubmoduleConfigSet {
    /// Parse a typed submodule set from an already-loaded `.gitmodules`
    /// [`GitConfig`]. This is the moral equivalent of git driving
    /// `parse_config` over every `submodule.*.*` key in the blob.
    ///
    /// Per-key precedence matches git's `parse_config` with `overwrite == 0`:
    /// the FIRST value of a key wins and later duplicates emit a
    /// [`ParseWarning::MultipleConfig`] (git's `warn_multiple_config`).
    pub fn parse(config: &GitConfig) -> Self {
        let mut set = SubmoduleConfigSet::default();
        for section in &config.sections {
            if section.name != "submodule" {
                continue;
            }
            // `name_and_item_from_var`: the subsection IS the submodule name,
            // and suspicious names are dropped wholesale with a warning.
            let Some(name) = section.subsection.as_deref() else {
                continue;
            };
            if !check_submodule_name(name) {
                set.warnings.push(ParseWarning::SuspiciousName {
                    name: name.to_string(),
                });
                continue;
            }
            // Ensure the submodule exists even if it has zero recognized keys
            // (git's lookup_or_create_by_name runs before each key's dispatch).
            set.lookup_or_create_by_name(name);
            for entry in &section.entries {
                // git lowercases the variable name (`key`) before dispatch.
                let item = entry.key.to_ascii_lowercase();
                let value = entry.value.as_deref();
                parse_config(&mut set, name, &item, value);
            }
        }
        set
    }

    fn lookup_or_create_by_name(&mut self, name: &str) -> usize {
        if let Some(index) = self.submodules.iter().position(|sub| sub.name == name) {
            return index;
        }
        self.submodules.push(Submodule {
            name: name.to_string(),
            ..Submodule::default()
        });
        self.submodules.len() - 1
    }

    /// All parsed submodules, in `.gitmodules` declaration order.
    pub fn iter(&self) -> impl Iterator<Item = &Submodule> {
        self.submodules.iter()
    }

    /// `submodule_from_name`: look up by the `.gitmodules` subsection name.
    pub fn from_name(&self, name: &str) -> Option<&Submodule> {
        self.submodules.iter().find(|sub| sub.name == name)
    }

    /// `submodule_from_path`: look up by the path a submodule is bound at.
    pub fn from_path(&self, path: &str) -> Option<&Submodule> {
        self.submodules
            .iter()
            .find(|sub| sub.path.as_deref() == Some(path))
    }

    /// True when no submodules were declared.
    pub fn is_empty(&self) -> bool {
        self.submodules.is_empty()
    }

    /// Number of declared submodules.
    pub fn len(&self) -> usize {
        self.submodules.len()
    }
}

/// Per-key parse dispatch — direct port of git `submodule-config.c`'s
/// `parse_config`. `set` already contains the named submodule (created by the
/// caller); we index it back out so each arm can mutate in place and push
/// warnings onto `set.warnings`.
fn parse_config(set: &mut SubmoduleConfigSet, name: &str, item: &str, value: Option<&str>) {
    let index = set
        .submodules
        .iter()
        .position(|sub| sub.name == name)
        .expect("submodule created before parse_config dispatch");

    match item {
        "path" => {
            let Some(value) = value else { return };
            if looks_like_command_line_option(value) {
                set.warnings.push(ParseWarning::CommandLineOption {
                    var: format!("submodule.{name}.path"),
                    value: value.to_string(),
                });
            } else if set.submodules[index].path.is_some() {
                set.warnings.push(ParseWarning::MultipleConfig {
                    name: name.to_string(),
                    option: "path".to_string(),
                });
            } else {
                set.submodules[index].path = Some(value.to_string());
            }
        }
        "fetchrecursesubmodules" => {
            if set.submodules[index].fetch_recurse != RecurseMode::None {
                set.warnings.push(ParseWarning::MultipleConfig {
                    name: name.to_string(),
                    option: "fetchrecursesubmodules".to_string(),
                });
            } else if let Some(value) = value {
                set.submodules[index].fetch_recurse = parse_fetch_recurse(value);
            }
        }
        "ignore" => {
            let Some(value) = value else { return };
            if set.submodules[index].ignore.is_some() {
                set.warnings.push(ParseWarning::MultipleConfig {
                    name: name.to_string(),
                    option: "ignore".to_string(),
                });
            } else if !matches!(value, "untracked" | "dirty" | "all" | "none") {
                set.warnings.push(ParseWarning::InvalidIgnore {
                    name: name.to_string(),
                    value: value.to_string(),
                });
            } else {
                set.submodules[index].ignore = Some(value.to_string());
            }
        }
        "url" => {
            let Some(value) = value else { return };
            if looks_like_command_line_option(value) {
                set.warnings.push(ParseWarning::CommandLineOption {
                    var: format!("submodule.{name}.url"),
                    value: value.to_string(),
                });
            } else if set.submodules[index].url.is_some() {
                set.warnings.push(ParseWarning::MultipleConfig {
                    name: name.to_string(),
                    option: "url".to_string(),
                });
            } else {
                set.submodules[index].url = Some(value.to_string());
            }
        }
        "update" => {
            let Some(value) = value else { return };
            if set.submodules[index].update_strategy.kind != UpdateType::Unspecified {
                set.warnings.push(ParseWarning::MultipleConfig {
                    name: name.to_string(),
                    option: "update".to_string(),
                });
            } else {
                match parse_update_strategy(value) {
                    Some(strategy) if strategy.kind != UpdateType::Command => {
                        set.submodules[index].update_strategy = strategy;
                    }
                    // git die()s on a bad value or a `!command` from .gitmodules
                    // (the command-form is forbidden there for security). This
                    // crate has no fatal channel, so we record the invalid value
                    // as a warning and leave the strategy unspecified; the
                    // `init`/`update` path promotes it to the fatal git behavior.
                    _ => {
                        set.warnings.push(ParseWarning::InvalidUpdate {
                            name: name.to_string(),
                        });
                    }
                }
            }
        }
        "shallow" => {
            if set.submodules[index].recommend_shallow.is_some() {
                set.warnings.push(ParseWarning::MultipleConfig {
                    name: name.to_string(),
                    option: "shallow".to_string(),
                });
            } else {
                // git_config_bool: a bare key (no value) is true.
                let parsed = value.is_none_or(|v| parse_config_bool(v).unwrap_or(false));
                set.submodules[index].recommend_shallow = Some(parsed);
            }
        }
        "branch" => {
            let Some(value) = value else { return };
            if set.submodules[index].branch.is_some() {
                set.warnings.push(ParseWarning::MultipleConfig {
                    name: name.to_string(),
                    option: "branch".to_string(),
                });
            } else {
                set.submodules[index].branch = Some(value.to_string());
            }
        }
        // git's parse_config silently ignores any other submodule.<name>.<key>.
        _ => {}
    }
}

/// Port of `check_submodule_name` (git `submodule-config.c`). Returns `true`
/// if `name` is syntactically acceptable as a `.gitmodules` subsection, `false`
/// otherwise (git's `0` vs `-1`). Rejects empty names and any `..` path
/// component (using the cross-platform separator set `/` and `\` so the rule is
/// OS-independent).
pub fn check_submodule_name(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }
    let bytes = name.as_bytes();
    // git starts "inside a component" then re-checks at every separator.
    let mut i = 0;
    let mut at_component_start = true;
    while i <= bytes.len() {
        if at_component_start && is_xplatform_dir_sep_component(bytes, i) {
            return false;
        }
        at_component_start = false;
        if i < bytes.len() && is_xplatform_dir_sep(bytes[i]) {
            at_component_start = true;
        }
        i += 1;
    }
    true
}

/// A `..` component begins at `i` when bytes[i..] is `..` followed by EOS or a
/// separator. Mirrors git's `name[0]=='.' && name[1]=='.' && (!name[2] ||
/// sep(name[2]))` check applied at each component boundary.
fn is_xplatform_dir_sep_component(bytes: &[u8], i: usize) -> bool {
    bytes.get(i) == Some(&b'.')
        && bytes.get(i + 1) == Some(&b'.')
        && match bytes.get(i + 2) {
            None => true,
            Some(&c) => is_xplatform_dir_sep(c),
        }
}

fn is_xplatform_dir_sep(c: u8) -> bool {
    c == b'/' || c == b'\\'
}

/// Port of `check_submodule_url` (git `submodule-config.c`). Returns `true`
/// if the URL is acceptable (per the CVE-2020-11008 / option-injection checks),
/// `false` otherwise (git's `0` vs `-1`). Mirrors the relative-URL and
/// `git://` newline/`../`-escape checks; the http(s) `url_normalize` round-trip
/// is approximated by the same newline check on the decoded form (sley has no
/// `url_normalize` yet — TODO(submodule) below).
pub fn check_submodule_url(url: &str) -> bool {
    if looks_like_command_line_option(url) {
        return false;
    }

    if submodule_url_is_relative(url) || url.starts_with("git://") {
        let decoded = url_decode(url);
        if decoded.contains('\n') {
            return false;
        }
        // URLs that escape their root via "../" can overwrite the host field.
        let (dotdots, next) = count_leading_dotdots(url);
        if dotdots > 0 {
            let first = next.as_bytes().first().copied();
            if first == Some(b':') || first == Some(b'/') {
                return false;
            }
        }
    } else if let Some(curl_url) = url_to_curl_url(url) {
        // git runs the curl url through `url_normalize`, rejecting anything that
        // is not a valid absolute URL: a missing/empty scheme, a missing "://",
        // or a missing host for a non-`file:` scheme (CVE-2020-11008 family).
        if !curl_url_is_normalizable(curl_url) {
            return false;
        }
        let decoded = url_decode(curl_url);
        if decoded.contains('\n') {
            return false;
        }
    }

    true
}

/// Minimal port of git's `url_normalize` validity gate (`urlmatch.c`): whether a
/// curl url is a normalizable absolute URL. Rejects (returns false) a url whose
/// scheme is empty / not letter-led / not followed by "://", or whose host is
/// missing — the conditions that make `url_normalize` return NULL and so make
/// `check_submodule_url` reject the submodule url.
fn curl_url_is_normalizable(url: &str) -> bool {
    let bytes = url.as_bytes();
    // scheme: a non-empty run of [A-Za-z0-9+.-] starting with a letter, then "://"
    let scheme_len = bytes
        .iter()
        .take_while(|&&c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'-' | b'.'))
        .count();
    if scheme_len == 0
        || !bytes[0].is_ascii_alphabetic()
        || scheme_len + 3 > bytes.len()
        || &bytes[scheme_len..scheme_len + 3] != b"://"
    {
        return false;
    }
    let scheme = &url[..scheme_len];
    let after_scheme = &url[scheme_len + 3..];
    // Skip an optional `user[:pass]@` that precedes the first `/?#`.
    let authority_end = after_scheme
        .find(['/', '?', '#'])
        .unwrap_or(after_scheme.len());
    let host_start = match after_scheme.find('@') {
        Some(at) if at < authority_end => &after_scheme[at + 1..],
        _ => after_scheme,
    };
    // A missing host (empty, or immediately a `:/?#`) is invalid for every
    // scheme except `file:`.
    let host_missing = host_start
        .as_bytes()
        .first()
        .is_none_or(|c| matches!(c, b':' | b'/' | b'?' | b'#'));
    if host_missing && !scheme.eq_ignore_ascii_case("file") {
        return false;
    }
    true
}

/// `starts_with_dot_slash` (git `dir.h`, XPLATFORM): a leading `./` where the
/// separator is EITHER `/` or `\` — the cross-platform form git uses for
/// submodule urls, so a `.\`-prefixed url is relative on every OS.
fn starts_with_dot_slash_xplat(url: &str) -> bool {
    let bytes = url.as_bytes();
    bytes.first() == Some(&b'.') && matches!(bytes.get(1), Some(b'/') | Some(b'\\'))
}

/// `starts_with_dot_dot_slash` (git `dir.h`, XPLATFORM): a leading `../` with a
/// `/`-or-`\` separator.
fn starts_with_dot_dot_slash_xplat(url: &str) -> bool {
    let bytes = url.as_bytes();
    bytes.first() == Some(&b'.')
        && bytes.get(1) == Some(&b'.')
        && matches!(bytes.get(2), Some(b'/') | Some(b'\\'))
}

fn submodule_url_is_relative(url: &str) -> bool {
    starts_with_dot_slash_xplat(url) || starts_with_dot_dot_slash_xplat(url)
}

/// Port of `count_leading_dotdots` (git `submodule-config.c`): counts leading
/// `../` components (skipping `./`) and returns the remaining suffix. Both `/`
/// and `\` count as the separator (XPLATFORM), matching git so a `..\`-escaping
/// url is caught on every OS.
fn count_leading_dotdots(url: &str) -> (usize, &str) {
    let mut result = 0;
    let mut rest = url;
    loop {
        if starts_with_dot_dot_slash_xplat(rest) {
            result += 1;
            rest = &rest[3..];
        } else if starts_with_dot_slash_xplat(rest) {
            rest = &rest[2..];
        } else {
            return (result, rest);
        }
    }
}

/// Port of `url_to_curl_url` (git `submodule-config.c`): if the transport is one
/// git-remote-curl handles, returns the URL that would be passed to it.
fn url_to_curl_url(url: &str) -> Option<&str> {
    for prefix in ["http::", "https::", "ftp::", "ftps::"] {
        if let Some(stripped) = url.strip_prefix(prefix) {
            return Some(stripped);
        }
    }
    for prefix in ["http://", "https://", "ftp://", "ftps://"] {
        if url.starts_with(prefix) {
            return Some(url);
        }
    }
    None
}

/// Port of git's `looks_like_command_line_option`: a value starting with `-`
/// could be mistaken for a CLI flag when passed to a child git process.
pub fn looks_like_command_line_option(value: &str) -> bool {
    value.starts_with('-')
}

/// Minimal percent-decoder for the `check_submodule_url` newline check. Mirrors
/// git's `url_decode` for the bytes we care about (`%0a` etc.); leaves
/// malformed escapes intact.
fn url_decode(input: &str) -> String {
    let bytes = input.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            let hi = hex_val(bytes[i + 1]);
            let lo = hex_val(bytes[i + 2]);
            if let (Some(hi), Some(lo)) = (hi, lo) {
                out.push((hi << 4) | lo);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn hex_val(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'a'..=b'f' => Some(c - b'a' + 10),
        b'A'..=b'F' => Some(c - b'A' + 10),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use sley_config::GitConfig;

    fn config_from(text: &str) -> GitConfig {
        GitConfig::parse(text.as_bytes()).expect("valid config")
    }

    #[test]
    fn parses_basic_submodule() {
        let cfg =
            config_from("[submodule \"lib\"]\n\tpath = lib\n\turl = https://example.com/lib.git\n");
        let set = SubmoduleConfigSet::parse(&cfg);
        assert_eq!(set.len(), 1);
        let sub = set.from_name("lib").expect("lib present");
        assert_eq!(sub.path.as_deref(), Some("lib"));
        assert_eq!(sub.url.as_deref(), Some("https://example.com/lib.git"));
        assert_eq!(set.from_path("lib").map(|s| s.name.as_str()), Some("lib"));
    }

    #[test]
    fn first_value_wins_and_warns_on_duplicate() {
        let cfg = config_from("[submodule \"x\"]\n\tpath = a\n\tpath = b\n");
        let set = SubmoduleConfigSet::parse(&cfg);
        assert_eq!(
            set.from_name("x").and_then(|s| s.path.as_deref()),
            Some("a")
        );
        assert!(set.warnings.iter().any(|w| matches!(
            w,
            ParseWarning::MultipleConfig { option, .. } if option == "path"
        )));
    }

    #[test]
    fn suspicious_name_dropped() {
        let cfg = config_from("[submodule \"../evil\"]\n\tpath = x\n");
        let set = SubmoduleConfigSet::parse(&cfg);
        assert!(set.is_empty());
        assert!(matches!(
            set.warnings.first(),
            Some(ParseWarning::SuspiciousName { .. })
        ));
    }

    #[test]
    fn check_submodule_name_rejects_dotdot() {
        assert!(!check_submodule_name("a/../b"));
        assert!(!check_submodule_name(".."));
        assert!(!check_submodule_name("../x"));
        assert!(!check_submodule_name("a/.."));
        assert!(!check_submodule_name(""));
        assert!(check_submodule_name("normal/name"));
        assert!(check_submodule_name("a..b"));
        assert!(check_submodule_name("..."));
    }

    #[test]
    fn check_submodule_url_rejects_escapes() {
        // Looks like a command-line option.
        assert!(!check_submodule_url("-upload-pack=evil"));
        // Relative URL whose first byte after the leading "../" is ':' / '/',
        // the CVE-2020-11008 host-overwrite vector git guards.
        assert!(!check_submodule_url("../:evil"));
        assert!(!check_submodule_url("..//evil"));
        // A relative URL with a normal first component after the "../" is fine
        // (git only rejects the ':'/'/' first byte).
        assert!(check_submodule_url("../../../host/path"));
        assert!(check_submodule_url("https://example.com/ok.git"));
        assert!(check_submodule_url("./relative"));
        // Embedded newline in a git:// / relative URL is rejected.
        assert!(!check_submodule_url("git://h/%0arepo"));
    }

    #[test]
    fn update_strategy_parses() {
        assert_eq!(parse_update_type("checkout"), UpdateType::Checkout);
        assert_eq!(parse_update_type("none"), UpdateType::None);
        assert_eq!(parse_update_type("!cmd"), UpdateType::Command);
        assert_eq!(parse_update_type("bogus"), UpdateType::Unspecified);
        let strat = parse_update_strategy("!run").expect("command");
        assert_eq!(strat.kind, UpdateType::Command);
        assert_eq!(strat.command.as_deref(), Some("run"));
        assert!(parse_update_strategy("bogus").is_none());
    }

    #[test]
    fn fetch_recurse_parses() {
        assert_eq!(parse_fetch_recurse("true"), RecurseMode::On);
        assert_eq!(parse_fetch_recurse("false"), RecurseMode::Off);
        assert_eq!(parse_fetch_recurse("on-demand"), RecurseMode::OnDemand);
        assert_eq!(parse_fetch_recurse("garbage"), RecurseMode::Error);
    }

    #[test]
    fn shallow_and_branch_parse() {
        let cfg = config_from("[submodule \"s\"]\n\tbranch = main\n\tshallow = true\n");
        let set = SubmoduleConfigSet::parse(&cfg);
        let sub = set.from_name("s").expect("s");
        assert_eq!(sub.branch.as_deref(), Some("main"));
        assert_eq!(sub.recommend_shallow, Some(true));
    }
}