grit-lib 0.5.18

Core library for the grit Git implementation
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
//! Refspec parsing and validation — a port of `git/refspec.c`.
//!
//! A *refspec* describes how references map between a local and a remote
//! repository.  It has the general form `[+|^]<src>[:<dst>]`.  This module
//! parses a single refspec string and validates it according to the same rules
//! as Git's `parse_refspec()`, distinguishing fetch refspecs from push
//! refspecs (the two have slightly different validity rules).
//!
//! The primary entry points are [`parse_fetch_refspec`] and
//! [`parse_push_refspec`], which return [`RefspecItem`] on success or
//! [`RefspecError::Invalid`] when the refspec is malformed.  Callers that only
//! care about validity (for example loading `remote.<name>.fetch` /
//! `remote.<name>.push` config) can use [`valid_fetch_refspec`] and
//! [`valid_push_refspec`].

use crate::check_ref_format::{check_refname_format, RefNameOptions};

/// A parsed refspec item.
///
/// Holds a parsed refspec, capturing the
/// modifier flags and the source/destination sides of the mapping.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RefspecItem {
    /// The `+` modifier was present (force / non-fast-forward update).
    pub force: bool,
    /// The `^` modifier was present (negative refspec — exclusion).
    pub negative: bool,
    /// This refspec is the bare `:` (or `+:`) push refspec for matching refs.
    pub matching: bool,
    /// The refspec uses a `*` glob pattern.
    pub pattern: bool,
    /// The source side is an exact (full-length hex) object id.
    pub exact_sha1: bool,
    /// The source side (`<src>`), or `None` when absent.
    pub src: Option<String>,
    /// The destination side (`<dst>`), or `None` when no `:` was present.
    pub dst: Option<String>,
}

/// Error returned when a refspec cannot be parsed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RefspecError {
    /// The refspec string is invalid.
    Invalid(String),
}

impl std::fmt::Display for RefspecError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RefspecError::Invalid(s) => write!(f, "invalid refspec '{s}'"),
        }
    }
}

impl std::error::Error for RefspecError {}

/// Length of a full SHA-1 hex object id.
const SHA1_HEXSZ: usize = 40;

/// Returns `true` when `s` is a string of exactly `SHA1_HEXSZ` hex digits.
fn is_exact_sha1_hex(s: &str) -> bool {
    s.len() == SHA1_HEXSZ && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Validate `name` as a refname using the same flags as Git's
/// `check_refname_format` with `REFNAME_ALLOW_ONELEVEL` and, when `is_glob` is
/// set, `REFNAME_REFSPEC_PATTERN`.
///
/// Returns `true` when the name is well-formed.
fn refname_ok(name: &str, is_glob: bool) -> bool {
    let opts = RefNameOptions {
        allow_onelevel: true,
        refspec_pattern: is_glob,
        normalize: false,
    };
    check_refname_format(name, &opts).is_ok()
}

/// Parse a single refspec.  `fetch` selects fetch (`true`) vs push (`false`)
/// validity rules.
///
/// This is a direct port of `parse_refspec()` in `git/refspec.c`.
fn parse_refspec(refspec: &str, fetch: bool) -> Result<RefspecItem, RefspecError> {
    let bytes = refspec.as_bytes();
    let invalid = || RefspecError::Invalid(refspec.to_owned());

    let mut item = RefspecItem::default();
    let mut is_glob = false;

    // Leading modifier: '+' (force) or '^' (negative).
    let mut lhs_start = 0usize;
    if let Some(&first) = bytes.first() {
        if first == b'+' {
            item.force = true;
            lhs_start = 1;
        } else if first == b'^' {
            item.negative = true;
            lhs_start = 1;
        }
    }

    let lhs = &refspec[lhs_start..];

    // rhs points to the last ':' within lhs (strrchr).
    let colon_pos = lhs.rfind(':');

    // Negative refspecs only have one side.
    if item.negative && colon_pos.is_some() {
        return Err(invalid());
    }

    // Special case ":" (or "+:") as a push refspec for matching refs.
    // In C: rhs == lhs && rhs[1] == '\0' — i.e. the ':' is the first char of
    // lhs and is the only char.
    if !fetch && colon_pos == Some(0) && lhs.len() == 1 {
        item.matching = true;
        return Ok(item);
    }

    // Compute src (lhs) and dst (rhs) substrings.
    let (lhs_str, rhs_opt): (&str, Option<&str>) = match colon_pos {
        Some(pos) => (&lhs[..pos], Some(&lhs[pos + 1..])),
        None => (lhs, None),
    };

    if let Some(rhs) = rhs_opt {
        let rlen = rhs.len();
        is_glob = rlen >= 1 && rhs.contains('*');
        item.dst = Some(rhs.to_owned());
    } else {
        item.dst = None;
    }

    let llen = lhs_str.len();
    if llen >= 1 && lhs_str.contains('*') {
        // LHS has a '*'.
        let rhs_empty = rhs_opt.is_some_and(|r| r.is_empty());
        if (rhs_opt.is_some() && !is_glob && !rhs_empty)
            || (rhs_opt.is_none() && !item.negative && fetch)
        {
            return Err(invalid());
        }
        is_glob = true;
    } else if rhs_opt.is_some() && is_glob {
        // RHS is a glob but LHS is not.
        return Err(invalid());
    }

    item.pattern = is_glob;
    if llen == 1 && lhs_str == "@" {
        item.src = Some("HEAD".to_owned());
    } else {
        item.src = Some(lhs_str.to_owned());
    }
    let src = item.src.as_deref().unwrap_or("");

    if item.negative {
        // Negative refspecs only have a LHS.
        if src.is_empty() {
            return Err(invalid()); // must not be empty
        } else if is_exact_sha1_hex(src) {
            return Err(invalid()); // cannot be exact sha1
        } else if refname_ok(src, is_glob) {
            // valid looking ref is ok
        } else {
            return Err(invalid());
        }
        return Ok(item);
    }

    if fetch {
        // LHS
        if src.is_empty() {
            // empty is ok; it means "HEAD"
        } else if is_exact_sha1_hex(src) {
            item.exact_sha1 = true; // ok
        } else if refname_ok(src, is_glob) {
            // valid looking ref is ok
        } else {
            return Err(invalid());
        }
        // RHS
        match item.dst.as_deref() {
            None | Some("") => {} // missing/empty: do not store
            Some(dst) => {
                if !refname_ok(dst, is_glob) {
                    return Err(invalid());
                }
            }
        }
    } else {
        // push
        // LHS
        if src.is_empty() {
            // empty is ok
        } else if is_glob {
            if !refname_ok(src, is_glob) {
                return Err(invalid());
            }
        } else {
            // anything goes, for now
        }
        // RHS
        match item.dst.as_deref() {
            None => {
                // missing is allowed, but LHS then must be a valid looking ref.
                if !refname_ok(src, is_glob) {
                    return Err(invalid());
                }
            }
            Some("") => {
                // empty is not allowed.
                return Err(invalid());
            }
            Some(dst) => {
                if !refname_ok(dst, is_glob) {
                    return Err(invalid());
                }
            }
        }
    }

    Ok(item)
}

/// Parse a fetch refspec, returning the parsed item or an error.
pub fn parse_fetch_refspec(refspec: &str) -> Result<RefspecItem, RefspecError> {
    parse_refspec(refspec, true)
}

/// Parse a push refspec, returning the parsed item or an error.
pub fn parse_push_refspec(refspec: &str) -> Result<RefspecItem, RefspecError> {
    parse_refspec(refspec, false)
}

/// Returns `true` when `refspec` is a valid fetch refspec.
pub fn valid_fetch_refspec(refspec: &str) -> bool {
    parse_refspec(refspec, true).is_ok()
}

/// Returns `true` when `refspec` is a valid push refspec.
pub fn valid_push_refspec(refspec: &str) -> bool {
    parse_refspec(refspec, false).is_ok()
}

/// When a refspec side contains exactly one `*`, map `from_ref` through that glob into `into_template`.
fn translate_single_star(
    from_template: &str,
    into_template: &str,
    from_ref: &str,
) -> Option<String> {
    let (from_pre, from_post) = split_one_star(from_template)?;
    let (into_pre, into_post) = split_one_star(into_template)?;
    if !from_ref.starts_with(from_pre) || !from_ref.ends_with(from_post) {
        return None;
    }
    let middle_len = from_ref
        .len()
        .checked_sub(from_pre.len() + from_post.len())?;
    let middle = &from_ref[from_pre.len()..from_pre.len() + middle_len];
    Some(format!("{into_pre}{middle}{into_post}"))
}

fn split_one_star(template: &str) -> Option<(&str, &str)> {
    let star = template.find('*')?;
    if template[star + 1..].contains('*') {
        return None;
    }
    Some((&template[..star], &template[star + 1..]))
}

fn refname_matches_template(template: &str, is_pattern: bool, refname: &str) -> bool {
    if is_pattern {
        translate_single_star(template, template, refname).is_some()
    } else {
        template == refname
    }
}

/// Binding from a local ref to the upstream ref name implied by fetch refspecs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FetchLocalBinding {
    pub force: bool,
    pub upstream_ref: String,
}

fn positive_local_binding(spec: &RefspecItem, local_ref: &str) -> Option<FetchLocalBinding> {
    if spec.negative {
        return None;
    }
    let dst = spec.dst.as_deref()?;
    let src = spec.src.as_deref().unwrap_or("");
    let upstream_ref = if spec.pattern {
        translate_single_star(dst, src, local_ref)?
    } else if dst == local_ref {
        src.to_owned()
    } else {
        return None;
    };
    Some(FetchLocalBinding {
        force: spec.force,
        upstream_ref,
    })
}

fn excluded_by_negative_specs(specs: &[RefspecItem], upstream_ref: &str) -> bool {
    specs.iter().any(|spec| {
        spec.negative
            && spec
                .src
                .as_deref()
                .is_some_and(|src| refname_matches_template(src, spec.pattern, upstream_ref))
    })
}

/// Whether `local_ref` is a destination of these fetch refspecs and not ruled out by `^` lines.
#[must_use]
pub(crate) fn fetch_specs_bind_local_ref(
    specs: &[RefspecItem],
    local_ref: &str,
) -> Option<FetchLocalBinding> {
    let binding = specs
        .iter()
        .find_map(|spec| positive_local_binding(spec, local_ref))?;
    if excluded_by_negative_specs(specs, &binding.upstream_ref) {
        return None;
    }
    Some(binding)
}

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

    // Mirrors the cases in git's t5511-refspec.sh.

    fn fetch_valid(s: &str) {
        assert!(valid_fetch_refspec(s), "expected fetch '{s}' to be valid");
    }
    fn fetch_invalid(s: &str) {
        assert!(
            !valid_fetch_refspec(s),
            "expected fetch '{s}' to be invalid"
        );
    }
    fn push_valid(s: &str) {
        assert!(valid_push_refspec(s), "expected push '{s}' to be valid");
    }
    fn push_invalid(s: &str) {
        assert!(!valid_push_refspec(s), "expected push '{s}' to be invalid");
    }

    #[test]
    fn empty_and_colon() {
        push_invalid("");
        push_valid(":");
        push_invalid("::");
        push_valid("+:");
        fetch_valid("");
        fetch_valid(":");
        fetch_invalid("::");
    }

    #[test]
    fn glob_balance() {
        push_valid("refs/heads/*:refs/remotes/frotz/*");
        push_invalid("refs/heads/*:refs/remotes/frotz");
        push_invalid("refs/heads:refs/remotes/frotz/*");
        push_valid("refs/heads/main:refs/remotes/frotz/xyzzy");

        fetch_valid("refs/heads/*:refs/remotes/frotz/*");
        fetch_valid("refs/heads/*:");
        fetch_invalid("refs/heads/*:refs/remotes/frotz");
        fetch_invalid("refs/heads:refs/remotes/frotz/*");
        fetch_valid("refs/heads/main:refs/remotes/frotz/xyzzy");
        fetch_invalid("refs/heads/main::refs/remotes/frotz/xyzzy");
        fetch_invalid("refs/heads/maste :refs/remotes/frotz/xyzzy");
    }

    #[test]
    fn rev_expressions() {
        push_valid("main~1:refs/remotes/frotz/backup");
        fetch_invalid("main~1:refs/remotes/frotz/backup");
        push_valid("HEAD~4:refs/remotes/frotz/new");
        fetch_invalid("HEAD~4:refs/remotes/frotz/new");
    }

    #[test]
    fn bare_head_and_at() {
        push_valid("HEAD");
        fetch_valid("HEAD");
        push_valid("@");
        fetch_valid("@");
        push_invalid("refs/heads/ nitfol");
        fetch_invalid("refs/heads/ nitfol");
    }

    #[test]
    fn head_colon() {
        push_invalid("HEAD:");
        fetch_valid("HEAD:");
        push_invalid("refs/heads/ nitfol:");
        fetch_invalid("refs/heads/ nitfol:");
    }

    #[test]
    fn delete_specs() {
        push_valid(":refs/remotes/frotz/deleteme");
        fetch_valid(":refs/remotes/frotz/HEAD-to-me");
        push_invalid(":refs/remotes/frotz/delete me");
        fetch_invalid(":refs/remotes/frotz/HEAD to me");
    }

    #[test]
    fn star_placements() {
        fetch_valid("refs/heads/*/for-linus:refs/remotes/mine/*-blah");
        push_valid("refs/heads/*/for-linus:refs/remotes/mine/*-blah");
        fetch_valid("refs/heads*/for-linus:refs/remotes/mine/*");
        push_valid("refs/heads*/for-linus:refs/remotes/mine/*");
        fetch_invalid("refs/heads/*/*/for-linus:refs/remotes/mine/*");
        push_invalid("refs/heads/*/*/for-linus:refs/remotes/mine/*");
        fetch_invalid("refs/heads/*g*/for-linus:refs/remotes/mine/*");
        push_invalid("refs/heads/*g*/for-linus:refs/remotes/mine/*");
        fetch_valid("refs/heads/*/for-linus:refs/remotes/mine/*");
        push_valid("refs/heads/*/for-linus:refs/remotes/mine/*");
    }

    #[test]
    fn utf8_and_tab() {
        fetch_valid("refs/heads/\u{00C4}");
        fetch_invalid("refs/heads/\ttab");
    }

    #[test]
    fn fetch_specs_bind_local_ref_maps_tracking_branch() {
        let specs = vec![parse_fetch_refspec("+refs/heads/*:refs/remotes/origin/*").unwrap()];
        let binding = fetch_specs_bind_local_ref(&specs, "refs/remotes/origin/main").unwrap();
        assert_eq!(binding.upstream_ref, "refs/heads/main");
    }

    #[test]
    fn fetch_specs_bind_local_ref_honors_negative_line() {
        let specs = vec![
            parse_fetch_refspec("+refs/heads/*:refs/remotes/origin/*").unwrap(),
            parse_fetch_refspec("^refs/heads/private").unwrap(),
        ];
        assert!(fetch_specs_bind_local_ref(&specs, "refs/remotes/origin/main").is_some());
        assert!(fetch_specs_bind_local_ref(&specs, "refs/remotes/origin/private").is_none());
    }
}