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
// This file is part of radicle-git
// <https://github.com/radicle-dev/radicle-git>
//
// Copyright (C) 2022 The Radicle Team <dev@radicle.xyz>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 or
// later as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use std::marker::PhantomData;

use git_ext::ref_format::{
    self, refname,
    refspec::{self, PatternString, QualifiedPattern},
    Qualified, RefStr, RefString,
};
use thiserror::Error;

use crate::{Branch, Local, Namespace, Remote, Tag};

#[derive(Debug, Error)]
pub enum Error {
    #[error(transparent)]
    RefFormat(#[from] ref_format::Error),
}

/// A collection of globs for a git reference type.
#[derive(Clone, Debug)]
pub struct Glob<T> {
    globs: Vec<QualifiedPattern<'static>>,
    glob_type: PhantomData<T>, // To support different methods for different T.
}

impl<T> Default for Glob<T> {
    fn default() -> Self {
        Self {
            globs: Default::default(),
            glob_type: PhantomData,
        }
    }
}

impl<T> Glob<T> {
    /// Return the [`QualifiedPattern`] globs of this `Glob`.
    pub fn globs(&self) -> impl Iterator<Item = &QualifiedPattern<'static>> {
        self.globs.iter()
    }

    /// Combine two `Glob`s together by combining their glob lists together.
    ///
    /// Note that the `Glob`s must result in the same type,
    /// e.g. `Glob<Tag>` can only combine with `Glob<Tag>`,
    /// `Glob<Local>` can combine with `Glob<Remote>`, etc.
    pub fn and(mut self, other: impl Into<Self>) -> Self {
        self.globs.extend(other.into().globs);
        self
    }
}

impl Glob<Namespace> {
    /// Creates the `Glob` that matches all `refs/namespaces`.
    pub fn all_namespaces() -> Self {
        Self::namespaces(refspec::pattern!("*"))
    }

    /// Creates a `Glob` for `refs/namespaces`, starting with `glob`.
    pub fn namespaces(glob: PatternString) -> Self {
        let globs = vec![Self::qualify(glob)];
        Self {
            globs,
            glob_type: PhantomData,
        }
    }

    /// Adds a `refs/namespaces` pattern to this `Glob`.
    pub fn insert(mut self, glob: PatternString) -> Self {
        self.globs.push(Self::qualify(glob));
        self
    }

    fn qualify(glob: PatternString) -> QualifiedPattern<'static> {
        qualify(&refname!("refs/namespaces"), glob).expect("BUG: pattern is qualified")
    }
}

impl FromIterator<PatternString> for Glob<Namespace> {
    fn from_iter<T: IntoIterator<Item = PatternString>>(iter: T) -> Self {
        let globs = iter
            .into_iter()
            .map(|pat| {
                qualify(&refname!("refs/namespaces"), pat).expect("BUG: pattern is qualified")
            })
            .collect();

        Self {
            globs,
            glob_type: PhantomData,
        }
    }
}

impl Extend<PatternString> for Glob<Namespace> {
    fn extend<T: IntoIterator<Item = PatternString>>(&mut self, iter: T) {
        self.globs.extend(iter.into_iter().map(|pat| {
            qualify(&refname!("refs/namespaces"), pat).expect("BUG: pattern is qualified")
        }))
    }
}

impl Glob<Tag> {
    /// Creates a `Glob` that matches all `refs/tags`.
    pub fn all_tags() -> Self {
        Self::tags(refspec::pattern!("*"))
    }

    /// Creates a `Glob` for `refs/tags`, starting with `glob`.
    pub fn tags(glob: PatternString) -> Self {
        let globs = vec![Self::qualify(glob)];
        Self {
            globs,
            glob_type: PhantomData,
        }
    }

    /// Adds a `refs/tags` pattern to this `Glob`.
    pub fn insert(mut self, glob: PatternString) -> Self {
        self.globs.push(Self::qualify(glob));
        self
    }

    fn qualify(glob: PatternString) -> QualifiedPattern<'static> {
        qualify(&refname!("refs/tags"), glob).expect("BUG: pattern is qualified")
    }
}

impl FromIterator<PatternString> for Glob<Tag> {
    fn from_iter<T: IntoIterator<Item = PatternString>>(iter: T) -> Self {
        let globs = iter
            .into_iter()
            .map(|pat| qualify(&refname!("refs/tags"), pat).expect("BUG: pattern is qualified"))
            .collect();

        Self {
            globs,
            glob_type: PhantomData,
        }
    }
}

impl Extend<PatternString> for Glob<Tag> {
    fn extend<T: IntoIterator<Item = PatternString>>(&mut self, iter: T) {
        self.globs.extend(
            iter.into_iter()
                .map(|pat| qualify(&refname!("refs/tag"), pat).expect("BUG: pattern is qualified")),
        )
    }
}

impl Glob<Local> {
    /// Creates the `Glob` that matches all `refs/heads`.
    pub fn all_heads() -> Self {
        Self::heads(refspec::pattern!("*"))
    }

    /// Creates a `Glob` for `refs/heads`, starting with `glob`.
    pub fn heads(glob: PatternString) -> Self {
        let globs = vec![Self::qualify_heads(glob)];
        Self {
            globs,
            glob_type: PhantomData,
        }
    }

    /// Adds a `refs/heads` pattern to this `Glob`.
    pub fn insert(mut self, glob: PatternString) -> Self {
        self.globs.push(Self::qualify_heads(glob));
        self
    }

    /// When chaining `Glob<Local>` with `Glob<Remote>`, use
    /// `branches` to convert this `Glob<Local>` into a
    /// `Glob<Branch>`.
    ///
    /// # Example
    /// ```no_run
    /// Glob::heads(pattern!("features/*"))
    ///     .insert(pattern!("qa/*"))
    ///     .branches()
    ///     .and(Glob::remotes(pattern!("origin/features/*")))
    /// ```
    pub fn branches(self) -> Glob<Branch> {
        self.into()
    }

    fn qualify_heads(glob: PatternString) -> QualifiedPattern<'static> {
        qualify(&refname!("refs/heads"), glob).expect("BUG: pattern is qualified")
    }
}

impl FromIterator<PatternString> for Glob<Local> {
    fn from_iter<T: IntoIterator<Item = PatternString>>(iter: T) -> Self {
        let globs = iter
            .into_iter()
            .map(|pat| qualify(&refname!("refs/heads"), pat).expect("BUG: pattern is qualified"))
            .collect();

        Self {
            globs,
            glob_type: PhantomData,
        }
    }
}

impl Extend<PatternString> for Glob<Local> {
    fn extend<T: IntoIterator<Item = PatternString>>(&mut self, iter: T) {
        self.globs.extend(
            iter.into_iter().map(|pat| {
                qualify(&refname!("refs/heads"), pat).expect("BUG: pattern is qualified")
            }),
        )
    }
}

impl From<Glob<Local>> for Glob<Branch> {
    fn from(Glob { globs, .. }: Glob<Local>) -> Self {
        Self {
            globs,
            glob_type: PhantomData,
        }
    }
}

impl Glob<Remote> {
    /// Creates the `Glob` that matches all `refs/remotes`.
    pub fn all_remotes() -> Self {
        Self::remotes(refspec::pattern!("*"))
    }

    /// Creates a `Glob` for `refs/remotes`, starting with `glob`.
    pub fn remotes(glob: PatternString) -> Self {
        let globs = vec![Self::qualify_remotes(glob)];
        Self {
            globs,
            glob_type: PhantomData,
        }
    }

    /// Adds a `refs/remotes` pattern to this `Glob`.
    pub fn insert(mut self, glob: PatternString) -> Self {
        self.globs.push(Self::qualify_remotes(glob));
        self
    }

    /// When chaining `Glob<Remote>` with `Glob<Local>`, use
    /// `branches` to convert this `Glob<Remote>` into a
    /// `Glob<Branch>`.
    ///
    /// # Example
    /// ```no_run
    /// Glob::remotes(pattern!("origin/features/*"))
    ///     .insert(pattern!("origin/qa/*"))
    ///     .branches()
    ///     .and(Glob::heads(pattern!("features/*")))
    /// ```
    pub fn branches(self) -> Glob<Branch> {
        self.into()
    }

    fn qualify_remotes(glob: PatternString) -> QualifiedPattern<'static> {
        qualify(&refname!("refs/remotes"), glob).expect("BUG: pattern is qualified")
    }
}

impl FromIterator<PatternString> for Glob<Remote> {
    fn from_iter<T: IntoIterator<Item = PatternString>>(iter: T) -> Self {
        let globs = iter
            .into_iter()
            .map(|pat| qualify(&refname!("refs/remotes"), pat).expect("BUG: pattern is qualified"))
            .collect();

        Self {
            globs,
            glob_type: PhantomData,
        }
    }
}

impl Extend<PatternString> for Glob<Remote> {
    fn extend<T: IntoIterator<Item = PatternString>>(&mut self, iter: T) {
        self.globs.extend(
            iter.into_iter().map(|pat| {
                qualify(&refname!("refs/remotes"), pat).expect("BUG: pattern is qualified")
            }),
        )
    }
}

impl From<Glob<Remote>> for Glob<Branch> {
    fn from(Glob { globs, .. }: Glob<Remote>) -> Self {
        Self {
            globs,
            glob_type: PhantomData,
        }
    }
}

impl Glob<Qualified<'_>> {
    pub fn all_category<R: AsRef<RefStr>>(category: R) -> Self {
        Self {
            globs: vec![Self::qualify_category(category, refspec::pattern!("*"))],
            glob_type: PhantomData,
        }
    }

    /// Creates a `Glob` for `refs/<category>`, starting with `glob`.
    pub fn categories<R>(category: R, glob: PatternString) -> Self
    where
        R: AsRef<RefStr>,
    {
        let globs = vec![Self::qualify_category(category, glob)];
        Self {
            globs,
            glob_type: PhantomData,
        }
    }

    /// Adds a `refs/<category>` pattern to this `Glob`.
    pub fn insert<R>(mut self, category: R, glob: PatternString) -> Self
    where
        R: AsRef<RefStr>,
    {
        self.globs.push(Self::qualify_category(category, glob));
        self
    }

    fn qualify_category<R>(category: R, glob: PatternString) -> QualifiedPattern<'static>
    where
        R: AsRef<RefStr>,
    {
        let prefix = refname!("refs").and(category);
        qualify(&prefix, glob).expect("BUG: pattern is qualified")
    }
}

fn qualify(prefix: &RefString, glob: PatternString) -> Option<QualifiedPattern<'static>> {
    prefix.to_pattern(glob).qualified().map(|q| q.into_owned())
}