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
use std::{error, fmt, str::FromStr};

use globset::{Error as GlobError, Glob, GlobBuilder, GlobMatcher};

use crate::version::{self, PartialVersion, VersionError};

use super::Runtime;

#[derive(Debug)]
pub enum ConstraintError {
    GlobError(GlobError),
    VersionError(version::VersionError),
}

impl fmt::Display for ConstraintError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        use ConstraintError::*;
        match self {
            GlobError(ref error) => write!(fmt, "could not parse constraint: {error}",),
            VersionError(ref error) => write!(
                fmt,
                "could not parse version constraint {text:?}: {error}",
                text = error.text().unwrap_or("<unknown>")
            ),
        }
    }
}

impl error::Error for ConstraintError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match *self {
            ConstraintError::GlobError(ref error) => Some(error),
            ConstraintError::VersionError(ref error) => Some(error),
        }
    }
}

impl From<GlobError> for ConstraintError {
    fn from(error: GlobError) -> ConstraintError {
        ConstraintError::GlobError(error)
    }
}

impl From<version::VersionError> for ConstraintError {
    fn from(error: version::VersionError) -> ConstraintError {
        ConstraintError::VersionError(error)
    }
}

/// A constraint used when selecting a PostgreSQL runtime.
#[derive(Clone, Debug)]
pub enum Constraint {
    /// Match the runtime's `bindir`.
    BinDir(GlobMatcher),
    /// Match the given version.
    Version(PartialVersion),
    /// Either constraint can be satisfied.
    Either(Box<Constraint>, Box<Constraint>),
    /// Both constraints must be satisfied.
    Both(Box<Constraint>, Box<Constraint>),
    /// Invert the given constraint; use `!constraint` for the same effect.
    Not(Box<Constraint>),
    /// Match any runtime.
    Anything,
    /// Match no runtimes at all.
    Nothing,
}

impl Constraint {
    /// Match the given runtime's `bindir` against this glob pattern.
    ///
    /// The [syntax](https://docs.rs/globset/latest/globset/index.html#syntax)
    /// comes from the [globset](https://crates.io/crates/globset) crate.
    /// However, here we deviate from its default rules:
    ///
    /// - `*` and `?` do **not** match path separators (`/`); use `**` for that.
    /// - empty alternators, e.g. `{,.rs}` are allowed.
    ///
    /// Use [`glob`][`Self::glob`] if you want to select your own rules.
    pub fn path(pattern: &str) -> Result<Self, GlobError> {
        Ok(Self::BinDir(
            GlobBuilder::new(pattern)
                .literal_separator(true)
                .empty_alternates(true)
                .build()?
                .compile_matcher(),
        ))
    }

    /// Match the given runtime's `bindir` against this glob.
    pub fn glob(glob: &Glob) -> Self {
        Self::BinDir(glob.compile_matcher())
    }

    /// Match the given runtime against this version.
    pub fn version(version: &str) -> Result<Self, VersionError> {
        Ok(Self::Version(version.parse()?))
    }

    /// Match **any** of the given constraints.
    ///
    /// If there are no constraints, this returns [`Self::Nothing`].
    pub fn any<C: IntoIterator<Item = Constraint>>(constraints: C) -> Self {
        constraints
            .into_iter()
            .reduce(|a, b| a | b)
            .unwrap_or(Self::Nothing)
    }

    /// Match **all** of the given constraints.
    ///
    /// If there are no constraints, this returns [`Self::Anything`].
    pub fn all<C: IntoIterator<Item = Constraint>>(constraints: C) -> Self {
        constraints
            .into_iter()
            .reduce(|a, b| a & b)
            .unwrap_or(Self::Anything)
    }

    /// Does the given runtime match this constraint?
    pub fn matches(&self, runtime: &Runtime) -> bool {
        match self {
            Self::BinDir(matcher) => matcher.is_match(&runtime.bindir),
            Self::Version(version) => version.compatible(runtime.version),
            Self::Either(ca, cb) => ca.matches(runtime) || cb.matches(runtime),
            Self::Both(ca, cb) => ca.matches(runtime) && cb.matches(runtime),
            Self::Not(constraint) => !constraint.matches(runtime),
            Self::Anything => true,
            Self::Nothing => false,
        }
    }
}

impl std::ops::Not for Constraint {
    type Output = Self;

    /// Invert this constraint.
    fn not(self) -> Self::Output {
        match self {
            Self::Anything => Self::Nothing,
            Self::Nothing => Self::Anything,
            Self::Not(constraint) => *constraint,
            _ => Self::Not(Box::new(self)),
        }
    }
}

impl std::ops::BitOr for Constraint {
    type Output = Self;

    /// Match either of the constraints.
    fn bitor(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Self::Anything, _) | (_, Self::Anything) => Self::Anything,
            (Self::Nothing, c) | (c, Self::Nothing) => c,
            (ca, cb) => Self::Either(Box::new(ca), Box::new(cb)),
        }
    }
}

impl std::ops::BitAnd for Constraint {
    type Output = Self;

    /// Match both the constraints.
    fn bitand(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Self::Anything, c) | (c, Self::Anything) => c,
            (Self::Nothing, _) | (_, Self::Nothing) => Self::Nothing,
            (ca, cb) => Self::Both(Box::new(ca), Box::new(cb)),
        }
    }
}

impl From<PartialVersion> for Constraint {
    /// Convert a [`PartialVersion`] into a [`Constraint::Version`].
    fn from(version: PartialVersion) -> Self {
        Self::Version(version)
    }
}

impl FromStr for Constraint {
    type Err = ConstraintError;

    /// Parse a constraint from a string.
    ///
    /// If it contains a path separator, it will be parsed as a glob pattern,
    /// otherwise it will be parsed as a version constraint.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.contains(std::path::MAIN_SEPARATOR) {
            Ok(Self::path(s)?)
        } else {
            Ok(Self::version(s)?)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Constraint;
    use super::PartialVersion;

    /// An example constraint.
    const CONSTRAINT: Constraint = Constraint::Version(PartialVersion::Post10m(13));

    #[test]
    fn test_not() {
        let c1 = Constraint::Version(PartialVersion::Post10m(13));
        assert!(matches!(c1, Constraint::Version(_)));
        let c2 = !c1;
        assert!(matches!(c2, Constraint::Not(_)));
        let c3 = !c2;
        assert!(matches!(c3, Constraint::Version(_)));
    }

    #[test]
    fn test_not_anything_and_nothing() {
        let c1 = Constraint::Anything;
        let c2 = !c1;
        assert!(matches!(c2, Constraint::Nothing));
        let c3 = !c2;
        assert!(matches!(c3, Constraint::Anything));
    }

    #[test]
    fn test_or() {
        assert!(matches!(
            Constraint::Anything | CONSTRAINT.clone(),
            Constraint::Anything
        ));
        assert!(matches!(
            CONSTRAINT.clone() | Constraint::Anything,
            Constraint::Anything
        ));
        assert!(matches!(
            Constraint::Nothing | CONSTRAINT.clone(),
            Constraint::Version(_)
        ));
        assert!(matches!(
            CONSTRAINT.clone() | Constraint::Nothing,
            Constraint::Version(_)
        ));
    }

    #[test]
    fn test_or_anything_and_nothing() {
        assert!(matches!(
            Constraint::Anything | Constraint::Anything,
            Constraint::Anything
        ));
        assert!(matches!(
            Constraint::Nothing | Constraint::Anything,
            Constraint::Anything
        ));
        assert!(matches!(
            Constraint::Anything | Constraint::Nothing,
            Constraint::Anything
        ));
    }

    #[test]
    fn test_and() {
        assert!(matches!(
            Constraint::Anything & CONSTRAINT.clone(),
            Constraint::Version(_)
        ));
        assert!(matches!(
            CONSTRAINT.clone() & Constraint::Anything,
            Constraint::Version(_)
        ));
        assert!(matches!(
            Constraint::Nothing & CONSTRAINT.clone(),
            Constraint::Nothing
        ));
        assert!(matches!(
            CONSTRAINT.clone() & Constraint::Nothing,
            Constraint::Nothing
        ));
    }

    #[test]
    fn test_and_anything_and_nothing() {
        assert!(matches!(
            Constraint::Anything & Constraint::Anything,
            Constraint::Anything
        ));
        assert!(matches!(
            Constraint::Nothing & Constraint::Anything,
            Constraint::Nothing
        ));
        assert!(matches!(
            Constraint::Anything & Constraint::Nothing,
            Constraint::Nothing
        ));
    }

    #[test]
    fn test_any() {
        assert!(matches!(Constraint::any([]), Constraint::Nothing));
        assert!(matches!(
            Constraint::any([
                Constraint::Anything,
                Constraint::Nothing,
                Constraint::Nothing
            ]),
            Constraint::Anything
        ));
        assert!(matches!(
            Constraint::any([Constraint::Nothing, CONSTRAINT.clone(), Constraint::Nothing]),
            Constraint::Version(_)
        ));
        assert!(matches!(
            Constraint::any([
                Constraint::Anything,
                CONSTRAINT.clone(),
                Constraint::Nothing
            ]),
            Constraint::Anything
        ));
        assert!(matches!(
            Constraint::any([CONSTRAINT.clone(), CONSTRAINT.clone()]),
            Constraint::Either(ca, cb)
                if matches!(*ca, Constraint::Version(_))
                && matches!(*cb, Constraint::Version(_))
        ));
    }

    #[test]
    fn test_all() {
        assert!(matches!(Constraint::all([]), Constraint::Anything));
        assert!(matches!(
            Constraint::all([
                Constraint::Anything,
                Constraint::Anything,
                Constraint::Anything
            ]),
            Constraint::Anything
        ));
        assert!(matches!(
            Constraint::all([
                Constraint::Anything,
                CONSTRAINT.clone(),
                Constraint::Anything,
            ]),
            Constraint::Version(_),
        ));
        assert!(matches!(
            Constraint::all([
                Constraint::Anything,
                CONSTRAINT.clone(),
                Constraint::Nothing,
            ]),
            Constraint::Nothing,
        ));
        assert!(matches!(
            Constraint::all([CONSTRAINT.clone(), CONSTRAINT.clone()]),
            Constraint::Both(ca, cb)
                if matches!(*ca, Constraint::Version(_))
                && matches!(*cb, Constraint::Version(_))
        ));
    }
}