crates/repo/src/git/refs/name.rs 14.4 KiB raw
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
}