Skip to main content

grit_lib/check_ref_format/
ref_name.rs

1//! Owned and borrowed ref names with policy-driven validation.
2
3use std::borrow::{Borrow, Cow};
4use std::fmt;
5use std::ops::Deref;
6use std::str;
7
8use super::{check_refname_format_borrowed, refname_is_safe, RefFormatOptions, RefNameError};
9
10/// Options controlling how a ref name is validated when parsed.
11///
12/// The default matches Git's normal full-ref rules (`git check-ref-format` with no flags).
13#[derive(Debug, Clone, Default)]
14#[non_exhaustive]
15pub struct RefNamePolicy {
16    format: RefFormatOptions,
17    storable: bool,
18    safe_for_fs: bool,
19    receive_pack_delete: Option<bool>,
20    advertised_fetch: bool,
21    advertised_symref: bool,
22}
23
24impl RefNamePolicy {
25    /// Git's default full-ref format rules.
26    #[must_use]
27    pub fn new() -> Self {
28        Self::default()
29    }
30
31    /// Allow a single-level ref name (no `/` separator required).
32    #[must_use]
33    pub fn allow_onelevel(mut self) -> Self {
34        self.format.allow_onelevel = true;
35        self
36    }
37
38    /// Allow exactly one `*` wildcard anywhere in the name.
39    #[must_use]
40    pub fn refspec_pattern(mut self) -> Self {
41        self.format.refspec_pattern = true;
42        self
43    }
44
45    /// Collapse consecutive slashes and strip a leading `/` before validating.
46    ///
47    /// When the name changes, [`RefName::parse`] returns the normalized owned string.
48    /// [`RefNameRef::parse`] rejects names that would require normalization.
49    #[must_use]
50    pub fn normalize(mut self) -> Self {
51        self.format.normalize = true;
52        self
53    }
54
55    /// Require the name to be safe to store (HEAD, pseudo-refs, and valid `refs/…` names).
56    #[must_use]
57    pub fn storable(mut self) -> Self {
58        self.storable = true;
59        self
60    }
61
62    /// Require the name to be safe to map to a path under ref storage (`refname_is_safe`).
63    #[must_use]
64    pub fn safe_for_fs(mut self) -> Self {
65        self.safe_for_fs = true;
66        self
67    }
68
69    /// Require a receive-pack wire ref name (`refs/…` with delete-aware one-level rules).
70    #[must_use]
71    pub fn receive_pack(mut self, is_delete: bool) -> Self {
72        self.receive_pack_delete = Some(is_delete);
73        self
74    }
75
76    /// Require a fetch/upload-pack advertised ref (`refs/…` plus default format rules).
77    #[must_use]
78    pub fn advertised_fetch(mut self) -> Self {
79        self.advertised_fetch = true;
80        self
81    }
82
83    /// Require a symref advertisement target (format with `--allow-onelevel`).
84    #[must_use]
85    pub fn advertised_symref(mut self) -> Self {
86        self.advertised_symref = true;
87        self
88    }
89
90    pub(crate) fn format_options(&self) -> &RefFormatOptions {
91        &self.format
92    }
93
94    pub(crate) fn receive_pack_delete(&self) -> Option<bool> {
95        self.receive_pack_delete
96    }
97
98    pub(crate) fn requires_storable(&self) -> bool {
99        self.storable
100    }
101
102    pub(crate) fn requires_safe_for_fs(&self) -> bool {
103        self.safe_for_fs
104    }
105
106    pub(crate) fn requires_advertised_fetch(&self) -> bool {
107        self.advertised_fetch
108    }
109
110    pub(crate) fn requires_advertised_symref(&self) -> bool {
111        self.advertised_symref
112    }
113
114    /// Policy for symref advertisement targets (`--allow-onelevel` format rules).
115    #[must_use]
116    pub fn symref_target() -> Self {
117        Self::new().allow_onelevel()
118    }
119}
120
121/// Validated full ref name (for example `refs/heads/main`).
122#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
123pub struct RefName(String);
124
125/// Borrowed validated ref name (like [`std::path::Path`] to [`std::path::PathBuf`]).
126#[repr(transparent)]
127#[derive(PartialEq, Eq, PartialOrd, Ord)]
128pub struct RefNameRef(str);
129
130impl RefName {
131    /// Parse and validate `name` according to `policy`.
132    ///
133    /// # Errors
134    ///
135    /// Returns [`RefNameError`] when the name fails any enabled rule.
136    pub fn parse(name: &str, policy: &RefNamePolicy) -> Result<Self, RefNameError> {
137        let format = effective_format_options(name, policy);
138        let normalized = check_refname_format_borrowed(name, &format)?;
139        let stored: Cow<'_, str> = normalized;
140        apply_policy_checks(stored.as_ref(), policy)?;
141        Ok(Self(stored.into_owned()))
142    }
143
144    /// Parse a branch short name into `refs/heads/<name>`.
145    ///
146    /// # Errors
147    ///
148    /// Returns [`RefNameError`] when the short name or full ref would be invalid.
149    pub fn branch(short: &str) -> Result<Self, RefNameError> {
150        branch_short_checks(short)?;
151        Self::parse(&format!("refs/heads/{short}"), &RefNamePolicy::default())
152    }
153
154    /// Parse a tag short name into `refs/tags/<name>`.
155    ///
156    /// # Errors
157    ///
158    /// Returns [`RefNameError`] when the short name or full ref would be invalid.
159    pub fn tag(short: &str) -> Result<Self, RefNameError> {
160        if short.is_empty() {
161            return Err(RefNameError::Empty);
162        }
163        Self::parse(&format!("refs/tags/{short}"), &RefNamePolicy::default())
164    }
165
166    /// Construct a ref name read from storage without re-validating.
167    #[must_use]
168    pub fn from_trusted(name: impl Into<String>) -> Self {
169        Self(name.into())
170    }
171
172    /// Parse and validate using default Git full-ref format rules, plus `HEAD`.
173    ///
174    /// # Errors
175    ///
176    /// Returns [`RefNameError`] when the name is empty or otherwise invalid.
177    pub fn try_from(name: &str) -> Result<Self, RefNameError> {
178        if name == "HEAD" {
179            return Ok(Self(name.to_owned()));
180        }
181        Self::parse(name, &RefNamePolicy::default())
182    }
183
184    /// Borrow the stored ref name.
185    #[must_use]
186    pub fn as_str(&self) -> &str {
187        &self.0
188    }
189}
190
191impl RefNameRef {
192    /// Parse `name` in place when validation does not require owning a normalized copy.
193    ///
194    /// # Errors
195    ///
196    /// Returns [`RefNameError::NormalizationRequired`] when `policy` enables normalization and
197    /// the normalized form differs from `name`. Use [`RefName::parse`] in that case.
198    pub fn parse<'a>(name: &'a str, policy: &RefNamePolicy) -> Result<&'a Self, RefNameError> {
199        let format = effective_format_options(name, policy);
200        if format.normalize {
201            let normalized = check_refname_format_borrowed(name, &format)?;
202            if let Cow::Owned(_) = normalized {
203                return Err(RefNameError::NormalizationRequired);
204            }
205        } else {
206            check_refname_format_borrowed(name, &format)?;
207        }
208        apply_policy_checks(name, policy)?;
209        Ok(Self::new(name))
210    }
211
212    /// Borrow the validated ref name as UTF-8.
213    #[must_use]
214    pub fn as_str(&self) -> &str {
215        &self.0
216    }
217
218    /// Borrow a name read from ref storage without re-validating.
219    #[must_use]
220    pub fn from_trusted(s: &str) -> &Self {
221        Self::new(s)
222    }
223
224    #[must_use]
225    fn new(s: &str) -> &Self {
226        // SAFETY: RefNameRef is repr(transparent) over str.
227        unsafe { &*(s as *const str as *const RefNameRef) }
228    }
229}
230
231impl AsRef<RefNameRef> for str {
232    fn as_ref(&self) -> &RefNameRef {
233        RefNameRef::from_trusted(self)
234    }
235}
236
237impl AsRef<RefNameRef> for String {
238    fn as_ref(&self) -> &RefNameRef {
239        RefNameRef::from_trusted(self.as_str())
240    }
241}
242
243impl AsRef<RefNameRef> for RefNameRef {
244    fn as_ref(&self) -> &RefNameRef {
245        self
246    }
247}
248
249/// Format flags for the first validation pass: pseudo-refs and HEAD need
250/// `--allow-onelevel` when `storable()` or `advertised_symref()` is enabled.
251fn effective_format_options(name: &str, policy: &RefNamePolicy) -> RefFormatOptions {
252    let mut format = policy.format_options().clone();
253    if !name.starts_with("refs/")
254        && (policy.requires_storable() || policy.requires_advertised_symref())
255    {
256        format.allow_onelevel = true;
257    }
258    format
259}
260
261fn branch_short_checks(name: &str) -> Result<(), RefNameError> {
262    if name.is_empty() {
263        return Err(RefNameError::Empty);
264    }
265    if name.starts_with('-') {
266        return Err(RefNameError::BranchStartsWithDash);
267    }
268    if name == "HEAD" {
269        return Err(RefNameError::ReservedBranchName);
270    }
271    Ok(())
272}
273
274fn apply_policy_checks(name: &str, policy: &RefNamePolicy) -> Result<(), RefNameError> {
275    if policy.requires_advertised_symref() {
276        RefNameRef::parse(name, &RefNamePolicy::symref_target())?;
277    }
278
279    if policy.requires_advertised_fetch() && !is_valid_fetch_advertised_ref(name) {
280        return Err(RefNameError::NotAdvertisedFetchRef);
281    }
282
283    if let Some(is_delete) = policy.receive_pack_delete() {
284        if !receive_pack_refname_ok(name, is_delete) {
285            return Err(RefNameError::ReceivePackRefused);
286        }
287    }
288
289    if policy.requires_safe_for_fs() && !refname_is_safe(name) {
290        return Err(RefNameError::UnsafeForFilesystem);
291    }
292
293    if policy.requires_storable() && !is_storable_ref_name(name) {
294        return Err(RefNameError::NotStorable);
295    }
296
297    Ok(())
298}
299
300pub(crate) fn is_storable_ref_name(name: &str) -> bool {
301    if let Some(rest) = name.strip_prefix("refs/") {
302        !rest.is_empty() && is_valid_fetch_advertised_ref(name)
303    } else {
304        refname_is_safe(name)
305    }
306}
307
308pub(crate) fn is_valid_fetch_advertised_ref(name: &str) -> bool {
309    if !name.starts_with("refs/") {
310        return false;
311    }
312    check_refname_format_borrowed(name, &RefFormatOptions::default()).is_ok()
313}
314
315pub(crate) fn receive_pack_refname_ok(refname: &str, is_delete: bool) -> bool {
316    if !refname.starts_with("refs/") {
317        return false;
318    }
319    check_refname_format_borrowed(
320        &refname[5..],
321        &RefFormatOptions {
322            allow_onelevel: is_delete,
323            ..RefFormatOptions::default()
324        },
325    )
326    .is_ok()
327}
328
329impl AsRef<str> for RefName {
330    fn as_ref(&self) -> &str {
331        self.as_str()
332    }
333}
334
335impl From<RefName> for String {
336    fn from(name: RefName) -> Self {
337        name.0
338    }
339}
340
341impl AsRef<RefNameRef> for RefName {
342    fn as_ref(&self) -> &RefNameRef {
343        RefNameRef::new(self.as_str())
344    }
345}
346
347impl Borrow<RefNameRef> for RefName {
348    fn borrow(&self) -> &RefNameRef {
349        RefNameRef::new(self.as_str())
350    }
351}
352
353impl Deref for RefName {
354    type Target = RefNameRef;
355
356    fn deref(&self) -> &RefNameRef {
357        RefNameRef::new(self.as_str())
358    }
359}
360
361impl fmt::Display for RefName {
362    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363        f.write_str(&self.0)
364    }
365}
366
367impl fmt::Display for RefNameRef {
368    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369        f.write_str(self.as_str())
370    }
371}
372
373#[cfg(feature = "serde-models")]
374impl serde::Serialize for RefName {
375    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
376    where
377        S: serde::Serializer,
378    {
379        serializer.serialize_str(self.as_str())
380    }
381}