repo: Add Git refname module

824fcaab91f625879eb289d63044af7d2310218c
Port the Git ref abstractions into `rustik-repo` from the
`git-ref-format` crate and others.

Assisted-by: Codex:gpt-5
Alexis Sellier committed ago 1 parent 2df69b8d
LICENSE +1 -1
1 1
MIT License
2 2
3 -
Copyright (c) 2026 Alexis Sellier
3 +
Copyright (c) 2026 Alexis Sellier <self@cloudhead.io>
4 4
5 5
Permission is hereby granted, free of charge, to any person obtaining a copy
6 6
of this software and associated documentation files (the "Software"), to deal
7 7
in the Software without restriction, including without limitation the rights
8 8
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
STYLE +0 -1
76 76
* Use `assert!` instead of `panic!` when it's clearer/simpler.
77 77
* Never do this: `f(g()?)` -- find a way to avoid having a `?` operator inside a function call.
78 78
79 79
MODULES
80 80
81 -
* For large modules, group related declarations with simple ASCII section banners such as `// Constants //` or `// Error Handling //`.
82 81
* Keep imports and sub-modules at the top, then constants, then types, then functions.
83 82
84 83
FUNCTIONS
85 84
86 85
* Prefer methods on types to free functions.
crates/repo/src/git.rs added +4 -0
1 +
//! Git data types and operations.
2 +
3 +
/// Git reference names and refspecs.
4 +
pub mod refs;
crates/repo/src/git/refs.rs added +78 -0
1 +
// Copyright (c) Kim Altintop <kim@eagain.st>
2 +
// Copyright (c) The Radicle Team
3 +
4 +
//! Git reference names and refspecs.
5 +
#![allow(unsafe_code)]
6 +
7 +
use std::borrow::{Borrow, Cow};
8 +
use std::convert::TryFrom;
9 +
use std::fmt::{self, Display, Write as _};
10 +
use std::iter::{Extend, FromIterator};
11 +
use std::ops::Deref;
12 +
13 +
pub use check::{Error, Options, ref_format as check_ref_format};
14 +
pub use name::{Component, RefStr, RefString};
15 +
pub use namespaced::Namespaced;
16 +
pub use qualified::Qualified;
17 +
pub use refspec::DuplicateGlob;
18 +
19 +
/// Git refname validation.
20 +
pub mod check;
21 +
/// Known literal refname components.
22 +
pub mod lit;
23 +
/// Git reference names.
24 +
pub mod name;
25 +
/// Namespaced Git refnames.
26 +
pub mod namespaced;
27 +
/// Fully qualified Git refnames.
28 +
pub mod qualified;
29 +
/// Git refspec patterns.
30 +
pub mod refspec;
31 +
32 +
#[cfg(test)]
33 +
#[allow(clippy::unwrap_used)]
34 +
mod tests {
35 +
    use super::*;
36 +
37 +
    #[test]
38 +
    fn refnames_validate_git_rules() {
39 +
        assert!(RefString::try_from("refs/heads/main").is_ok());
40 +
        assert!(RefString::try_from("main").is_ok());
41 +
        assert_eq!(RefString::try_from("refs//main"), Err(Error::Slash));
42 +
        assert_eq!(
43 +
            RefString::try_from("refs/heads/a.lock"),
44 +
            Err(Error::DotLock)
45 +
        );
46 +
        assert_eq!(
47 +
            RefString::try_from("refs/heads/a~b"),
48 +
            Err(Error::InvalidChar('~'))
49 +
        );
50 +
    }
51 +
52 +
    #[test]
53 +
    fn qualified_and_namespaced_refs_roundtrip() {
54 +
        let qualified =
55 +
            Qualified::from_refstr(RefString::try_from("refs/heads/main").unwrap()).unwrap();
56 +
        let namespaced = qualified.with_namespace(name::component::ORIGIN);
57 +
58 +
        assert_eq!(
59 +
            namespaced.as_str(),
60 +
            "refs/namespaces/origin/refs/heads/main"
61 +
        );
62 +
        assert_eq!(namespaced.namespace().as_str(), "origin");
63 +
        assert_eq!(namespaced.strip_namespace().as_str(), "refs/heads/main");
64 +
    }
65 +
66 +
    #[test]
67 +
    fn refspec_patterns_allow_one_glob() {
68 +
        let pattern = refspec::PatternString::try_from("refs/heads/*").unwrap();
69 +
        let qualified = pattern.qualified().unwrap();
70 +
        let namespaced = qualified.with_namespace(name::component::ORIGIN).unwrap();
71 +
72 +
        assert_eq!(namespaced.as_str(), "refs/namespaces/origin/refs/heads/*");
73 +
        assert_eq!(
74 +
            refspec::PatternString::try_from("refs/*/*"),
75 +
            Err(Error::Pattern)
76 +
        );
77 +
    }
78 +
}
crates/repo/src/git/refs/check.rs added +122 -0
1 +
// Copyright (c) Kim Altintop <kim@eagain.st>
2 +
// Copyright (c) The Radicle Team
3 +
4 +
//! Git refname validation.
5 +
use std::fmt;
6 +
7 +
/// Options controlling Git refname validation.
8 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9 +
pub struct Options {
10 +
    /// Allows a refname without a slash.
11 +
    pub allow_onelevel: bool,
12 +
    /// Allows exactly one `*` pattern character.
13 +
    pub allow_pattern: bool,
14 +
}
15 +
16 +
/// A Git refname validation error.
17 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18 +
#[non_exhaustive]
19 +
pub enum Error {
20 +
    /// The refname is empty.
21 +
    Empty,
22 +
    /// The refname is the single character `@`.
23 +
    LoneAt,
24 +
    /// The refname contains consecutive slashes or a trailing slash.
25 +
    Slash,
26 +
    /// A component ends with `.lock`.
27 +
    DotLock,
28 +
    /// The refname contains consecutive dots.
29 +
    DotDot,
30 +
    /// The refname contains `@{`.
31 +
    AtOpenBrace,
32 +
    /// The refname contains an invalid character.
33 +
    InvalidChar(char),
34 +
    /// A component starts with dot.
35 +
    StartsDot,
36 +
    /// A component ends with dot.
37 +
    EndsDot,
38 +
    /// The refname contains an ASCII control character.
39 +
    Control,
40 +
    /// The refname contains a space.
41 +
    Space,
42 +
    /// The refname contains more than one `*`.
43 +
    Pattern,
44 +
    /// The refname must contain at least one slash.
45 +
    OneLevel,
46 +
}
47 +
48 +
impl fmt::Display for Error {
49 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 +
        match self {
51 +
            Self::Empty => f.write_str("empty input"),
52 +
            Self::LoneAt => f.write_str("lone '@' character"),
53 +
            Self::Slash => f.write_str("consecutive or trailing slash"),
54 +
            Self::DotLock => f.write_str("ends with '.lock'"),
55 +
            Self::DotDot => f.write_str("consecutive dots ('..')"),
56 +
            Self::AtOpenBrace => f.write_str("at-open-brace ('@{')"),
57 +
            Self::InvalidChar(c) => write!(f, "invalid character {c:?}"),
58 +
            Self::StartsDot => f.write_str("component starts with '.'"),
59 +
            Self::EndsDot => f.write_str("component ends with '.'"),
60 +
            Self::Control => f.write_str("control character"),
61 +
            Self::Space => f.write_str("whitespace"),
62 +
            Self::Pattern => f.write_str("must contain at most one '*'"),
63 +
            Self::OneLevel => f.write_str("must contain at least one '/'"),
64 +
        }
65 +
    }
66 +
}
67 +
68 +
impl std::error::Error for Error {}
69 +
70 +
/// Validates that `name` is a Git refname.
71 +
pub fn ref_format(opts: Options, name: &str) -> Result<(), Error> {
72 +
    match name {
73 +
        "" => return Err(Error::Empty),
74 +
        "@" => return Err(Error::LoneAt),
75 +
        "." => return Err(Error::StartsDot),
76 +
        _ => {}
77 +
    }
78 +
    let mut globs = 0usize;
79 +
    let mut parts = 0usize;
80 +
81 +
    for component in name.split('/') {
82 +
        if component.is_empty() {
83 +
            return Err(Error::Slash);
84 +
        }
85 +
        if component.ends_with(".lock") {
86 +
            return Err(Error::DotLock);
87 +
        }
88 +
        parts += 1;
89 +
        validate_component(component, &mut globs)?;
90 +
    }
91 +
92 +
    if parts < 2 && !opts.allow_onelevel {
93 +
        Err(Error::OneLevel)
94 +
    } else if globs > 1 && opts.allow_pattern {
95 +
        Err(Error::Pattern)
96 +
    } else if globs > 0 && !opts.allow_pattern {
97 +
        Err(Error::InvalidChar('*'))
98 +
    } else {
99 +
        Ok(())
100 +
    }
101 +
}
102 +
103 +
/// Validates one Git refname component.
104 +
fn validate_component(component: &str, globs: &mut usize) -> Result<(), Error> {
105 +
    let next_chars = component.chars().skip(1).map(Some).chain([None]);
106 +
    for (index, (current, next)) in component.chars().zip(next_chars).enumerate() {
107 +
        match (current, next) {
108 +
            ('.', Some('.')) => return Err(Error::DotDot),
109 +
            ('@', Some('{')) => return Err(Error::AtOpenBrace),
110 +
            ('\0' | '\\' | '~' | '^' | ':' | '?' | '[', _) => {
111 +
                return Err(Error::InvalidChar(current));
112 +
            }
113 +
            ('*', _) => *globs += 1,
114 +
            ('.', _) if index == 0 => return Err(Error::StartsDot),
115 +
            ('.', None) => return Err(Error::EndsDot),
116 +
            (' ', _) => return Err(Error::Space),
117 +
            (c, _) if c.is_ascii_control() => return Err(Error::Control),
118 +
            _ => {}
119 +
        }
120 +
    }
121 +
    Ok(())
122 +
}
crates/repo/src/git/refs/lit.rs added +211 -0
1 +
// Copyright (c) Kim Altintop <kim@eagain.st>
2 +
// Copyright (c) The Radicle Team
3 +
4 +
//! Known literal refname components.
5 +
use super::*;
6 +
7 +
/// A known literal [`RefStr`].
8 +
pub trait Lit: Sized + sealed::Sealed {
9 +
    /// The literal value.
10 +
    const SELF: Self;
11 +
    /// The literal refname string.
12 +
    const NAME: &'static RefStr;
13 +
14 +
    /// Converts a component into this literal when it matches.
15 +
    #[inline]
16 +
    fn from_component(component: &name::Component<'_>) -> Option<Self> {
17 +
        (component.as_ref() == Self::NAME).then_some(Self::SELF)
18 +
    }
19 +
}
20 +
21 +
impl<T: Lit> From<T> for &'static RefStr {
22 +
    #[inline]
23 +
    fn from(_: T) -> Self {
24 +
        T::NAME
25 +
    }
26 +
}
27 +
28 +
/// Seals the literal trait.
29 +
mod sealed {
30 +
    /// Marker trait for literal implementors.
31 +
    pub trait Sealed {}
32 +
}
33 +
34 +
/// A known literal component.
35 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
36 +
pub enum KnownLit {
37 +
    /// The `refs` component.
38 +
    Refs,
39 +
    /// The `heads` component.
40 +
    Heads,
41 +
    /// The `namespaces` component.
42 +
    Namespaces,
43 +
    /// The `remotes` component.
44 +
    Remotes,
45 +
    /// The `tags` component.
46 +
    Tags,
47 +
    /// The `notes` component.
48 +
    Notes,
49 +
}
50 +
51 +
impl KnownLit {
52 +
    /// Returns the known literal matching `component`.
53 +
    pub fn from_component(component: &name::Component<'_>) -> Option<Self> {
54 +
        let component: &RefStr = component.as_ref();
55 +
        if component == Refs::NAME {
56 +
            Some(Self::Refs)
57 +
        } else if component == Heads::NAME {
58 +
            Some(Self::Heads)
59 +
        } else if component == Namespaces::NAME {
60 +
            Some(Self::Namespaces)
61 +
        } else if component == Remotes::NAME {
62 +
            Some(Self::Remotes)
63 +
        } else if component == Tags::NAME {
64 +
            Some(Self::Tags)
65 +
        } else if component == Notes::NAME {
66 +
            Some(Self::Notes)
67 +
        } else {
68 +
            None
69 +
        }
70 +
    }
71 +
}
72 +
73 +
impl From<KnownLit> for name::Component<'static> {
74 +
    #[inline]
75 +
    fn from(lit: KnownLit) -> Self {
76 +
        match lit {
77 +
            KnownLit::Refs => Refs.into(),
78 +
            KnownLit::Heads => Heads.into(),
79 +
            KnownLit::Namespaces => Namespaces.into(),
80 +
            KnownLit::Remotes => Remotes.into(),
81 +
            KnownLit::Tags => Tags.into(),
82 +
            KnownLit::Notes => Notes.into(),
83 +
        }
84 +
    }
85 +
}
86 +
87 +
/// Either a known literal or any component.
88 +
pub enum SomeLit<'a> {
89 +
    /// A known literal.
90 +
    Known(KnownLit),
91 +
    /// Any other component.
92 +
    Any(name::Component<'a>),
93 +
}
94 +
95 +
impl SomeLit<'_> {
96 +
    /// Returns the known literal, if this value is known.
97 +
    pub fn known(self) -> Option<KnownLit> {
98 +
        match self {
99 +
            Self::Known(lit) => Some(lit),
100 +
            Self::Any(_) => None,
101 +
        }
102 +
    }
103 +
}
104 +
105 +
impl<'a> From<name::Component<'a>> for SomeLit<'a> {
106 +
    #[inline]
107 +
    fn from(component: name::Component<'a>) -> Self {
108 +
        match KnownLit::from_component(&component) {
109 +
            Some(lit) => Self::Known(lit),
110 +
            None => Self::Any(component),
111 +
        }
112 +
    }
113 +
}
114 +
115 +
/// Literal tuple for `refs/heads/<name>`.
116 +
pub type RefsHeads<T> = (Refs, Heads, T);
117 +
/// Literal tuple for `refs/tags/<name>`.
118 +
pub type RefsTags<T> = (Refs, Tags, T);
119 +
/// Literal tuple for `refs/notes/<name>`.
120 +
pub type RefsNotes<T> = (Refs, Notes, T);
121 +
/// Literal tuple for `refs/remotes/<name>`.
122 +
pub type RefsRemotes<T> = (Refs, Remotes, T);
123 +
/// Literal tuple for `refs/namespaces/<namespace>/<qualified>`.
124 +
pub type RefsNamespaces<'a, T> = (Refs, Namespaces, T, Qualified<'a>);
125 +
126 +
/// Creates a `refs/heads/<name>` literal tuple.
127 +
#[inline]
128 +
pub fn refs_heads<T: AsRef<RefStr>>(name: T) -> RefsHeads<T> {
129 +
    (Refs, Heads, name)
130 +
}
131 +
132 +
/// Creates a `refs/tags/<name>` literal tuple.
133 +
#[inline]
134 +
pub fn refs_tags<T: AsRef<RefStr>>(name: T) -> RefsTags<T> {
135 +
    (Refs, Tags, name)
136 +
}
137 +
138 +
/// Creates a `refs/notes/<name>` literal tuple.
139 +
#[inline]
140 +
pub fn refs_notes<T: AsRef<RefStr>>(name: T) -> RefsNotes<T> {
141 +
    (Refs, Notes, name)
142 +
}
143 +
144 +
/// Creates a `refs/remotes/<name>` literal tuple.
145 +
#[inline]
146 +
pub fn refs_remotes<T: AsRef<RefStr>>(name: T) -> RefsRemotes<T> {
147 +
    (Refs, Remotes, name)
148 +
}
149 +
150 +
/// Creates a `refs/namespaces/<namespace>/<qualified>` literal tuple.
151 +
#[inline]
152 +
pub fn refs_namespaces<'a, 'b, T>(namespace: T, name: Qualified<'b>) -> RefsNamespaces<'b, T>
153 +
where
154 +
    T: Into<name::Component<'a>>,
155 +
{
156 +
    (Refs, Namespaces, namespace, name)
157 +
}
158 +
159 +
/// The `refs` literal.
160 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
161 +
pub struct Refs;
162 +
impl Lit for Refs {
163 +
    const SELF: Self = Self;
164 +
    const NAME: &'static RefStr = name::REFS;
165 +
}
166 +
impl sealed::Sealed for Refs {}
167 +
168 +
/// The `heads` literal.
169 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
170 +
pub struct Heads;
171 +
impl Lit for Heads {
172 +
    const SELF: Self = Self;
173 +
    const NAME: &'static RefStr = name::HEADS;
174 +
}
175 +
impl sealed::Sealed for Heads {}
176 +
177 +
/// The `namespaces` literal.
178 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
179 +
pub struct Namespaces;
180 +
impl Lit for Namespaces {
181 +
    const SELF: Self = Self;
182 +
    const NAME: &'static RefStr = name::NAMESPACES;
183 +
}
184 +
impl sealed::Sealed for Namespaces {}
185 +
186 +
/// The `remotes` literal.
187 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
188 +
pub struct Remotes;
189 +
impl Lit for Remotes {
190 +
    const SELF: Self = Self;
191 +
    const NAME: &'static RefStr = name::REMOTES;
192 +
}
193 +
impl sealed::Sealed for Remotes {}
194 +
195 +
/// The `tags` literal.
196 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
197 +
pub struct Tags;
198 +
impl Lit for Tags {
199 +
    const SELF: Self = Self;
200 +
    const NAME: &'static RefStr = name::TAGS;
201 +
}
202 +
impl sealed::Sealed for Tags {}
203 +
204 +
/// The `notes` literal.
205 +
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
206 +
pub struct Notes;
207 +
impl Lit for Notes {
208 +
    const SELF: Self = Self;
209 +
    const NAME: &'static RefStr = name::NOTES;
210 +
}
211 +
impl sealed::Sealed for Notes {}
crates/repo/src/git/refs/name.rs added +565 -0
1 +
// Copyright (c) Kim Altintop <kim@eagain.st>
2 +
// Copyright (c) The Radicle Team
3 +
4 +
//! Git reference names.
5 +
use super::*;
6 +
7 +
/// Iterator over slash-separated refname components.
8 +
pub type Iter<'a> = std::str::Split<'a, char>;
9 +
10 +
/// Common refname components as strings.
11 +
pub mod str {
12 +
    /// The `heads` component.
13 +
    pub const HEADS: &str = "heads";
14 +
    /// The `main` component.
15 +
    pub const MAIN: &str = "main";
16 +
    /// The `master` component.
17 +
    pub const MASTER: &str = "master";
18 +
    /// The `namespaces` component.
19 +
    pub const NAMESPACES: &str = "namespaces";
20 +
    /// The `notes` component.
21 +
    pub const NOTES: &str = "notes";
22 +
    /// The `origin` component.
23 +
    pub const ORIGIN: &str = "origin";
24 +
    /// The `refs` component.
25 +
    pub const REFS: &str = "refs";
26 +
    /// The `remotes` component.
27 +
    pub const REMOTES: &str = "remotes";
28 +
    /// The `tags` component.
29 +
    pub const TAGS: &str = "tags";
30 +
    /// The `refs/heads/main` refname.
31 +
    pub const REFS_HEADS_MAIN: &str = "refs/heads/main";
32 +
    /// The `refs/heads/master` refname.
33 +
    pub const REFS_HEADS_MASTER: &str = "refs/heads/master";
34 +
}
35 +
36 +
/// Common refname components as bytes.
37 +
pub mod bytes {
38 +
    use super::str;
39 +
40 +
    /// The `heads` component.
41 +
    pub const HEADS: &[u8] = str::HEADS.as_bytes();
42 +
    /// The `main` component.
43 +
    pub const MAIN: &[u8] = str::MAIN.as_bytes();
44 +
    /// The `master` component.
45 +
    pub const MASTER: &[u8] = str::MASTER.as_bytes();
46 +
    /// The `namespaces` component.
47 +
    pub const NAMESPACES: &[u8] = str::NAMESPACES.as_bytes();
48 +
    /// The `notes` component.
49 +
    pub const NOTES: &[u8] = str::NOTES.as_bytes();
50 +
    /// The `origin` component.
51 +
    pub const ORIGIN: &[u8] = str::ORIGIN.as_bytes();
52 +
    /// The `refs` component.
53 +
    pub const REFS: &[u8] = str::REFS.as_bytes();
54 +
    /// The `remotes` component.
55 +
    pub const REMOTES: &[u8] = str::REMOTES.as_bytes();
56 +
    /// The `tags` component.
57 +
    pub const TAGS: &[u8] = str::TAGS.as_bytes();
58 +
    /// The `refs/heads/main` refname.
59 +
    pub const REFS_HEADS_MAIN: &[u8] = str::REFS_HEADS_MAIN.as_bytes();
60 +
    /// The `refs/heads/master` refname.
61 +
    pub const REFS_HEADS_MASTER: &[u8] = str::REFS_HEADS_MASTER.as_bytes();
62 +
}
63 +
64 +
/// The `heads` component.
65 +
pub const HEADS: &RefStr = RefStr::from_str(str::HEADS);
66 +
/// The `main` component.
67 +
pub const MAIN: &RefStr = RefStr::from_str(str::MAIN);
68 +
/// The `master` component.
69 +
pub const MASTER: &RefStr = RefStr::from_str(str::MASTER);
70 +
/// The `namespaces` component.
71 +
pub const NAMESPACES: &RefStr = RefStr::from_str(str::NAMESPACES);
72 +
/// The `notes` component.
73 +
pub const NOTES: &RefStr = RefStr::from_str(str::NOTES);
74 +
/// The `origin` component.
75 +
pub const ORIGIN: &RefStr = RefStr::from_str(str::ORIGIN);
76 +
/// The `refs` component.
77 +
pub const REFS: &RefStr = RefStr::from_str(str::REFS);
78 +
/// The `remotes` component.
79 +
pub const REMOTES: &RefStr = RefStr::from_str(str::REMOTES);
80 +
/// The `tags` component.
81 +
pub const TAGS: &RefStr = RefStr::from_str(str::TAGS);
82 +
/// The `refs/heads/main` refname.
83 +
pub const REFS_HEADS_MAIN: &RefStr = RefStr::from_str(str::REFS_HEADS_MAIN);
84 +
/// The `refs/heads/master` refname.
85 +
pub const REFS_HEADS_MASTER: &RefStr = RefStr::from_str(str::REFS_HEADS_MASTER);
86 +
87 +
/// Validation options for ordinary refnames.
88 +
const CHECK_OPTS: check::Options = check::Options {
89 +
    allow_pattern: false,
90 +
    allow_onelevel: true,
91 +
};
92 +
93 +
/// A borrowed valid Git refname.
94 +
#[repr(transparent)]
95 +
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
96 +
pub struct RefStr(str);
97 +
98 +
impl RefStr {
99 +
    /// Validates `s` and returns it as a borrowed refname.
100 +
    pub fn try_from_str(s: &str) -> Result<&RefStr, check::Error> {
101 +
        TryFrom::try_from(s)
102 +
    }
103 +
104 +
    /// Returns the refname as a string slice.
105 +
    #[inline]
106 +
    pub fn as_str(&self) -> &str {
107 +
        self
108 +
    }
109 +
110 +
    /// Returns an owned copy of this refname.
111 +
    #[inline]
112 +
    pub fn to_ref_string(&self) -> RefString {
113 +
        self.to_owned()
114 +
    }
115 +
116 +
    /// Strips `base` followed by a slash from this refname.
117 +
    pub fn strip_prefix<P>(&self, base: P) -> Option<&RefStr>
118 +
    where
119 +
        P: AsRef<RefStr>,
120 +
    {
121 +
        self.0
122 +
            .strip_prefix(base.as_ref().as_str())
123 +
            .and_then(|s| s.strip_prefix('/'))
124 +
            .map(Self::from_str)
125 +
    }
126 +
127 +
    /// Joins another refname component or suffix to this refname.
128 +
    pub fn join<R>(&self, other: R) -> RefString
129 +
    where
130 +
        R: AsRef<RefStr>,
131 +
    {
132 +
        let mut buf = self.to_ref_string();
133 +
        buf.push(other);
134 +
        buf
135 +
    }
136 +
137 +
    /// Appends a refspec pattern suffix to this refname.
138 +
    pub fn to_pattern<P>(&self, pattern: P) -> refspec::PatternString
139 +
    where
140 +
        P: AsRef<refspec::PatternStr>,
141 +
    {
142 +
        self.to_owned().with_pattern(pattern)
143 +
    }
144 +
145 +
    /// Returns this refname as a qualified refname, if it is qualified.
146 +
    #[inline]
147 +
    pub fn qualified(&self) -> Option<Qualified<'_>> {
148 +
        Qualified::from_refstr(self)
149 +
    }
150 +
151 +
    /// Returns this refname as a namespaced refname, if it is namespaced.
152 +
    #[inline]
153 +
    pub fn to_namespaced(&self) -> Option<Namespaced<'_>> {
154 +
        self.into()
155 +
    }
156 +
157 +
    /// Returns slash-separated string components.
158 +
    #[inline]
159 +
    pub fn iter(&self) -> Iter<'_> {
160 +
        self.0.split('/')
161 +
    }
162 +
163 +
    /// Returns slash-separated refname components.
164 +
    #[inline]
165 +
    pub fn components(&self) -> Components<'_> {
166 +
        Components::from(self)
167 +
    }
168 +
169 +
    /// Returns the first component.
170 +
    pub fn head(&self) -> Component<'_> {
171 +
        match self.components().next() {
172 +
            Some(component) => component,
173 +
            None => Component(Cow::Borrowed(self)),
174 +
        }
175 +
    }
176 +
177 +
    /// Converts a known-valid string slice to a refname.
178 +
    pub(crate) const fn from_str(s: &str) -> &RefStr {
179 +
        // SAFETY: `RefStr` is a transparent wrapper around `str`.
180 +
        unsafe { &*(s as *const str as *const RefStr) }
181 +
    }
182 +
}
183 +
184 +
impl Deref for RefStr {
185 +
    type Target = str;
186 +
187 +
    #[inline]
188 +
    fn deref(&self) -> &Self::Target {
189 +
        &self.0
190 +
    }
191 +
}
192 +
193 +
impl AsRef<str> for RefStr {
194 +
    #[inline]
195 +
    fn as_ref(&self) -> &str {
196 +
        self
197 +
    }
198 +
}
199 +
200 +
impl AsRef<RefStr> for RefStr {
201 +
    #[inline]
202 +
    fn as_ref(&self) -> &RefStr {
203 +
        self
204 +
    }
205 +
}
206 +
207 +
impl<'a> TryFrom<&'a str> for &'a RefStr {
208 +
    type Error = check::Error;
209 +
210 +
    #[inline]
211 +
    fn try_from(s: &'a str) -> Result<Self, Self::Error> {
212 +
        check::ref_format(CHECK_OPTS, s).map(|()| RefStr::from_str(s))
213 +
    }
214 +
}
215 +
216 +
impl<'a> From<&'a RefStr> for Cow<'a, RefStr> {
217 +
    #[inline]
218 +
    fn from(rs: &'a RefStr) -> Cow<'a, RefStr> {
219 +
        Cow::Borrowed(rs)
220 +
    }
221 +
}
222 +
223 +
impl Display for RefStr {
224 +
    #[inline]
225 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 +
        f.write_str(self)
227 +
    }
228 +
}
229 +
230 +
/// An owned valid Git refname.
231 +
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
232 +
pub struct RefString(String);
233 +
234 +
impl RefString {
235 +
    /// Returns this owned refname as a borrowed refname.
236 +
    #[inline]
237 +
    pub fn as_refstr(&self) -> &RefStr {
238 +
        self
239 +
    }
240 +
241 +
    /// Joins another refname suffix to this refname.
242 +
    pub fn and<R>(mut self, other: R) -> Self
243 +
    where
244 +
        R: AsRef<RefStr>,
245 +
    {
246 +
        self.push(other);
247 +
        self
248 +
    }
249 +
250 +
    /// Pushes another refname suffix onto this refname.
251 +
    pub fn push<R>(&mut self, other: R)
252 +
    where
253 +
        R: AsRef<RefStr>,
254 +
    {
255 +
        self.0.push('/');
256 +
        self.0.push_str(other.as_ref().as_str());
257 +
    }
258 +
259 +
    /// Removes the final slash-separated component.
260 +
    pub fn pop(&mut self) -> bool {
261 +
        match self.0.rfind('/') {
262 +
            Some(index) => {
263 +
                self.0.truncate(index);
264 +
                true
265 +
            }
266 +
            None => false,
267 +
        }
268 +
    }
269 +
270 +
    /// Appends a refspec pattern suffix.
271 +
    pub fn with_pattern<P>(self, pattern: P) -> refspec::PatternString
272 +
    where
273 +
        P: AsRef<refspec::PatternStr>,
274 +
    {
275 +
        let mut buf = self.0;
276 +
        buf.push('/');
277 +
        buf.push_str(pattern.as_ref().as_str());
278 +
        refspec::PatternString(buf)
279 +
    }
280 +
281 +
    /// Returns this refname as a qualified refname, if it is qualified.
282 +
    #[inline]
283 +
    pub fn into_qualified<'a>(self) -> Option<Qualified<'a>> {
284 +
        Qualified::from_refstr(self)
285 +
    }
286 +
287 +
    /// Reserves capacity for at least `additional` bytes.
288 +
    #[inline]
289 +
    pub fn reserve(&mut self, additional: usize) {
290 +
        self.0.reserve(additional);
291 +
    }
292 +
293 +
    /// Shrinks the allocated capacity as much as possible.
294 +
    #[inline]
295 +
    pub fn shrink_to_fit(&mut self) {
296 +
        self.0.shrink_to_fit();
297 +
    }
298 +
}
299 +
300 +
impl Deref for RefString {
301 +
    type Target = RefStr;
302 +
303 +
    #[inline]
304 +
    fn deref(&self) -> &Self::Target {
305 +
        self.borrow()
306 +
    }
307 +
}
308 +
309 +
impl AsRef<RefStr> for RefString {
310 +
    #[inline]
311 +
    fn as_ref(&self) -> &RefStr {
312 +
        self
313 +
    }
314 +
}
315 +
316 +
impl AsRef<str> for RefString {
317 +
    #[inline]
318 +
    fn as_ref(&self) -> &str {
319 +
        self.0.as_str()
320 +
    }
321 +
}
322 +
323 +
impl Borrow<RefStr> for RefString {
324 +
    #[inline]
325 +
    fn borrow(&self) -> &RefStr {
326 +
        RefStr::from_str(self.0.as_str())
327 +
    }
328 +
}
329 +
330 +
impl ToOwned for RefStr {
331 +
    type Owned = RefString;
332 +
333 +
    #[inline]
334 +
    fn to_owned(&self) -> Self::Owned {
335 +
        RefString(self.0.to_owned())
336 +
    }
337 +
}
338 +
339 +
impl TryFrom<&str> for RefString {
340 +
    type Error = check::Error;
341 +
342 +
    #[inline]
343 +
    fn try_from(s: &str) -> Result<Self, Self::Error> {
344 +
        RefStr::try_from_str(s).map(ToOwned::to_owned)
345 +
    }
346 +
}
347 +
348 +
impl TryFrom<String> for RefString {
349 +
    type Error = check::Error;
350 +
351 +
    #[inline]
352 +
    fn try_from(s: String) -> Result<Self, Self::Error> {
353 +
        check::ref_format(CHECK_OPTS, s.as_str()).map(|()| RefString(s))
354 +
    }
355 +
}
356 +
357 +
impl<'a> From<&'a RefString> for Cow<'a, RefStr> {
358 +
    #[inline]
359 +
    fn from(rs: &'a RefString) -> Cow<'a, RefStr> {
360 +
        Cow::Borrowed(rs.as_refstr())
361 +
    }
362 +
}
363 +
364 +
impl<'a> From<RefString> for Cow<'a, RefStr> {
365 +
    #[inline]
366 +
    fn from(rs: RefString) -> Cow<'a, RefStr> {
367 +
        Cow::Owned(rs)
368 +
    }
369 +
}
370 +
371 +
impl From<RefString> for String {
372 +
    #[inline]
373 +
    fn from(rs: RefString) -> Self {
374 +
        rs.0
375 +
    }
376 +
}
377 +
378 +
impl Display for RefString {
379 +
    #[inline]
380 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 +
        f.write_str(&self.0)
382 +
    }
383 +
}
384 +
385 +
impl<A> FromIterator<A> for RefString
386 +
where
387 +
    A: AsRef<RefStr>,
388 +
{
389 +
    #[allow(clippy::panic)]
390 +
    fn from_iter<T>(iter: T) -> Self
391 +
    where
392 +
        T: IntoIterator<Item = A>,
393 +
    {
394 +
        let mut iter = iter.into_iter();
395 +
        let Some(first) = iter.next() else {
396 +
            panic!("RefString::from_iter: empty iterator");
397 +
        };
398 +
        let mut buf = first.as_ref().as_str().to_owned();
399 +
        for component in iter {
400 +
            buf.push('/');
401 +
            buf.push_str(component.as_ref().as_str());
402 +
        }
403 +
        RefString(buf)
404 +
    }
405 +
}
406 +
407 +
impl<A> Extend<A> for RefString
408 +
where
409 +
    A: AsRef<RefStr>,
410 +
{
411 +
    fn extend<T>(&mut self, iter: T)
412 +
    where
413 +
        T: IntoIterator<Item = A>,
414 +
    {
415 +
        for component in iter {
416 +
            self.push(component);
417 +
        }
418 +
    }
419 +
}
420 +
421 +
/// Iterator over borrowed refname components.
422 +
#[must_use = "iterators are lazy and do nothing unless consumed"]
423 +
#[derive(Clone)]
424 +
pub struct Components<'a> {
425 +
    /// Inner string splitter.
426 +
    inner: Iter<'a>,
427 +
}
428 +
429 +
impl<'a> Iterator for Components<'a> {
430 +
    type Item = Component<'a>;
431 +
432 +
    #[inline]
433 +
    fn next(&mut self) -> Option<Self::Item> {
434 +
        self.inner
435 +
            .next()
436 +
            .map(RefStr::from_str)
437 +
            .map(Cow::from)
438 +
            .map(Component)
439 +
    }
440 +
}
441 +
442 +
impl<'a> DoubleEndedIterator for Components<'a> {
443 +
    #[inline]
444 +
    fn next_back(&mut self) -> Option<Self::Item> {
445 +
        self.inner
446 +
            .next_back()
447 +
            .map(RefStr::from_str)
448 +
            .map(Cow::from)
449 +
            .map(Component)
450 +
    }
451 +
}
452 +
453 +
impl<'a> From<&'a RefStr> for Components<'a> {
454 +
    #[inline]
455 +
    fn from(rs: &'a RefStr) -> Self {
456 +
        Self {
457 +
            inner: rs.as_str().split('/'),
458 +
        }
459 +
    }
460 +
}
461 +
462 +
/// A slash-free component of a Git refname.
463 +
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
464 +
pub struct Component<'a>(pub(crate) Cow<'a, RefStr>);
465 +
466 +
impl<'a> Component<'a> {
467 +
    /// Returns `r` as a component if it contains no slash.
468 +
    #[inline]
469 +
    pub fn from_refstr(r: impl Into<Cow<'a, RefStr>>) -> Option<Self> {
470 +
        let r = r.into();
471 +
        if r.contains('/') { None } else { Some(Self(r)) }
472 +
    }
473 +
474 +
    /// Returns this component as a known literal, if it matches one.
475 +
    #[inline]
476 +
    pub fn as_lit<T: lit::Lit>(&self) -> Option<T> {
477 +
        T::from_component(self)
478 +
    }
479 +
480 +
    /// Returns the wrapped borrowed or owned refname.
481 +
    #[inline]
482 +
    pub fn into_inner(self) -> Cow<'a, RefStr> {
483 +
        self.0
484 +
    }
485 +
}
486 +
487 +
impl Deref for Component<'_> {
488 +
    type Target = RefStr;
489 +
490 +
    #[inline]
491 +
    fn deref(&self) -> &Self::Target {
492 +
        &self.0
493 +
    }
494 +
}
495 +
496 +
impl AsRef<RefStr> for Component<'_> {
497 +
    #[inline]
498 +
    fn as_ref(&self) -> &RefStr {
499 +
        self
500 +
    }
501 +
}
502 +
503 +
impl<'a> From<&'a RefStr> for Option<Component<'a>> {
504 +
    #[inline]
505 +
    fn from(r: &'a RefStr) -> Self {
506 +
        Component::from_refstr(r)
507 +
    }
508 +
}
509 +
510 +
impl<'a> From<Component<'a>> for Cow<'a, RefStr> {
511 +
    #[inline]
512 +
    fn from(component: Component<'a>) -> Self {
513 +
        component.0
514 +
    }
515 +
}
516 +
517 +
impl<T: lit::Lit> From<T> for Component<'static> {
518 +
    #[inline]
519 +
    fn from(_: T) -> Self {
520 +
        Component(Cow::from(T::NAME))
521 +
    }
522 +
}
523 +
524 +
impl<'a> From<lit::SomeLit<'a>> for Component<'a> {
525 +
    #[inline]
526 +
    fn from(lit: lit::SomeLit<'a>) -> Self {
527 +
        match lit {
528 +
            lit::SomeLit::Known(known) => known.into(),
529 +
            lit::SomeLit::Any(component) => component,
530 +
        }
531 +
    }
532 +
}
533 +
534 +
impl Display for Component<'_> {
535 +
    #[inline]
536 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537 +
        f.write_str(self.0.as_str())
538 +
    }
539 +
}
540 +
541 +
/// Common refname components.
542 +
pub mod component {
543 +
    use super::Component;
544 +
    use crate::git::refs::name;
545 +
    use std::borrow::Cow;
546 +
547 +
    /// The `heads` component.
548 +
    pub const HEADS: Component<'static> = Component(Cow::Borrowed(name::HEADS));
549 +
    /// The `main` component.
550 +
    pub const MAIN: Component<'static> = Component(Cow::Borrowed(name::MAIN));
551 +
    /// The `master` component.
552 +
    pub const MASTER: Component<'static> = Component(Cow::Borrowed(name::MASTER));
553 +
    /// The `namespaces` component.
554 +
    pub const NAMESPACES: Component<'static> = Component(Cow::Borrowed(name::NAMESPACES));
555 +
    /// The `notes` component.
556 +
    pub const NOTES: Component<'static> = Component(Cow::Borrowed(name::NOTES));
557 +
    /// The `origin` component.
558 +
    pub const ORIGIN: Component<'static> = Component(Cow::Borrowed(name::ORIGIN));
559 +
    /// The `refs` component.
560 +
    pub const REFS: Component<'static> = Component(Cow::Borrowed(name::REFS));
561 +
    /// The `remotes` component.
562 +
    pub const REMOTES: Component<'static> = Component(Cow::Borrowed(name::REMOTES));
563 +
    /// The `tags` component.
564 +
    pub const TAGS: Component<'static> = Component(Cow::Borrowed(name::TAGS));
565 +
}
crates/repo/src/git/refs/namespaced.rs added +124 -0
1 +
// Copyright (c) Kim Altintop <kim@eagain.st>
2 +
// Copyright (c) The Radicle Team
3 +
4 +
//! Namespaced Git refnames.
5 +
use super::*;
6 +
7 +
/// A qualified refname under a Git namespace.
8 +
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
9 +
pub struct Namespaced<'a>(pub(crate) Cow<'a, RefStr>);
10 +
11 +
impl<'a> Namespaced<'a> {
12 +
    /// Returns the namespace component.
13 +
    #[allow(clippy::panic)]
14 +
    pub fn namespace(&self) -> Component<'_> {
15 +
        let Some(namespace) = self.components().nth(2) else {
16 +
            panic!("Namespaced::namespace: missing namespace component");
17 +
        };
18 +
        namespace
19 +
    }
20 +
21 +
    /// Removes the outer namespace.
22 +
    pub fn strip_namespace<'b>(&self) -> Qualified<'b> {
23 +
        let mut components = self.components().skip(3).collect::<RefString>();
24 +
        if components.as_str().is_empty() {
25 +
            components = name::REFS.to_ref_string();
26 +
        }
27 +
        Qualified(Cow::Owned(components))
28 +
    }
29 +
30 +
    /// Removes all nested namespaces.
31 +
    pub fn strip_namespace_recursive<'b>(&self) -> Qualified<'b> {
32 +
        let mut stripped = self.strip_namespace();
33 +
        while let Some(namespaced) = stripped.to_namespaced() {
34 +
            stripped = namespaced.strip_namespace();
35 +
        }
36 +
        stripped
37 +
    }
38 +
39 +
    /// Returns an owned namespaced refname.
40 +
    #[inline]
41 +
    pub fn to_owned<'b>(&self) -> Namespaced<'b> {
42 +
        Namespaced(Cow::Owned(self.0.clone().into_owned()))
43 +
    }
44 +
45 +
    /// Converts this value into an owned namespaced refname.
46 +
    #[inline]
47 +
    pub fn into_owned<'b>(self) -> Namespaced<'b> {
48 +
        Namespaced(Cow::Owned(self.0.into_owned()))
49 +
    }
50 +
51 +
    /// Converts this value into a qualified refname.
52 +
    #[inline]
53 +
    pub fn into_qualified(self) -> Qualified<'a> {
54 +
        Qualified(self.0)
55 +
    }
56 +
}
57 +
58 +
impl Deref for Namespaced<'_> {
59 +
    type Target = RefStr;
60 +
61 +
    #[inline]
62 +
    fn deref(&self) -> &Self::Target {
63 +
        &self.0
64 +
    }
65 +
}
66 +
67 +
impl AsRef<RefStr> for Namespaced<'_> {
68 +
    #[inline]
69 +
    fn as_ref(&self) -> &RefStr {
70 +
        self
71 +
    }
72 +
}
73 +
74 +
impl AsRef<str> for Namespaced<'_> {
75 +
    #[inline]
76 +
    fn as_ref(&self) -> &str {
77 +
        self.0.as_str()
78 +
    }
79 +
}
80 +
81 +
impl<'a> From<Namespaced<'a>> for Qualified<'a> {
82 +
    #[inline]
83 +
    fn from(namespaced: Namespaced<'a>) -> Self {
84 +
        Qualified(namespaced.0)
85 +
    }
86 +
}
87 +
88 +
impl<'a> From<&'a RefStr> for Option<Namespaced<'a>> {
89 +
    fn from(refname: &'a RefStr) -> Self {
90 +
        let mut components = refname.iter();
91 +
        match (
92 +
            components.next(),
93 +
            components.next(),
94 +
            components.next(),
95 +
            components.next(),
96 +
        ) {
97 +
            (Some("refs"), Some("namespaces"), Some(_), Some("refs")) => {
98 +
                Some(Namespaced(Cow::from(refname)))
99 +
            }
100 +
            _ => None,
101 +
        }
102 +
    }
103 +
}
104 +
105 +
impl<'a, T> From<lit::RefsNamespaces<'_, T>> for Namespaced<'static>
106 +
where
107 +
    T: Into<Component<'a>>,
108 +
{
109 +
    #[inline]
110 +
    fn from((refs, namespaces, namespace, name): lit::RefsNamespaces<'_, T>) -> Self {
111 +
        Self(Cow::Owned(
112 +
            IntoIterator::into_iter([refs.into(), namespaces.into(), namespace.into()])
113 +
                .collect::<RefString>()
114 +
                .and(name),
115 +
        ))
116 +
    }
117 +
}
118 +
119 +
impl Display for Namespaced<'_> {
120 +
    #[inline]
121 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 +
        self.0.fmt(f)
123 +
    }
124 +
}
crates/repo/src/git/refs/qualified.rs added +238 -0
1 +
// Copyright (c) Kim Altintop <kim@eagain.st>
2 +
// Copyright (c) The Radicle Team
3 +
4 +
//! Fully qualified Git refnames.
5 +
use super::*;
6 +
7 +
/// A fully qualified Git refname.
8 +
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
9 +
pub struct Qualified<'a>(pub(crate) Cow<'a, RefStr>);
10 +
11 +
impl<'a> Qualified<'a> {
12 +
    /// Creates a qualified refname from `refs/<a>/<b>/<tail...>`.
13 +
    pub fn from_components<'b, 'c, 'd, A, B, C>(a: A, b: B, tail: C) -> Self
14 +
    where
15 +
        A: Into<Component<'b>>,
16 +
        B: Into<Component<'c>>,
17 +
        C: IntoIterator<Item = Component<'d>>,
18 +
    {
19 +
        let mut inner = name::REFS.join(a.into()).and(b.into());
20 +
        inner.extend(tail);
21 +
        Self(inner.into())
22 +
    }
23 +
24 +
    /// Returns `refname` as qualified if it starts with `refs/` and has a category and name.
25 +
    pub fn from_refstr(refname: impl Into<Cow<'a, RefStr>>) -> Option<Self> {
26 +
        let refname = refname.into();
27 +
        let mut iter = refname.iter();
28 +
        match (iter.next(), iter.next(), iter.next()) {
29 +
            (Some("refs"), Some(_), Some(_)) => Some(Self(refname)),
30 +
            _ => None,
31 +
        }
32 +
    }
33 +
34 +
    /// Returns the qualified refname as a string.
35 +
    #[inline]
36 +
    pub fn as_str(&self) -> &str {
37 +
        self.as_ref()
38 +
    }
39 +
40 +
    /// Joins another refname suffix.
41 +
    #[inline]
42 +
    pub fn join<'b, R>(&self, other: R) -> Qualified<'b>
43 +
    where
44 +
        R: AsRef<RefStr>,
45 +
    {
46 +
        Qualified(self.0.join(other).into())
47 +
    }
48 +
49 +
    /// Appends a refspec pattern suffix.
50 +
    pub fn to_pattern<P>(&self, pattern: P) -> refspec::QualifiedPattern<'_>
51 +
    where
52 +
        P: AsRef<refspec::PatternStr>,
53 +
    {
54 +
        refspec::QualifiedPattern(Cow::Owned(RefStr::to_pattern(self, pattern.as_ref())))
55 +
    }
56 +
57 +
    /// Returns this refname as namespaced if it has a namespace prefix.
58 +
    #[inline]
59 +
    pub fn to_namespaced(&self) -> Option<Namespaced<'_>> {
60 +
        self.0.as_ref().into()
61 +
    }
62 +
63 +
    /// Adds `refs/namespaces/<namespace>/` before this refname.
64 +
    pub fn with_namespace<'b>(&self, namespace: Component<'b>) -> Namespaced<'a> {
65 +
        Namespaced(Cow::Owned(
66 +
            IntoIterator::into_iter([lit::Refs.into(), lit::Namespaces.into(), namespace])
67 +
                .chain(self.0.components())
68 +
                .collect(),
69 +
        ))
70 +
    }
71 +
72 +
    /// Returns the first three string components and the remaining iterator.
73 +
    #[allow(clippy::panic)]
74 +
    pub fn non_empty_iter(&self) -> (&str, &str, &str, name::Iter<'_>) {
75 +
        let mut iter = self.iter();
76 +
        let (Some(first), Some(second), Some(third)) = (iter.next(), iter.next(), iter.next())
77 +
        else {
78 +
            panic!("Qualified::non_empty_iter: missing component");
79 +
        };
80 +
        (first, second, third, iter)
81 +
    }
82 +
83 +
    /// Returns the first three components and the remaining iterator.
84 +
    #[allow(clippy::panic)]
85 +
    pub fn non_empty_components(
86 +
        &self,
87 +
    ) -> (
88 +
        Component<'_>,
89 +
        Component<'_>,
90 +
        Component<'_>,
91 +
        name::Components<'_>,
92 +
    ) {
93 +
        let mut components = self.components();
94 +
        let (Some(first), Some(second), Some(third)) =
95 +
            (components.next(), components.next(), components.next())
96 +
        else {
97 +
            panic!("Qualified::non_empty_components: missing component");
98 +
        };
99 +
        (first, second, third, components)
100 +
    }
101 +
102 +
    /// Returns an owned qualified refname.
103 +
    #[inline]
104 +
    pub fn to_owned<'b>(&self) -> Qualified<'b> {
105 +
        Qualified(Cow::Owned(self.0.clone().into_owned()))
106 +
    }
107 +
108 +
    /// Converts this value into an owned qualified refname.
109 +
    #[inline]
110 +
    pub fn into_owned<'b>(self) -> Qualified<'b> {
111 +
        Qualified(Cow::Owned(self.0.into_owned()))
112 +
    }
113 +
114 +
    /// Converts this qualified refname into an owned refname.
115 +
    #[inline]
116 +
    pub fn into_refstring(self) -> RefString {
117 +
        self.into()
118 +
    }
119 +
}
120 +
121 +
impl Deref for Qualified<'_> {
122 +
    type Target = RefStr;
123 +
124 +
    #[inline]
125 +
    fn deref(&self) -> &Self::Target {
126 +
        &self.0
127 +
    }
128 +
}
129 +
130 +
impl AsRef<RefStr> for Qualified<'_> {
131 +
    #[inline]
132 +
    fn as_ref(&self) -> &RefStr {
133 +
        self
134 +
    }
135 +
}
136 +
137 +
impl AsRef<str> for Qualified<'_> {
138 +
    #[inline]
139 +
    fn as_ref(&self) -> &str {
140 +
        self.0.as_str()
141 +
    }
142 +
}
143 +
144 +
impl AsRef<Self> for Qualified<'_> {
145 +
    #[inline]
146 +
    fn as_ref(&self) -> &Self {
147 +
        self
148 +
    }
149 +
}
150 +
151 +
impl<'a> From<Qualified<'a>> for Cow<'a, RefStr> {
152 +
    #[inline]
153 +
    fn from(qualified: Qualified<'a>) -> Self {
154 +
        qualified.0
155 +
    }
156 +
}
157 +
158 +
impl From<Qualified<'_>> for RefString {
159 +
    #[inline]
160 +
    fn from(qualified: Qualified<'_>) -> Self {
161 +
        qualified.0.into_owned()
162 +
    }
163 +
}
164 +
165 +
impl<T, U> From<(lit::Refs, T, U)> for Qualified<'_>
166 +
where
167 +
    T: AsRef<RefStr>,
168 +
    U: AsRef<RefStr>,
169 +
{
170 +
    #[inline]
171 +
    fn from((refs, category, name): (lit::Refs, T, U)) -> Self {
172 +
        let refs: &RefStr = refs.into();
173 +
        Self(Cow::Owned(refs.join(category).and(name)))
174 +
    }
175 +
}
176 +
177 +
impl<T> From<lit::RefsHeads<T>> for Qualified<'_>
178 +
where
179 +
    T: AsRef<RefStr>,
180 +
{
181 +
    #[inline]
182 +
    fn from((refs, heads, name): lit::RefsHeads<T>) -> Self {
183 +
        Self(Cow::Owned(
184 +
            IntoIterator::into_iter([Component::from(refs), heads.into()])
185 +
                .collect::<RefString>()
186 +
                .and(name),
187 +
        ))
188 +
    }
189 +
}
190 +
191 +
impl<T> From<lit::RefsTags<T>> for Qualified<'_>
192 +
where
193 +
    T: AsRef<RefStr>,
194 +
{
195 +
    #[inline]
196 +
    fn from((refs, tags, name): lit::RefsTags<T>) -> Self {
197 +
        Self(Cow::Owned(
198 +
            IntoIterator::into_iter([Component::from(refs), tags.into()])
199 +
                .collect::<RefString>()
200 +
                .and(name),
201 +
        ))
202 +
    }
203 +
}
204 +
205 +
impl<T> From<lit::RefsNotes<T>> for Qualified<'_>
206 +
where
207 +
    T: AsRef<RefStr>,
208 +
{
209 +
    #[inline]
210 +
    fn from((refs, notes, name): lit::RefsNotes<T>) -> Self {
211 +
        Self(Cow::Owned(
212 +
            IntoIterator::into_iter([Component::from(refs), notes.into()])
213 +
                .collect::<RefString>()
214 +
                .and(name),
215 +
        ))
216 +
    }
217 +
}
218 +
219 +
impl<T> From<lit::RefsRemotes<T>> for Qualified<'_>
220 +
where
221 +
    T: AsRef<RefStr>,
222 +
{
223 +
    #[inline]
224 +
    fn from((refs, remotes, name): lit::RefsRemotes<T>) -> Self {
225 +
        Self(Cow::Owned(
226 +
            IntoIterator::into_iter([Component::from(refs), remotes.into()])
227 +
                .collect::<RefString>()
228 +
                .and(name),
229 +
        ))
230 +
    }
231 +
}
232 +
233 +
impl Display for Qualified<'_> {
234 +
    #[inline]
235 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 +
        self.0.fmt(f)
237 +
    }
238 +
}
crates/repo/src/git/refs/refspec.rs added +694 -0
1 +
// Copyright (c) Kim Altintop <kim@eagain.st>
2 +
// Copyright (c) The Radicle Team
3 +
4 +
//! Git refspec patterns.
5 +
use super::*;
6 +
7 +
/// Iterator over slash-separated refspec pattern components.
8 +
pub type Iter<'a> = std::str::Split<'a, char>;
9 +
10 +
/// The `*` refspec pattern.
11 +
pub const STAR: &PatternStr = PatternStr::from_str("*");
12 +
13 +
/// Validation options for refspec patterns.
14 +
const CHECK_OPTS: check::Options = check::Options {
15 +
    allow_onelevel: true,
16 +
    allow_pattern: true,
17 +
};
18 +
19 +
/// A borrowed valid Git refspec pattern.
20 +
#[repr(transparent)]
21 +
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
22 +
pub struct PatternStr(str);
23 +
24 +
impl PatternStr {
25 +
    /// Validates `s` and returns it as a borrowed pattern.
26 +
    #[inline]
27 +
    pub fn try_from_str(s: &str) -> Result<&Self, check::Error> {
28 +
        TryFrom::try_from(s)
29 +
    }
30 +
31 +
    /// Returns the pattern as a string slice.
32 +
    #[inline]
33 +
    pub fn as_str(&self) -> &str {
34 +
        self
35 +
    }
36 +
37 +
    /// Joins another refname suffix to this pattern.
38 +
    pub fn join<R>(&self, other: R) -> PatternString
39 +
    where
40 +
        R: AsRef<RefStr>,
41 +
    {
42 +
        let mut buf = self.to_owned();
43 +
        buf.push(other);
44 +
        buf
45 +
    }
46 +
47 +
    /// Returns this pattern as qualified if it starts with `refs/`.
48 +
    #[inline]
49 +
    pub fn qualified(&self) -> Option<QualifiedPattern<'_>> {
50 +
        QualifiedPattern::from_patternstr(self)
51 +
    }
52 +
53 +
    /// Returns this pattern as namespaced if it has a namespace prefix.
54 +
    #[inline]
55 +
    pub fn to_namespaced(&self) -> Option<NamespacedPattern<'_>> {
56 +
        self.into()
57 +
    }
58 +
59 +
    /// Returns slash-separated string components.
60 +
    #[inline]
61 +
    pub fn iter(&self) -> Iter<'_> {
62 +
        self.0.split('/')
63 +
    }
64 +
65 +
    /// Returns slash-separated pattern components.
66 +
    #[inline]
67 +
    pub fn components(&self) -> Components<'_> {
68 +
        Components::from(self)
69 +
    }
70 +
71 +
    /// Converts a known-valid string slice to a pattern.
72 +
    pub(crate) const fn from_str(s: &str) -> &PatternStr {
73 +
        // SAFETY: `PatternStr` is a transparent wrapper around `str`.
74 +
        unsafe { &*(s as *const str as *const PatternStr) }
75 +
    }
76 +
}
77 +
78 +
impl Deref for PatternStr {
79 +
    type Target = str;
80 +
81 +
    #[inline]
82 +
    fn deref(&self) -> &Self::Target {
83 +
        &self.0
84 +
    }
85 +
}
86 +
87 +
impl AsRef<str> for PatternStr {
88 +
    #[inline]
89 +
    fn as_ref(&self) -> &str {
90 +
        self
91 +
    }
92 +
}
93 +
94 +
impl AsRef<Self> for PatternStr {
95 +
    #[inline]
96 +
    fn as_ref(&self) -> &Self {
97 +
        self
98 +
    }
99 +
}
100 +
101 +
impl<'a> TryFrom<&'a str> for &'a PatternStr {
102 +
    type Error = check::Error;
103 +
104 +
    #[inline]
105 +
    fn try_from(s: &'a str) -> Result<Self, Self::Error> {
106 +
        check::ref_format(CHECK_OPTS, s).map(|()| PatternStr::from_str(s))
107 +
    }
108 +
}
109 +
110 +
impl<'a> From<&'a RefStr> for &'a PatternStr {
111 +
    #[inline]
112 +
    fn from(refname: &'a RefStr) -> Self {
113 +
        PatternStr::from_str(refname.as_str())
114 +
    }
115 +
}
116 +
117 +
impl<'a> From<&'a PatternStr> for Cow<'a, PatternStr> {
118 +
    #[inline]
119 +
    fn from(pattern: &'a PatternStr) -> Cow<'a, PatternStr> {
120 +
        Cow::Borrowed(pattern)
121 +
    }
122 +
}
123 +
124 +
impl Display for PatternStr {
125 +
    #[inline]
126 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 +
        f.write_str(self)
128 +
    }
129 +
}
130 +
131 +
/// An owned valid Git refspec pattern.
132 +
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
133 +
pub struct PatternString(pub(crate) String);
134 +
135 +
impl PatternString {
136 +
    /// Returns the pattern as a string slice.
137 +
    #[inline]
138 +
    pub fn as_str(&self) -> &str {
139 +
        self.as_ref()
140 +
    }
141 +
142 +
    /// Returns this owned pattern as a borrowed pattern.
143 +
    #[inline]
144 +
    pub fn as_pattern_str(&self) -> &PatternStr {
145 +
        self.as_ref()
146 +
    }
147 +
148 +
    /// Builds a pattern from slash-separated pattern components.
149 +
    #[inline]
150 +
    pub fn from_components<'a, T>(iter: T) -> Result<Self, DuplicateGlob>
151 +
    where
152 +
        T: IntoIterator<Item = Component<'a>>,
153 +
    {
154 +
        iter.into_iter().collect()
155 +
    }
156 +
157 +
    /// Joins another refname suffix to this pattern.
158 +
    #[inline]
159 +
    pub fn and<R>(mut self, other: R) -> Self
160 +
    where
161 +
        R: AsRef<RefStr>,
162 +
    {
163 +
        self.push(other);
164 +
        self
165 +
    }
166 +
167 +
    /// Pushes another refname suffix onto this pattern.
168 +
    #[inline]
169 +
    pub fn push<R>(&mut self, other: R)
170 +
    where
171 +
        R: AsRef<RefStr>,
172 +
    {
173 +
        self.0.push('/');
174 +
        self.0.push_str(other.as_ref().as_str());
175 +
    }
176 +
177 +
    /// Removes the final slash-separated component.
178 +
    pub fn pop(&mut self) -> bool {
179 +
        match self.0.rfind('/') {
180 +
            Some(index) => {
181 +
                self.0.truncate(index);
182 +
                true
183 +
            }
184 +
            None => false,
185 +
        }
186 +
    }
187 +
}
188 +
189 +
impl Deref for PatternString {
190 +
    type Target = PatternStr;
191 +
192 +
    #[inline]
193 +
    fn deref(&self) -> &Self::Target {
194 +
        self.borrow()
195 +
    }
196 +
}
197 +
198 +
impl AsRef<PatternStr> for PatternString {
199 +
    #[inline]
200 +
    fn as_ref(&self) -> &PatternStr {
201 +
        self
202 +
    }
203 +
}
204 +
205 +
impl AsRef<str> for PatternString {
206 +
    #[inline]
207 +
    fn as_ref(&self) -> &str {
208 +
        self.0.as_str()
209 +
    }
210 +
}
211 +
212 +
impl Borrow<PatternStr> for PatternString {
213 +
    #[inline]
214 +
    fn borrow(&self) -> &PatternStr {
215 +
        PatternStr::from_str(self.0.as_str())
216 +
    }
217 +
}
218 +
219 +
impl ToOwned for PatternStr {
220 +
    type Owned = PatternString;
221 +
222 +
    #[inline]
223 +
    fn to_owned(&self) -> Self::Owned {
224 +
        PatternString(self.0.to_owned())
225 +
    }
226 +
}
227 +
228 +
impl From<RefString> for PatternString {
229 +
    #[inline]
230 +
    fn from(refname: RefString) -> Self {
231 +
        Self(refname.into())
232 +
    }
233 +
}
234 +
235 +
impl<'a> From<&'a PatternString> for Cow<'a, PatternStr> {
236 +
    #[inline]
237 +
    fn from(pattern: &'a PatternString) -> Cow<'a, PatternStr> {
238 +
        Cow::Borrowed(pattern.as_ref())
239 +
    }
240 +
}
241 +
242 +
impl From<PatternString> for String {
243 +
    #[inline]
244 +
    fn from(pattern: PatternString) -> Self {
245 +
        pattern.0
246 +
    }
247 +
}
248 +
249 +
impl TryFrom<&str> for PatternString {
250 +
    type Error = check::Error;
251 +
252 +
    #[inline]
253 +
    fn try_from(s: &str) -> Result<Self, Self::Error> {
254 +
        PatternStr::try_from_str(s).map(ToOwned::to_owned)
255 +
    }
256 +
}
257 +
258 +
impl TryFrom<String> for PatternString {
259 +
    type Error = check::Error;
260 +
261 +
    #[inline]
262 +
    fn try_from(s: String) -> Result<Self, Self::Error> {
263 +
        check::ref_format(CHECK_OPTS, s.as_str()).map(|()| PatternString(s))
264 +
    }
265 +
}
266 +
267 +
/// Error returned when a refspec pattern has multiple glob components.
268 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
269 +
pub struct DuplicateGlob;
270 +
271 +
impl Display for DuplicateGlob {
272 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 +
        f.write_str("more than one '*' encountered")
274 +
    }
275 +
}
276 +
277 +
impl std::error::Error for DuplicateGlob {}
278 +
279 +
impl<'a> FromIterator<Component<'a>> for Result<PatternString, DuplicateGlob> {
280 +
    fn from_iter<T>(iter: T) -> Self
281 +
    where
282 +
        T: IntoIterator<Item = Component<'a>>,
283 +
    {
284 +
        let mut buf = String::new();
285 +
        let mut seen_glob = false;
286 +
        for component in iter {
287 +
            if matches!(component, Component::Glob(_)) {
288 +
                if seen_glob {
289 +
                    return Err(DuplicateGlob);
290 +
                }
291 +
                seen_glob = true;
292 +
            }
293 +
            if !buf.is_empty() {
294 +
                buf.push('/');
295 +
            }
296 +
            buf.push_str(component.as_str());
297 +
        }
298 +
        assert!(!buf.is_empty(), "PatternString::from_iter: empty iterator");
299 +
        Ok(PatternString(buf))
300 +
    }
301 +
}
302 +
303 +
impl Display for PatternString {
304 +
    #[inline]
305 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306 +
        f.write_str(&self.0)
307 +
    }
308 +
}
309 +
310 +
/// A component of a refspec pattern.
311 +
pub enum Component<'a> {
312 +
    /// A `*` glob or a component containing `*`.
313 +
    Glob(Option<&'a PatternStr>),
314 +
    /// A normal refname component.
315 +
    Normal(&'a RefStr),
316 +
}
317 +
318 +
impl Component<'_> {
319 +
    /// Returns this component as a string slice.
320 +
    #[inline]
321 +
    pub fn as_str(&self) -> &str {
322 +
        self.as_ref()
323 +
    }
324 +
}
325 +
326 +
impl AsRef<str> for Component<'_> {
327 +
    #[inline]
328 +
    fn as_ref(&self) -> &str {
329 +
        match self {
330 +
            Self::Glob(None) => "*",
331 +
            Self::Glob(Some(pattern)) => pattern.as_str(),
332 +
            Self::Normal(refname) => refname.as_str(),
333 +
        }
334 +
    }
335 +
}
336 +
337 +
impl Display for Component<'_> {
338 +
    #[inline]
339 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
340 +
        f.write_str(self.as_str())
341 +
    }
342 +
}
343 +
344 +
impl<T: lit::Lit> From<T> for Component<'static> {
345 +
    #[inline]
346 +
    fn from(_: T) -> Self {
347 +
        Self::Normal(T::NAME)
348 +
    }
349 +
}
350 +
351 +
/// Iterator over refspec pattern components.
352 +
#[must_use = "iterators are lazy and do nothing unless consumed"]
353 +
#[derive(Clone)]
354 +
pub struct Components<'a> {
355 +
    /// Inner string splitter.
356 +
    inner: Iter<'a>,
357 +
}
358 +
359 +
impl<'a> Iterator for Components<'a> {
360 +
    type Item = Component<'a>;
361 +
362 +
    #[inline]
363 +
    fn next(&mut self) -> Option<Self::Item> {
364 +
        self.inner.next().map(pattern_component)
365 +
    }
366 +
}
367 +
368 +
impl<'a> DoubleEndedIterator for Components<'a> {
369 +
    #[inline]
370 +
    fn next_back(&mut self) -> Option<Self::Item> {
371 +
        self.inner.next_back().map(pattern_component)
372 +
    }
373 +
}
374 +
375 +
impl<'a> From<&'a PatternStr> for Components<'a> {
376 +
    #[inline]
377 +
    fn from(pattern: &'a PatternStr) -> Self {
378 +
        Self {
379 +
            inner: pattern.as_str().split('/'),
380 +
        }
381 +
    }
382 +
}
383 +
384 +
/// Converts a string component to a pattern component.
385 +
fn pattern_component(component: &str) -> Component<'_> {
386 +
    match component {
387 +
        "*" => Component::Glob(None),
388 +
        value if value.contains('*') => Component::Glob(Some(PatternStr::from_str(value))),
389 +
        value => Component::Normal(RefStr::from_str(value)),
390 +
    }
391 +
}
392 +
393 +
/// Common refspec pattern components.
394 +
pub mod component {
395 +
    use super::{Component, PatternStr};
396 +
    use crate::git::refs::name;
397 +
398 +
    /// The `*` component.
399 +
    pub const STAR: Component<'static> = Component::Glob(None);
400 +
    /// The `heads` component.
401 +
    pub const HEADS: Component<'static> = Component::Normal(name::HEADS);
402 +
    /// The `main` component.
403 +
    pub const MAIN: Component<'static> = Component::Normal(name::MAIN);
404 +
    /// The `master` component.
405 +
    pub const MASTER: Component<'static> = Component::Normal(name::MASTER);
406 +
    /// The `namespaces` component.
407 +
    pub const NAMESPACES: Component<'static> = Component::Normal(name::NAMESPACES);
408 +
    /// The `notes` component.
409 +
    pub const NOTES: Component<'static> = Component::Normal(name::NOTES);
410 +
    /// The `origin` component.
411 +
    pub const ORIGIN: Component<'static> = Component::Normal(name::ORIGIN);
412 +
    /// The `refs` component.
413 +
    pub const REFS: Component<'static> = Component::Normal(name::REFS);
414 +
    /// The `remotes` component.
415 +
    pub const REMOTES: Component<'static> = Component::Normal(name::REMOTES);
416 +
    /// The `tags` component.
417 +
    pub const TAGS: Component<'static> = Component::Normal(name::TAGS);
418 +
    /// A typed reference to the `*` pattern.
419 +
    pub const STAR_PATTERN: &PatternStr = super::STAR;
420 +
}
421 +
422 +
/// A fully qualified refspec pattern.
423 +
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
424 +
pub struct QualifiedPattern<'a>(pub(crate) Cow<'a, PatternStr>);
425 +
426 +
impl<'a> QualifiedPattern<'a> {
427 +
    /// Returns `pattern` as qualified if it starts with `refs/` and has a category and name.
428 +
    pub fn from_patternstr(pattern: impl Into<Cow<'a, PatternStr>>) -> Option<Self> {
429 +
        let pattern = pattern.into();
430 +
        let mut iter = pattern.iter();
431 +
        match (iter.next(), iter.next(), iter.next()) {
432 +
            (Some("refs"), Some(_), Some(_)) => Some(Self(pattern)),
433 +
            _ => None,
434 +
        }
435 +
    }
436 +
437 +
    /// Returns the qualified pattern as a string.
438 +
    #[inline]
439 +
    pub fn as_str(&self) -> &str {
440 +
        self.as_ref()
441 +
    }
442 +
443 +
    /// Joins another refname suffix.
444 +
    #[inline]
445 +
    pub fn join<'b, R>(&self, other: R) -> QualifiedPattern<'b>
446 +
    where
447 +
        R: AsRef<RefStr>,
448 +
    {
449 +
        QualifiedPattern(Cow::Owned(self.0.join(other)))
450 +
    }
451 +
452 +
    /// Returns this pattern as namespaced if it has a namespace prefix.
453 +
    #[inline]
454 +
    pub fn to_namespaced(&self) -> Option<NamespacedPattern<'_>> {
455 +
        self.0.as_ref().into()
456 +
    }
457 +
458 +
    /// Adds `refs/namespaces/<namespace>/` before this pattern.
459 +
    pub fn with_namespace<'b>(
460 +
        &self,
461 +
        namespace: crate::git::refs::Component<'b>,
462 +
    ) -> Result<NamespacedPattern<'a>, DuplicateGlob> {
463 +
        let prefix = [
464 +
            Component::Normal(name::REFS),
465 +
            Component::Normal(name::NAMESPACES),
466 +
            Component::Normal(namespace.as_ref()),
467 +
        ];
468 +
        PatternString::from_components(IntoIterator::into_iter(prefix).chain(self.components()))
469 +
            .map(|pattern| NamespacedPattern(Cow::Owned(pattern)))
470 +
    }
471 +
472 +
    /// Returns the first three string components and the remaining iterator.
473 +
    #[allow(clippy::panic)]
474 +
    pub fn non_empty_iter(&self) -> (&str, &str, &str, Iter<'_>) {
475 +
        let mut iter = self.iter();
476 +
        let (Some(first), Some(second), Some(third)) = (iter.next(), iter.next(), iter.next())
477 +
        else {
478 +
            panic!("QualifiedPattern::non_empty_iter: missing component");
479 +
        };
480 +
        (first, second, third, iter)
481 +
    }
482 +
483 +
    /// Returns the first three components and the remaining iterator.
484 +
    #[allow(clippy::panic)]
485 +
    pub fn non_empty_components(
486 +
        &self,
487 +
    ) -> (Component<'_>, Component<'_>, Component<'_>, Components<'_>) {
488 +
        let mut components = self.components();
489 +
        let (Some(first), Some(second), Some(third)) =
490 +
            (components.next(), components.next(), components.next())
491 +
        else {
492 +
            panic!("QualifiedPattern::non_empty_components: missing component");
493 +
        };
494 +
        (first, second, third, components)
495 +
    }
496 +
497 +
    /// Returns an owned qualified pattern.
498 +
    #[inline]
499 +
    pub fn to_owned<'b>(&self) -> QualifiedPattern<'b> {
500 +
        QualifiedPattern(Cow::Owned(self.0.clone().into_owned()))
501 +
    }
502 +
503 +
    /// Converts this value into an owned qualified pattern.
504 +
    #[inline]
505 +
    pub fn into_owned<'b>(self) -> QualifiedPattern<'b> {
506 +
        QualifiedPattern(Cow::Owned(self.0.into_owned()))
507 +
    }
508 +
509 +
    /// Converts this qualified pattern into an owned pattern.
510 +
    #[inline]
511 +
    pub fn into_patternstring(self) -> PatternString {
512 +
        self.into()
513 +
    }
514 +
}
515 +
516 +
impl Deref for QualifiedPattern<'_> {
517 +
    type Target = PatternStr;
518 +
519 +
    #[inline]
520 +
    fn deref(&self) -> &Self::Target {
521 +
        &self.0
522 +
    }
523 +
}
524 +
525 +
impl AsRef<PatternStr> for QualifiedPattern<'_> {
526 +
    #[inline]
527 +
    fn as_ref(&self) -> &PatternStr {
528 +
        self
529 +
    }
530 +
}
531 +
532 +
impl AsRef<str> for QualifiedPattern<'_> {
533 +
    #[inline]
534 +
    fn as_ref(&self) -> &str {
535 +
        self.0.as_str()
536 +
    }
537 +
}
538 +
539 +
impl AsRef<Self> for QualifiedPattern<'_> {
540 +
    #[inline]
541 +
    fn as_ref(&self) -> &Self {
542 +
        self
543 +
    }
544 +
}
545 +
546 +
impl<'a> From<QualifiedPattern<'a>> for Cow<'a, PatternStr> {
547 +
    #[inline]
548 +
    fn from(pattern: QualifiedPattern<'a>) -> Self {
549 +
        pattern.0
550 +
    }
551 +
}
552 +
553 +
impl From<QualifiedPattern<'_>> for PatternString {
554 +
    #[inline]
555 +
    fn from(pattern: QualifiedPattern<'_>) -> Self {
556 +
        pattern.0.into_owned()
557 +
    }
558 +
}
559 +
560 +
/// A qualified refspec pattern under a Git namespace.
561 +
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
562 +
pub struct NamespacedPattern<'a>(Cow<'a, PatternStr>);
563 +
564 +
impl<'a> NamespacedPattern<'a> {
565 +
    /// Returns the namespace component.
566 +
    #[allow(clippy::panic)]
567 +
    pub fn namespace(&self) -> Component<'_> {
568 +
        let Some(namespace) = self.components().nth(2) else {
569 +
            panic!("NamespacedPattern::namespace: missing namespace component");
570 +
        };
571 +
        namespace
572 +
    }
573 +
574 +
    /// Removes the outer namespace.
575 +
    #[allow(clippy::panic)]
576 +
    pub fn strip_namespace(&self) -> PatternString {
577 +
        match PatternString::from_components(self.components().skip(3)) {
578 +
            Ok(pattern) => pattern,
579 +
            Err(_) => panic!("NamespacedPattern::strip_namespace: duplicate glob"),
580 +
        }
581 +
    }
582 +
583 +
    /// Removes all nested namespaces.
584 +
    pub fn strip_namespace_recursive(&self) -> PatternString {
585 +
        let mut stripped = self.strip_namespace();
586 +
        while let Some(namespaced) = stripped.to_namespaced() {
587 +
            stripped = namespaced.strip_namespace();
588 +
        }
589 +
        stripped
590 +
    }
591 +
592 +
    /// Returns an owned namespaced pattern.
593 +
    #[inline]
594 +
    pub fn to_owned<'b>(&self) -> NamespacedPattern<'b> {
595 +
        NamespacedPattern(Cow::Owned(self.0.clone().into_owned()))
596 +
    }
597 +
598 +
    /// Converts this value into an owned namespaced pattern.
599 +
    #[inline]
600 +
    pub fn into_owned<'b>(self) -> NamespacedPattern<'b> {
601 +
        NamespacedPattern(Cow::Owned(self.0.into_owned()))
602 +
    }
603 +
604 +
    /// Converts this value into a qualified pattern.
605 +
    #[inline]
606 +
    pub fn into_qualified(self) -> QualifiedPattern<'a> {
607 +
        QualifiedPattern(self.0)
608 +
    }
609 +
}
610 +
611 +
impl Deref for NamespacedPattern<'_> {
612 +
    type Target = PatternStr;
613 +
614 +
    #[inline]
615 +
    fn deref(&self) -> &Self::Target {
616 +
        self.borrow()
617 +
    }
618 +
}
619 +
620 +
impl AsRef<PatternStr> for NamespacedPattern<'_> {
621 +
    #[inline]
622 +
    fn as_ref(&self) -> &PatternStr {
623 +
        self.0.as_ref()
624 +
    }
625 +
}
626 +
627 +
impl AsRef<str> for NamespacedPattern<'_> {
628 +
    #[inline]
629 +
    fn as_ref(&self) -> &str {
630 +
        self.0.as_str()
631 +
    }
632 +
}
633 +
634 +
impl Borrow<PatternStr> for NamespacedPattern<'_> {
635 +
    #[inline]
636 +
    fn borrow(&self) -> &PatternStr {
637 +
        PatternStr::from_str(self.0.as_str())
638 +
    }
639 +
}
640 +
641 +
impl<'a> From<NamespacedPattern<'a>> for QualifiedPattern<'a> {
642 +
    #[inline]
643 +
    fn from(pattern: NamespacedPattern<'a>) -> Self {
644 +
        Self(pattern.0)
645 +
    }
646 +
}
647 +
648 +
impl<'a> From<&'a PatternStr> for Option<NamespacedPattern<'a>> {
649 +
    fn from(pattern: &'a PatternStr) -> Self {
650 +
        let mut components = pattern.iter();
651 +
        match (
652 +
            components.next(),
653 +
            components.next(),
654 +
            components.next(),
655 +
            components.next(),
656 +
        ) {
657 +
            (Some("refs"), Some("namespaces"), Some(_), Some("refs")) => {
658 +
                Some(NamespacedPattern(Cow::from(pattern)))
659 +
            }
660 +
            _ => None,
661 +
        }
662 +
    }
663 +
}
664 +
665 +
impl Display for NamespacedPattern<'_> {
666 +
    #[inline]
667 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
668 +
        self.0.fmt(f)
669 +
    }
670 +
}
671 +
672 +
/// A Git refspec with source, destination, and force flag.
673 +
#[derive(Clone, Debug, PartialEq, Eq)]
674 +
pub struct Refspec<T, U> {
675 +
    /// Source refspec side.
676 +
    pub src: T,
677 +
    /// Destination refspec side.
678 +
    pub dst: U,
679 +
    /// Whether this is a forced refspec.
680 +
    pub force: bool,
681 +
}
682 +
683 +
impl<T, U> Display for Refspec<T, U>
684 +
where
685 +
    T: Display,
686 +
    U: Display,
687 +
{
688 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689 +
        if self.force {
690 +
            f.write_char('+')?;
691 +
        }
692 +
        write!(f, "{}:{}", self.src, self.dst)
693 +
    }
694 +
}
crates/repo/src/lib.rs +2 -1
4 4
//! width. The [`Repo`] trait keeps that repository access behind a small
5 5
//! boundary so diff viewers stay I/O-free and testable; [`GitRepo`] is the
6 6
//! `git diff` implementation used by the `rustik-diff` pager. The trait yields
7 7
//! raw unified-diff bytes — parsing is left to the caller, so this crate
8 8
//! carries no diff-format dependency.
9 -
#![deny(unsafe_code)]
10 9
#![warn(missing_docs)]
11 10
#![warn(clippy::unwrap_used)]
12 11
12 +
pub mod git;
13 +
13 14
use std::ffi::{OsStr, OsString};
14 15
use std::io::{self, Read as _};
15 16
use std::path::{Path, PathBuf};
16 17
use std::process::{Command, Stdio};
17 18