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
// Copyright © 2021 The Radicle Link Contributors
//
// This file is part of radicle-link, distributed under the GPLv3 with Radicle
// Linking Exception. For full terms see the included LICENSE file.

use std::{
    borrow::Cow,
    fmt::{self, Display},
    ops::Deref,
};

use crate::{
    lit, name,
    refspec::{PatternStr, QualifiedPattern},
    Component, RefStr, RefString,
};

/// A fully-qualified refname.
///
/// A refname is qualified _iff_ it starts with "refs/" and has at least three
/// components. This implies that a [`Qualified`] ref has a category, such as
/// "refs/heads/main".
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
pub struct Qualified<'a>(pub(crate) Cow<'a, RefStr>);

impl<'a> Qualified<'a> {
    /// Infallibly create a [`Qualified`] from components.
    ///
    /// Note that the "refs/" prefix is implicitly added, so `a` is the second
    /// [`Component`]. Mirroring [`Self::non_empty_components`], providing
    /// two [`Component`]s guarantees well-formedness of the [`Qualified`].
    /// `tail` may be empty.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use git_ref_format::{component, Qualified};
    ///
    /// assert_eq!(
    ///     "refs/heads/main",
    ///     Qualified::from_components(component::HEADS, component::MAIN, None).as_str()
    /// )
    /// ```
    pub fn from_components<'b, 'c, 'd, A, B, C>(a: A, b: B, tail: C) -> Self
    where
        A: Into<Component<'b>>,
        B: Into<Component<'c>>,
        C: IntoIterator<Item = Component<'d>>,
    {
        let mut inner = name::REFS.join(a.into()).and(b.into());
        inner.extend(tail);

        Self(inner.into())
    }

    pub fn from_refstr(r: impl Into<Cow<'a, RefStr>>) -> Option<Self> {
        Self::_from_refstr(r.into())
    }

    fn _from_refstr(r: Cow<'a, RefStr>) -> Option<Self> {
        let mut iter = r.iter();
        match (iter.next()?, iter.next()?, iter.next()?) {
            ("refs", _, _) => Some(Qualified(r)),
            _ => None,
        }
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        self.as_ref()
    }

    #[inline]
    pub fn join<'b, R>(&self, other: R) -> Qualified<'b>
    where
        R: AsRef<RefStr>,
    {
        Qualified(self.0.join(other).into())
    }

    pub fn to_pattern<P>(&self, pattern: P) -> QualifiedPattern
    where
        P: AsRef<PatternStr>,
    {
        QualifiedPattern(Cow::Owned(RefStr::to_pattern(self, pattern.as_ref())))
    }

    #[inline]
    pub fn to_namespaced(&self) -> Option<Namespaced> {
        self.0.as_ref().into()
    }

    /// Add a namespace.
    ///
    /// Creates a new [`Namespaced`] by prefxing `self` with
    /// `refs/namespaces/<ns>`.
    pub fn with_namespace<'b>(&self, ns: Component<'b>) -> Namespaced<'a> {
        Namespaced(Cow::Owned(
            IntoIterator::into_iter([lit::Refs.into(), lit::Namespaces.into(), ns])
                .chain(self.0.components())
                .collect(),
        ))
    }

    /// Like [`Self::non_empty_components`], but with string slices.
    pub fn non_empty_iter(&self) -> (&str, &str, &str, name::Iter) {
        let mut iter = self.iter();
        (
            iter.next().unwrap(),
            iter.next().unwrap(),
            iter.next().unwrap(),
            iter,
        )
    }

    /// Return the first three [`Component`]s, and a possibly empty iterator
    /// over the remaining ones.
    ///
    /// A qualified ref is guaranteed to have at least three components, which
    /// this method provides a witness of. This is useful eg. for pattern
    /// matching on the prefix.
    pub fn non_empty_components(&self) -> (Component, Component, Component, name::Components) {
        let mut cs = self.components();
        (
            cs.next().unwrap(),
            cs.next().unwrap(),
            cs.next().unwrap(),
            cs,
        )
    }

    #[inline]
    pub fn to_owned<'b>(&self) -> Qualified<'b> {
        Qualified(Cow::Owned(self.0.clone().into_owned()))
    }

    #[inline]
    pub fn into_owned<'b>(self) -> Qualified<'b> {
        Qualified(Cow::Owned(self.0.into_owned()))
    }

    #[inline]
    pub fn into_refstring(self) -> RefString {
        self.into()
    }
}

impl Deref for Qualified<'_> {
    type Target = RefStr;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<RefStr> for Qualified<'_> {
    #[inline]
    fn as_ref(&self) -> &RefStr {
        self
    }
}

impl AsRef<str> for Qualified<'_> {
    #[inline]
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

impl AsRef<Self> for Qualified<'_> {
    #[inline]
    fn as_ref(&self) -> &Self {
        self
    }
}

impl<'a> From<Qualified<'a>> for Cow<'a, RefStr> {
    #[inline]
    fn from(q: Qualified<'a>) -> Self {
        q.0
    }
}

impl From<Qualified<'_>> for RefString {
    #[inline]
    fn from(q: Qualified) -> Self {
        q.0.into_owned()
    }
}

impl<T, U> From<(lit::Refs, T, U)> for Qualified<'_>
where
    T: AsRef<RefStr>,
    U: AsRef<RefStr>,
{
    #[inline]
    fn from((refs, cat, name): (lit::Refs, T, U)) -> Self {
        let refs: &RefStr = refs.into();
        Self(Cow::Owned(refs.join(cat).and(name)))
    }
}

impl<T> From<lit::RefsHeads<T>> for Qualified<'_>
where
    T: AsRef<RefStr>,
{
    #[inline]
    fn from((refs, heads, name): lit::RefsHeads<T>) -> Self {
        Self(Cow::Owned(
            IntoIterator::into_iter([Component::from(refs), heads.into()])
                .collect::<RefString>()
                .and(name),
        ))
    }
}

impl<T> From<lit::RefsTags<T>> for Qualified<'_>
where
    T: AsRef<RefStr>,
{
    #[inline]
    fn from((refs, tags, name): lit::RefsTags<T>) -> Self {
        Self(Cow::Owned(
            IntoIterator::into_iter([Component::from(refs), tags.into()])
                .collect::<RefString>()
                .and(name),
        ))
    }
}

impl<T> From<lit::RefsNotes<T>> for Qualified<'_>
where
    T: AsRef<RefStr>,
{
    #[inline]
    fn from((refs, notes, name): lit::RefsNotes<T>) -> Self {
        Self(Cow::Owned(
            IntoIterator::into_iter([Component::from(refs), notes.into()])
                .collect::<RefString>()
                .and(name),
        ))
    }
}

impl<T> From<lit::RefsRemotes<T>> for Qualified<'_>
where
    T: AsRef<RefStr>,
{
    #[inline]
    fn from((refs, remotes, name): lit::RefsRemotes<T>) -> Self {
        Self(Cow::Owned(
            IntoIterator::into_iter([Component::from(refs), remotes.into()])
                .collect::<RefString>()
                .and(name),
        ))
    }
}

impl Display for Qualified<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A [`Qualified`] ref under a git namespace.
///
/// A ref is namespaced if it starts with "refs/namespaces/", another path
/// component, and "refs/". Eg.
///
///     refs/namespaces/xyz/refs/heads/main
///
/// Note that namespaces can be nested, so the result of
/// [`Namespaced::strip_namespace`] may be convertible to a [`Namespaced`]
/// again. For example:
///
/// ```no_run
/// let full = refname!("refs/namespaces/a/refs/namespaces/b/refs/heads/main");
/// let namespaced = full.namespaced().unwrap();
/// let strip_first = namespaced.strip_namespace();
/// let nested = strip_first.namespaced().unwrap();
/// let strip_second = nested.strip_namespace();
///
/// assert_eq!("a", namespaced.namespace().as_str());
/// assert_eq!("b", nested.namespace().as_str());
/// assert_eq!("refs/namespaces/b/refs/heads/main", strip_first.as_str());
/// assert_eq!("refs/heads/main", strip_second.as_str());
/// ```
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
pub struct Namespaced<'a>(Cow<'a, RefStr>);

impl<'a> Namespaced<'a> {
    pub fn namespace(&self) -> Component {
        self.components().nth(2).unwrap()
    }

    pub fn strip_namespace<'b>(&self) -> Qualified<'b> {
        const REFS_NAMESPACES: &RefStr = RefStr::from_str("refs/namespaces");

        Qualified(Cow::Owned(
            self.strip_prefix(REFS_NAMESPACES)
                .unwrap()
                .components()
                .skip(1)
                .collect(),
        ))
    }

    pub fn strip_namespace_recursive<'b>(&self) -> Qualified<'b> {
        let mut strip = self.strip_namespace();
        while let Some(ns) = strip.to_namespaced() {
            strip = ns.strip_namespace();
        }
        strip
    }

    #[inline]
    pub fn to_owned<'b>(&self) -> Namespaced<'b> {
        Namespaced(Cow::Owned(self.0.clone().into_owned()))
    }

    #[inline]
    pub fn into_owned<'b>(self) -> Namespaced<'b> {
        Namespaced(Cow::Owned(self.0.into_owned()))
    }

    #[inline]
    pub fn into_qualified(self) -> Qualified<'a> {
        self.into()
    }
}

impl Deref for Namespaced<'_> {
    type Target = RefStr;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<RefStr> for Namespaced<'_> {
    #[inline]
    fn as_ref(&self) -> &RefStr {
        self
    }
}

impl AsRef<str> for Namespaced<'_> {
    #[inline]
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

impl<'a> From<Namespaced<'a>> for Qualified<'a> {
    #[inline]
    fn from(ns: Namespaced<'a>) -> Self {
        Self(ns.0)
    }
}

impl<'a> From<&'a RefStr> for Option<Namespaced<'a>> {
    fn from(rs: &'a RefStr) -> Self {
        let mut cs = rs.iter();
        match (cs.next()?, cs.next()?, cs.next()?, cs.next()?) {
            ("refs", "namespaces", _, "refs") => Some(Namespaced(Cow::from(rs))),

            _ => None,
        }
    }
}

impl<'a, T> From<lit::RefsNamespaces<'_, T>> for Namespaced<'static>
where
    T: Into<Component<'a>>,
{
    #[inline]
    fn from((refs, namespaces, namespace, name): lit::RefsNamespaces<T>) -> Self {
        Self(Cow::Owned(
            IntoIterator::into_iter([refs.into(), namespaces.into(), namespace.into()])
                .collect::<RefString>()
                .and(name),
        ))
    }
}

impl Display for Namespaced<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}