jayver 1.0.0

A calendar versioning scheme for binaries developed by Emmett Jayhart
Documentation
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Version requirements for Jayhart versioning.

use std::{
    fmt::{self, Display},
    str::FromStr,
};

#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};

use crate::{
    error::{Error, Result},
    version::Version,
};

/// Comparison operators for version requirements.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub enum Op {
    /// Exact version match (`=`)
    Exact,
    /// Greater than (`>`)
    Greater,
    /// Greater than or equal to (`>=`)
    GreaterEq,
    /// Less than (`<`)
    Less,
    /// Less than or equal to (`<=`)
    LessEq,
    /// Compatible with (`~>`) - same year and week
    Compatible,
}

impl Display for Op {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Op::Exact => write!(f, "="),
            Op::Greater => write!(f, ">"),
            Op::GreaterEq => write!(f, ">="),
            Op::Less => write!(f, "<"),
            Op::LessEq => write!(f, "<="),
            Op::Compatible => write!(f, "~>"),
        }
    }
}

impl FromStr for Op {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "=" => Ok(Op::Exact),
            ">" => Ok(Op::Greater),
            ">=" => Ok(Op::GreaterEq),
            "<" => Ok(Op::Less),
            "<=" => Ok(Op::LessEq),
            "~>" => Ok(Op::Compatible),
            "" => Ok(Op::Exact), // Default to exact match
            op => Err(Error::InvalidOperator {
                operator: op.to_string(),
            }),
        }
    }
}

/// A version comparator consisting of an operator and a version.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct Comparator {
    /// The operator of this comparator
    pub op: Op,
    /// The version to compare to
    pub version: Version,
}

impl Comparator {
    /// Create a new comparator
    pub fn new(op: Op, version: Version) -> Self {
        Self {
            op,
            version,
        }
    }

    /// Parse a comparator from a string
    pub fn parse(input: &str) -> Result<Self> {
        if input.is_empty() {
            return Err(Error::EmptyRequirement);
        }

        // Parse the operator and version parts
        let (op_str, version_str) = if let Some(stripped) = input.strip_prefix(">=") {
            (">=", stripped)
        } else if let Some(stripped) = input.strip_prefix(">") {
            (">", stripped)
        } else if let Some(stripped) = input.strip_prefix("<=") {
            ("<=", stripped)
        } else if let Some(stripped) = input.strip_prefix("<") {
            ("<", stripped)
        } else if let Some(stripped) = input.strip_prefix("=") {
            ("=", stripped)
        } else if let Some(stripped) = input.strip_prefix("~>") {
            ("~>", stripped)
        } else {
            // Default to exact match if no operator
            ("", input)
        };

        // Parse the operator
        let op = op_str.parse::<Op>()?;

        // Parse the version
        let version_str = version_str.trim();
        if version_str.is_empty() {
            return Err(Error::invalid_version("empty version after operator"));
        }

        let version = Version::parse(version_str).map_err(|_| Error::invalid_requirement(input))?;

        Ok(Self {
            op,
            version,
        })
    }

    /// Check if a version matches this comparator
    pub fn matches(&self, version: &Version) -> bool {
        match self.op {
            Op::Exact => version == &self.version,
            Op::Greater => version > &self.version,
            Op::GreaterEq => version >= &self.version,
            Op::Less => version < &self.version,
            Op::LessEq => version <= &self.version,
            Op::Compatible =>
                version.year == self.version.year
                    && version.week == self.version.week
                    && version.patch >= self.version.patch,
        }
    }
}

impl Display for Comparator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.op, self.version)
    }
}

impl FromStr for Comparator {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        Self::parse(s)
    }
}

/// A version requirement, consisting of one or more comparators.
///
/// # Examples
///
/// ```
/// use jayver::{Version, VersionReq};
///
/// let req = VersionReq::parse(">=25.10.0").unwrap();
/// let version = Version::parse("25.12.0").unwrap();
/// assert!(req.matches(&version));
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct VersionReq {
    /// The set of comparators that a version must satisfy
    pub comparators: Vec<Comparator>,
}

/// A version requirement that matches when any of its inner requirements match.
///
/// This is created by using `VersionReq::any()` and allows for "OR" semantics
/// between multiple version requirements.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct AnyVersionReq {
    /// The underlying requirements
    requirements: Vec<VersionReq>,
}

impl VersionReq {
    /// Create a new empty version requirement
    pub fn new() -> Self {
        Self {
            comparators: Vec::new(),
        }
    }

    /// Parse a version requirement string
    pub fn parse<S: AsRef<str>>(input: S) -> Result<Self> {
        let input = input.as_ref().trim();

        // Special case for "*" meaning any version
        if input == "*" {
            return Ok(Self {
                comparators: vec![],
            });
        }

        // Simple implementation - just handle basic cases for now
        if input.is_empty() {
            return Ok(Self {
                comparators: vec![],
            });
        }

        let mut comparators = Vec::new();

        // Split on commas (e.g., ">=1.2.3,<2.0.0")
        for part in input.split(',') {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }

            let comparator =
                Comparator::parse(part).map_err(|_| Error::invalid_requirement(input))?;

            comparators.push(comparator);
        }

        if comparators.is_empty() {
            return Err(Error::EmptyRequirement);
        }

        Ok(Self {
            comparators,
        })
    }

    /// Check if a version satisfies this requirement
    pub fn matches(&self, version: &Version) -> bool {
        // If no comparators, match any version
        if self.comparators.is_empty() {
            return true;
        }

        // All comparators must match
        self.comparators.iter().all(|c| c.matches(version))
    }

    /// Add a comparator to this requirement
    pub fn add_comparator(&mut self, comparator: Comparator) -> &mut Self {
        self.comparators.push(comparator);
        self
    }

    /// Add a parsed comparator string to this requirement
    pub fn with<S: AsRef<str>>(&mut self, comparator: S) -> Result<&mut Self> {
        let comp = Comparator::parse(comparator.as_ref())?;
        self.comparators.push(comp);
        Ok(self)
    }

    /// Create a new requirement that matches when *any* of its inner
    /// requirements match
    ///
    /// # Examples
    ///
    /// ```
    /// use jayver::{Version, VersionReq};
    ///
    /// let req = VersionReq::any(&[">=25.10.0", "<25.5.0"]).unwrap();
    /// let v1 = Version::parse("25.11.0").unwrap();
    /// let v2 = Version::parse("25.4.0").unwrap();
    ///
    /// assert!(req.matches(&v1)); // Matches >=25.10.0
    /// assert!(req.matches(&v2)); // Matches <25.5.0
    /// ```
    pub fn any<I, S>(requirements: I) -> Result<AnyVersionReq>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut result = Vec::new();

        for req_str in requirements {
            let req = Self::parse(req_str)?;
            result.push(req);
        }

        Ok(AnyVersionReq {
            requirements: result,
        })
    }
}

impl AnyVersionReq {
    /// Create a new empty AnyVersionReq
    pub fn new() -> Self {
        Self {
            requirements: Vec::new(),
        }
    }

    /// Check if a version satisfies any of the requirements
    pub fn matches(&self, version: &Version) -> bool {
        // If no requirements, match any version (like VersionReq)
        if self.requirements.is_empty() {
            return true;
        }

        // Match if ANY requirement matches
        self.requirements.iter().any(|req| req.matches(version))
    }

    /// Add a parsed requirement string to this AnyVersionReq
    pub fn with<S: AsRef<str>>(&mut self, requirement: S) -> Result<&mut Self> {
        let req = VersionReq::parse(requirement.as_ref())?;
        self.requirements.push(req);
        Ok(self)
    }
}

impl Default for VersionReq {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for AnyVersionReq {
    fn default() -> Self {
        Self::new()
    }
}

impl Display for VersionReq {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.comparators.is_empty() {
            return write!(f, "*");
        }

        let mut first = true;
        for comparator in &self.comparators {
            if !first {
                write!(f, ",")?;
            }
            first = false;

            write!(f, "{comparator}")?;
        }

        Ok(())
    }
}

impl Display for AnyVersionReq {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.requirements.is_empty() {
            return write!(f, "*");
        }

        let mut first = true;
        for req in &self.requirements {
            if !first {
                write!(f, " || ")?;
            }
            first = false;

            write!(f, "{req}")?;
        }

        Ok(())
    }
}

impl FromStr for VersionReq {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        Self::parse(s)
    }
}

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

    #[test]
    fn test_op_parse() {
        assert_eq!("=".parse::<Op>().unwrap(), Op::Exact);
        assert_eq!(">".parse::<Op>().unwrap(), Op::Greater);
        assert_eq!(">=".parse::<Op>().unwrap(), Op::GreaterEq);
        assert_eq!("<".parse::<Op>().unwrap(), Op::Less);
        assert_eq!("<=".parse::<Op>().unwrap(), Op::LessEq);
        assert_eq!("~>".parse::<Op>().unwrap(), Op::Compatible);
        assert_eq!("".parse::<Op>().unwrap(), Op::Exact); // Default

        assert!("!!".parse::<Op>().is_err());
    }

    #[test]
    fn test_comparator_parse() {
        let c = Comparator::parse(">=25.10.0").unwrap();
        assert_eq!(c.op, Op::GreaterEq);
        assert_eq!(c.version, Version::parse("25.10.0").unwrap());

        let c = Comparator::parse("25.10.0").unwrap(); // Default to Exact
        assert_eq!(c.op, Op::Exact);
        assert_eq!(c.version, Version::parse("25.10.0").unwrap());

        assert!(Comparator::parse("").is_err());
        assert!(Comparator::parse(">=").is_err());
        assert!(Comparator::parse("!25.10.0").is_err());
    }

    #[test]
    fn test_matches_exact() {
        let version = Version::parse("25.10.1").unwrap();
        let req = VersionReq::parse("=25.10.1").unwrap();
        assert!(req.matches(&version));

        let version2 = Version::parse("25.10.2").unwrap();
        assert!(!req.matches(&version2));
    }

    #[test]
    fn test_matches_greater() {
        let version = Version::parse("25.10.1").unwrap();
        let req = VersionReq::parse(">25.9.0").unwrap();
        assert!(req.matches(&version));

        let req2 = VersionReq::parse(">25.10.1").unwrap();
        assert!(!req2.matches(&version));
    }

    #[test]
    fn test_matches_greater_eq() {
        let version = Version::parse("25.10.1").unwrap();
        let req = VersionReq::parse(">=25.10.1").unwrap();
        assert!(req.matches(&version));

        let req2 = VersionReq::parse(">=25.10.2").unwrap();
        assert!(!req2.matches(&version));
    }

    #[test]
    fn test_matches_less() {
        let version = Version::parse("25.10.1").unwrap();
        let req = VersionReq::parse("<25.11.0").unwrap();
        assert!(req.matches(&version));

        let req2 = VersionReq::parse("<25.10.1").unwrap();
        assert!(!req2.matches(&version));
    }

    #[test]
    fn test_matches_less_eq() {
        let version = Version::parse("25.10.1").unwrap();
        let req = VersionReq::parse("<=25.10.1").unwrap();
        assert!(req.matches(&version));

        let req2 = VersionReq::parse("<=25.10.0").unwrap();
        assert!(!req2.matches(&version));
    }

    #[test]
    fn test_matches_compatible() {
        let version = Version::parse("25.10.1").unwrap();
        let req = VersionReq::parse("~>25.10.0").unwrap();
        assert!(req.matches(&version));

        let version2 = Version::parse("25.10.0").unwrap();
        assert!(req.matches(&version2));

        let version3 = Version::parse("25.11.0").unwrap();
        assert!(!req.matches(&version3));
    }

    #[test]
    fn test_multiple_comparators() {
        let version = Version::parse("25.10.5").unwrap();
        let req = VersionReq::parse(">=25.10.0,<25.11.0").unwrap();
        assert!(req.matches(&version));

        let version2 = Version::parse("25.9.0").unwrap();
        assert!(!req.matches(&version2));

        let version3 = Version::parse("25.11.0").unwrap();
        assert!(!req.matches(&version3));
    }

    #[test]
    fn test_display() {
        let req = VersionReq::parse(">=25.10.0,<25.11.0").unwrap();
        assert_eq!(req.to_string(), ">=25.10.0,<25.11.0");

        let req2 = VersionReq::parse("").unwrap();
        assert_eq!(req2.to_string(), "*");
    }

    #[test]
    fn test_with_method() {
        let mut req = VersionReq::new();
        req.with(">=25.10.0").unwrap().with("<25.11.0").unwrap();

        assert_eq!(req.to_string(), ">=25.10.0,<25.11.0");
    }

    #[test]
    fn test_any() {
        let req = VersionReq::any([">25.15.0", "<25.5.0"]).unwrap();

        let v1 = Version::parse("25.16.0").unwrap();
        let v2 = Version::parse("25.4.0").unwrap();
        let v3 = Version::parse("25.10.0").unwrap();

        assert!(req.matches(&v1)); // > 25.15.0
        assert!(req.matches(&v2)); // < 25.5.0
        assert!(!req.matches(&v3)); // Neither
    }

    #[test]
    fn test_any_display() {
        let req = VersionReq::any([">25.15.0", "<25.5.0"]).unwrap();
        assert_eq!(req.to_string(), ">25.15.0 || <25.5.0");

        // Use a properly typed empty array
        let empty: [&str; 0] = [];
        let req2 = VersionReq::any(empty).unwrap();
        assert_eq!(req2.to_string(), "*");
    }
}