Skip to main content

gix_validate/
tag.rs

1use bstr::{BStr, BString, ByteSlice};
2
3///
4pub mod name {
5    use bstr::BString;
6
7    /// The error returned by [`name()`][super::name()].
8    #[derive(Debug)]
9    #[expect(missing_docs)]
10    #[non_exhaustive]
11    pub enum Error {
12        InvalidByte { byte: BString },
13        StartsWithSlash,
14        RepeatedSlash,
15        RepeatedDot,
16        LockFileSuffix,
17        ReflogPortion,
18        Asterisk,
19        StartsWithDot,
20        EndsWithDot,
21        EndsWithSlash,
22        Empty,
23    }
24
25    impl std::fmt::Display for Error {
26        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27            match self {
28                Error::InvalidByte { byte } => write!(
29                    f,
30                    "A ref must not contain invalid bytes or ascii control characters: {byte:?}"
31                ),
32                Error::StartsWithSlash => write!(f, "A reference name must not start with a slash '/'"),
33                Error::RepeatedSlash => write!(
34                    f,
35                    "Multiple slashes in a row are not allowed as they may change the reference's meaning"
36                ),
37                Error::RepeatedDot => write!(f, "A ref must not contain '..' as it may be mistaken for a range"),
38                Error::LockFileSuffix => write!(f, "A ref must not end with '.lock'"),
39                Error::ReflogPortion => write!(f, "A ref must not contain '@{{' which is a part of a ref-log"),
40                Error::Asterisk => write!(f, "A ref must not contain '*' character"),
41                Error::StartsWithDot => write!(f, "A ref must not start with a '.'"),
42                Error::EndsWithDot => write!(f, "A ref must not end with a '.'"),
43                Error::EndsWithSlash => write!(f, "A ref must not end with a '/'"),
44                Error::Empty => write!(f, "A ref must not be empty"),
45            }
46        }
47    }
48
49    impl std::error::Error for Error {
50        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51            Some(const { &gix_error::ClassificationMarker::VALIDATION })
52        }
53    }
54}
55
56/// Assure the given `input` resemble a valid git tag name, which is returned unchanged on success.
57/// Tag names are provided as names, like `v1.0` or `alpha-1`, without paths.
58pub fn name(input: &BStr) -> Result<&BStr, name::Error> {
59    match name_inner(input, Mode::Validate)? {
60        None => Ok(input),
61        Some(_) => {
62            unreachable!("When validating, the input isn't changed")
63        }
64    }
65}
66
67#[derive(Eq, PartialEq)]
68pub(crate) enum Mode {
69    Sanitize,
70    Validate,
71}
72
73/// Validate or sanitize `input` according to `mode`.
74///
75/// Validation returns `Ok(None)` when `input` is valid, while sanitization returns the rebuilt name
76/// in `Ok(Some(_))` even if it is identical to `input`. An error means validation failed.
77pub(crate) fn name_inner(input: &BStr, mode: Mode) -> Result<Option<BString>, name::Error> {
78    let mut out: Option<BString> =
79        matches!(mode, Mode::Sanitize).then(|| BString::from(Vec::with_capacity(input.len())));
80    if input.is_empty() {
81        return if let Some(mut out) = out {
82            out.push(b'-');
83            Ok(Some(out))
84        } else {
85            Err(name::Error::Empty)
86        };
87    }
88    if *input.last().expect("non-empty") == b'/' && out.is_none() {
89        return Err(name::Error::EndsWithSlash);
90    }
91    if input.first() == Some(&b'/') && out.is_none() {
92        return Err(name::Error::StartsWithSlash);
93    }
94
95    let mut previous = 0;
96    let mut component_start;
97    let mut component_end = 0;
98    let last = input.len() - 1;
99    for (byte_pos, byte) in input.iter().enumerate() {
100        match byte {
101            b'\\' | b'^' | b':' | b'[' | b'?' | b' ' | b'~' | b'\0'..=b'\x1F' | b'\x7F' => {
102                if let Some(out) = out.as_mut() {
103                    out.push(b'-');
104                } else {
105                    return Err(name::Error::InvalidByte {
106                        byte: (&[*byte][..]).into(),
107                    });
108                }
109            }
110            b'*' => {
111                if let Some(out) = out.as_mut() {
112                    out.push(b'-');
113                } else {
114                    return Err(name::Error::Asterisk);
115                }
116            }
117
118            b'.' if previous == b'.' => {
119                if out.is_none() {
120                    return Err(name::Error::RepeatedDot);
121                }
122            }
123            b'.' if previous == b'/' => {
124                if let Some(out) = out.as_mut() {
125                    out.push(b'-');
126                } else {
127                    return Err(name::Error::StartsWithDot);
128                }
129            }
130            b'{' if previous == b'@' => {
131                if let Some(out) = out.as_mut() {
132                    out.push(b'-');
133                } else {
134                    return Err(name::Error::ReflogPortion);
135                }
136            }
137            b'/' if previous == b'/' => {
138                if out.is_none() {
139                    return Err(name::Error::RepeatedSlash);
140                }
141            }
142            c => {
143                if *c == b'/' {
144                    component_start = component_end;
145                    component_end = byte_pos;
146
147                    if input[component_start..component_end].ends_with_str(".lock") {
148                        if let Some(out) = out.as_mut() {
149                            while out.ends_with(b".lock") {
150                                let len_without_suffix = out.len() - b".lock".len();
151                                out.truncate(len_without_suffix);
152                            }
153                        } else {
154                            return Err(name::Error::LockFileSuffix);
155                        }
156                    }
157                }
158
159                if let Some(out) = out.as_mut() {
160                    out.push(*c);
161                }
162
163                if byte_pos == last && input[component_end + 1..].ends_with_str(".lock") {
164                    if let Some(out) = out.as_mut() {
165                        while out.ends_with(b".lock") {
166                            let len_without_suffix = out.len() - b".lock".len();
167                            out.truncate(len_without_suffix);
168                        }
169                    } else {
170                        return Err(name::Error::LockFileSuffix);
171                    }
172                }
173            }
174        }
175        previous = *byte;
176    }
177
178    if let Some(out) = out.as_mut() {
179        while out.last() == Some(&b'/') {
180            out.pop();
181        }
182        while out.first() == Some(&b'/') {
183            out.remove(0);
184        }
185    }
186    if out.as_ref().map_or(input, |b| b.as_bstr())[0] == b'.' {
187        if let Some(out) = out.as_mut() {
188            out[0] = b'-';
189        } else {
190            return Err(name::Error::StartsWithDot);
191        }
192    }
193    let last = out.as_ref().map_or(input, |b| b.as_bstr()).len() - 1;
194    if out.as_ref().map_or(input, |b| b.as_bstr())[last] == b'.' {
195        if let Some(out) = out.as_mut() {
196            let last = out.len() - 1;
197            out[last] = b'-';
198        } else {
199            return Err(name::Error::EndsWithDot);
200        }
201    }
202    Ok(out)
203}