use-git-ref 0.0.1

Primitive Git ref vocabulary for RustUse
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
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

use core::{fmt, str::FromStr};
use std::error::Error;

/// Error returned while parsing ref vocabulary.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GitRefParseError {
    /// The supplied ref text was empty.
    Empty,
    /// The supplied ref name used syntax this crate rejects.
    InvalidName,
    /// The supplied detached `HEAD` target was empty.
    EmptyDetachedTarget,
}

impl fmt::Display for GitRefParseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("Git ref name cannot be empty"),
            Self::InvalidName => formatter.write_str("invalid Git ref name"),
            Self::EmptyDetachedTarget => {
                formatter.write_str("detached HEAD target cannot be empty")
            },
        }
    }
}

impl Error for GitRefParseError {}

/// A broad ref-name kind.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum GitRefKind {
    /// The `HEAD` pseudo-ref.
    Head,
    /// A branch ref under `refs/heads/`.
    Branch,
    /// A tag ref under `refs/tags/`.
    Tag,
    /// A remote-tracking ref under `refs/remotes/`.
    Remote,
    /// Another syntactically valid ref name.
    Other,
}

impl GitRefKind {
    /// Returns the stable kind label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Head => "head",
            Self::Branch => "branch",
            Self::Tag => "tag",
            Self::Remote => "remote",
            Self::Other => "other",
        }
    }
}

impl fmt::Display for GitRefKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

fn ref_kind(value: &str) -> GitRefKind {
    if value == "HEAD" {
        GitRefKind::Head
    } else if value.starts_with("refs/heads/") {
        GitRefKind::Branch
    } else if value.starts_with("refs/tags/") {
        GitRefKind::Tag
    } else if value.starts_with("refs/remotes/") {
        GitRefKind::Remote
    } else {
        GitRefKind::Other
    }
}

fn has_lock_suffix(value: &str) -> bool {
    value
        .get(value.len().saturating_sub(5)..)
        .is_some_and(|suffix| suffix.eq_ignore_ascii_case(".lock"))
}

fn validate_ref_name(value: impl AsRef<str>) -> Result<String, GitRefParseError> {
    let trimmed = value.as_ref().trim();

    if trimmed.is_empty() {
        return Err(GitRefParseError::Empty);
    }

    if trimmed == "HEAD" {
        return Ok(trimmed.to_string());
    }

    let invalid = trimmed.starts_with('/')
        || trimmed.ends_with('/')
        || trimmed.starts_with('.')
        || trimmed.ends_with('.')
        || has_lock_suffix(trimmed)
        || trimmed.contains("//")
        || trimmed.contains("..")
        || trimmed.contains("@{")
        || trimmed.chars().any(|character| {
            character.is_ascii_control()
                || character.is_ascii_whitespace()
                || matches!(character, '~' | '^' | ':' | '?' | '*' | '[' | '\\')
        })
        || trimmed.split('/').any(|component| component.ends_with('.'));

    if invalid {
        Err(GitRefParseError::InvalidName)
    } else {
        Ok(trimmed.to_string())
    }
}

/// A validated ref name.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GitRefName {
    value: String,
    kind: GitRefKind,
}

impl GitRefName {
    /// Creates a ref name from text.
    ///
    /// # Errors
    ///
    /// Returns [`GitRefParseError`] when the name is empty or uses rejected syntax.
    pub fn new(value: impl AsRef<str>) -> Result<Self, GitRefParseError> {
        let value = validate_ref_name(value)?;
        let kind = ref_kind(&value);
        Ok(Self { value, kind })
    }

    /// Returns the broad ref kind.
    #[must_use]
    pub const fn kind(&self) -> GitRefKind {
        self.kind
    }

    /// Returns true when this is `HEAD`.
    #[must_use]
    pub const fn is_head(&self) -> bool {
        matches!(self.kind, GitRefKind::Head)
    }

    /// Returns true when this is a branch ref.
    #[must_use]
    pub const fn is_branch(&self) -> bool {
        matches!(self.kind, GitRefKind::Branch)
    }

    /// Returns true when this is a tag ref.
    #[must_use]
    pub const fn is_tag(&self) -> bool {
        matches!(self.kind, GitRefKind::Tag)
    }

    /// Returns true when this is a remote-tracking ref.
    #[must_use]
    pub const fn is_remote(&self) -> bool {
        matches!(self.kind, GitRefKind::Remote)
    }

    /// Returns the ref name text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.value
    }
}

impl AsRef<str> for GitRefName {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for GitRefName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for GitRefName {
    type Err = GitRefParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl TryFrom<&str> for GitRefName {
    type Error = GitRefParseError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

/// A concrete ref wrapper.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GitRef(GitRefName);

impl GitRef {
    /// Creates a concrete ref from a ref name.
    #[must_use]
    pub const fn from_name(name: GitRefName) -> Self {
        Self(name)
    }

    /// Parses a concrete ref from text.
    ///
    /// # Errors
    ///
    /// Returns [`GitRefParseError`] when the ref name is invalid.
    pub fn new(value: impl AsRef<str>) -> Result<Self, GitRefParseError> {
        GitRefName::new(value).map(Self)
    }

    /// Returns the ref name.
    #[must_use]
    pub const fn name(&self) -> &GitRefName {
        &self.0
    }

    /// Returns the ref kind.
    #[must_use]
    pub const fn kind(&self) -> GitRefKind {
        self.0.kind()
    }

    /// Returns the ref text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl AsRef<str> for GitRef {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for GitRef {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for GitRef {
    type Err = GitRefParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

/// A symbolic ref target.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SymbolicRef {
    target: GitRefName,
}

impl SymbolicRef {
    /// Creates a symbolic ref target from a validated ref name.
    #[must_use]
    pub const fn new(target: GitRefName) -> Self {
        Self { target }
    }

    /// Parses a symbolic ref target from text.
    ///
    /// # Errors
    ///
    /// Returns [`GitRefParseError`] when the target ref name is invalid.
    pub fn parse(value: impl AsRef<str>) -> Result<Self, GitRefParseError> {
        GitRefName::new(value).map(Self::new)
    }

    /// Returns the target ref name.
    #[must_use]
    pub const fn target(&self) -> &GitRefName {
        &self.target
    }

    /// Returns the target ref text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.target.as_str()
    }
}

impl fmt::Display for SymbolicRef {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for SymbolicRef {
    type Err = GitRefParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::parse(value)
    }
}

/// A lightweight `HEAD` vocabulary value.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum GitHead {
    /// `HEAD` exists as a symbolic ref.
    Symbolic(SymbolicRef),
    /// `HEAD` names object identifier text directly.
    Detached(String),
    /// `HEAD` is known as vocabulary, but no target is modeled.
    Unborn,
}

impl GitHead {
    /// Creates symbolic `HEAD` from a target ref name.
    #[must_use]
    pub const fn symbolic(target: GitRefName) -> Self {
        Self::Symbolic(SymbolicRef::new(target))
    }

    /// Creates detached `HEAD` from object identifier text.
    ///
    /// # Errors
    ///
    /// Returns [`GitRefParseError::EmptyDetachedTarget`] when the supplied text is empty.
    pub fn detached(value: impl AsRef<str>) -> Result<Self, GitRefParseError> {
        let trimmed = value.as_ref().trim();
        if trimmed.is_empty() {
            Err(GitRefParseError::EmptyDetachedTarget)
        } else {
            Ok(Self::Detached(trimmed.to_string()))
        }
    }

    /// Returns true when `HEAD` is symbolic.
    #[must_use]
    pub const fn is_symbolic(&self) -> bool {
        matches!(self, Self::Symbolic(_))
    }

    /// Returns true when `HEAD` is detached.
    #[must_use]
    pub const fn is_detached(&self) -> bool {
        matches!(self, Self::Detached(_))
    }

    /// Returns the symbolic target when present.
    #[must_use]
    pub const fn symbolic_ref(&self) -> Option<&SymbolicRef> {
        match self {
            Self::Symbolic(symbolic) => Some(symbolic),
            Self::Detached(_) | Self::Unborn => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{GitHead, GitRefKind, GitRefName, GitRefParseError, SymbolicRef};

    #[test]
    fn classifies_common_refs() -> Result<(), GitRefParseError> {
        let branch = GitRefName::new("refs/heads/main")?;
        let tag = GitRefName::new("refs/tags/v1.0.0")?;
        let remote = GitRefName::new("refs/remotes/origin/main")?;

        assert_eq!(branch.kind(), GitRefKind::Branch);
        assert_eq!(tag.kind(), GitRefKind::Tag);
        assert_eq!(remote.kind(), GitRefKind::Remote);
        Ok(())
    }

    #[test]
    fn models_symbolic_head() -> Result<(), GitRefParseError> {
        let symbolic = SymbolicRef::parse("refs/heads/main")?;
        let head = GitHead::Symbolic(symbolic);

        assert!(head.is_symbolic());
        assert_eq!(
            head.symbolic_ref().map(SymbolicRef::as_str),
            Some("refs/heads/main")
        );
        Ok(())
    }

    #[test]
    fn rejects_invalid_refs() {
        assert_eq!(GitRefName::new(""), Err(GitRefParseError::Empty));
        assert_eq!(
            GitRefName::new("refs/heads/main.lock"),
            Err(GitRefParseError::InvalidName)
        );
        assert_eq!(
            GitRefName::new("refs/heads/with space"),
            Err(GitRefParseError::InvalidName)
        );
    }
}