|
| 1 | +/// |
| 2 | +pub mod validate { |
| 3 | + use bstr::{BStr, BString}; |
| 4 | + use quick_error::quick_error; |
| 5 | + |
| 6 | + quick_error! { |
| 7 | + /// The error returned by [`name()`] |
| 8 | + #[derive(Debug)] |
| 9 | + #[allow(missing_docs)] |
| 10 | + pub enum NameError { |
| 11 | + InvalidByte(name: BString) { |
| 12 | + display("A ref must not contain invalid bytes or ascii control characters: '{}'", name) |
| 13 | + } |
| 14 | + DoubleDot { |
| 15 | + display("A ref must not contain '..' as it may be mistaken for a range") |
| 16 | + } |
| 17 | + LockFileSuffix { |
| 18 | + display("A ref must not end with '.lock'") |
| 19 | + } |
| 20 | + ReflogPortion { |
| 21 | + display("A ref must not contain '@{{' which is a part of a ref-log") |
| 22 | + } |
| 23 | + Asterisk { |
| 24 | + display("A ref must not contain '*' character") |
| 25 | + } |
| 26 | + StartsWithDot { |
| 27 | + display("A ref must not start with a '.'") |
| 28 | + } |
| 29 | + EndsWithSlash { |
| 30 | + display("A ref must not end with a '/'") |
| 31 | + } |
| 32 | + Empty { |
| 33 | + display("A ref must not be empty") |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + /// Assure the given `bytes` resemble a valid git ref name, which are returned unchanged on success. |
| 39 | + pub fn name(bytes: &BStr) -> Result<&BStr, NameError> { |
| 40 | + if bytes.is_empty() { |
| 41 | + return Err(NameError::Empty); |
| 42 | + } |
| 43 | + |
| 44 | + let mut last = 0; |
| 45 | + for byte in bytes.iter() { |
| 46 | + match byte { |
| 47 | + b'\\' | b'^' | b':' | b'[' | b'?' | b' ' | b'~' | b'\0'..=b'\x1F' | b'\x7F' => { |
| 48 | + return Err(NameError::InvalidByte(bytes.into())) |
| 49 | + } |
| 50 | + b'*' => return Err(NameError::Asterisk), |
| 51 | + b'.' if last == b'.' => return Err(NameError::DoubleDot), |
| 52 | + b'{' if last == b'@' => return Err(NameError::ReflogPortion), |
| 53 | + _ => {} |
| 54 | + } |
| 55 | + last = *byte; |
| 56 | + } |
| 57 | + if bytes[0] == b'.' { |
| 58 | + return Err(NameError::StartsWithDot); |
| 59 | + } |
| 60 | + if *bytes.last().expect("non-empty") == b'/' { |
| 61 | + return Err(NameError::EndsWithSlash); |
| 62 | + } |
| 63 | + if bytes.ends_with(b".lock") { |
| 64 | + return Err(NameError::LockFileSuffix); |
| 65 | + } |
| 66 | + Ok(bytes) |
| 67 | + } |
| 68 | +} |
0 commit comments