calver 1.1.6

Calver: A lightweight command-line tool for effortless Calendar Versioning increments.
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use chrono::{DateTime, Utc};
use clap::{Error, error::ErrorKind};

/// Default date format used for version generation (YYYY.MM.DD)
pub const DEFAULT_FORMAT: &str = "%Y.%m.%d";

/// Default separator between date and patch number
pub const DEFAULT_SEPARATOR: &str = "-";

/// A version generator that creates date-based versions with incremental patch numbers.
///
/// This struct generates unique version identifiers by combining a formatted date
/// with an incremental patch number. It's particularly useful for automatic build
/// versioning, daily releases, or development snapshots.
///
/// # Examples
///
/// Basic usage:
/// ```
/// use chrono::Utc;
///
/// let version = Version::new(None, None, None);
/// println!("{}", version.generate()); // "2025.09.15-0"
/// ```
///
/// Custom format:
/// ```
/// let version = Version::new(
///     Some("%Y%m%d".to_string()),
///     Some("_v".to_string()),
///     Some(1)
/// );
/// println!("{}", version.generate()); // "20250915_v1"
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Version {
    /// The UTC date/time used for version generation
    pub date: DateTime<Utc>,
    /// Custom date format string (defaults to "%Y.%m.%d")
    pub format: String,
    /// Separator between date and patch number (defaults to "-")
    pub separator: String,
    /// Incremental patch number (starts at 0)
    pub patch: u16,
}

impl Version {
    /// Creates a new Version instance with the current UTC time.
    ///
    /// # Parameters
    ///
    /// - `format`: Optional custom date format string. If None, uses `DEFAULT_FORMAT`
    /// - `separator`: Optional custom separator. If None, uses `DEFAULT_SEPARATOR`
    /// - `patch`: Optional initial patch number. If None, starts at 0
    ///
    /// # Examples
    ///
    /// ```
    /// // Version with default settings
    /// let version = Version::new(None, None, None);
    /// // Generates: "2025.09.15-0"
    ///
    /// // Version with custom format
    /// let version = Version::new(
    ///     Some("%Y%m%d".to_string()),
    ///     Some("_".to_string()),
    ///     Some(5)
    /// );
    /// // Generates: "20250915_5"
    /// ```
    pub fn new(format: Option<String>, separator: Option<String>, patch: Option<u16>) -> Self {
        Version {
            date: Utc::now(),
            format: format.unwrap_or_else(|| DEFAULT_FORMAT.to_string()),
            separator: separator.unwrap_or_else(|| DEFAULT_SEPARATOR.to_string()),
            patch: patch.unwrap_or(0),
        }
    }

    /// Updates the patch number based on the last generated version string.
    ///
    /// This method analyzes the provided last version string and automatically
    /// increments the patch number if the date portion matches the current date.
    /// If the dates don't match or the format is invalid, the patch remains unchanged.
    ///
    /// # Parameters
    ///
    /// - `last`: The last generated version string to analyze
    ///
    /// # Returns
    ///
    /// - `Ok(())` if the operation succeeds
    /// - `Err(Error)` if the patch would exceed `u16::MAX`
    ///
    /// # Logic Flow
    ///
    /// 1. Formats the current date using the configured format
    /// 2. Compares it with the beginning of the `last` string
    /// 3. If dates match, extracts the existing patch number
    /// 4. Increments the patch by 1
    /// 5. Checks for overflow (patch > `u16::MAX`)
    ///
    /// # Examples
    ///
    /// ```
    /// let mut version = Version::new(None, None, None);
    /// // Current date: 2025.09.15
    ///
    /// // Case 1: Same date - patch will be incremented
    /// version.set_patch_from_last("2025.09.15-3")?;
    /// // version.patch becomes 4
    ///
    /// // Case 2: Different date - no change
    /// version.set_patch_from_last("2025.09.14-10")?;
    /// // version.patch remains 0
    ///
    /// // Case 3: Invalid format - no change
    /// version.set_patch_from_last("invalid")?;
    /// // version.patch remains 0
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `ErrorKind::ValueValidation` if the calculated patch number
    /// would exceed `u16::MAX` (65535).
    pub fn set_patch_from_last(&mut self, last: &str) -> Result<(), Error> {
        let formatted_date = self.date.format(&self.format).to_string();

        if last.len() <= formatted_date.len() {
            return Ok(()); // `last` is too short to contain a valid patch
        }

        let last_split = &last[..formatted_date.len()];

        if last_split != formatted_date {
            return Ok(()); // Dates do not match
        }

        let suffix = &last[formatted_date.len()..];

        if let Some(patch_str) = suffix.strip_prefix(&self.separator)
            && let Ok(patch_num) = patch_str.parse::<u16>()
        {
            // Check for overflow before addition
            if patch_num == u16::MAX {
                return Err(Error::raw(
                    ErrorKind::ValueValidation,
                    format!(
                        "The patch calculated exceeds the maximum allowed value ({})",
                        u16::MAX
                    ),
                ));
            }
            self.patch = patch_num + 1;
        }

        Ok(())
    }

    /// Generates the final version string by combining date, separator, and patch.
    ///
    /// The output format is: `{formatted_date}{separator}{patch}`
    ///
    /// # Returns
    ///
    /// A formatted version string
    ///
    /// # Examples
    ///
    /// ```
    /// let version = Version {
    ///     date: /* 2024-03-15 UTC */,
    ///     format: "%Y.%m.%d".to_string(),
    ///     separator: "-".to_string(),
    ///     patch: 5,
    /// };
    ///
    /// let result = version.generate();
    /// // Result: "2025.09.15-5"
    /// ```
    pub fn generate(&self) -> String {
        format!(
            "{}{}{}",
            self.date.format(&self.format),
            self.separator,
            self.patch
        )
    }

    /// Generates the version prefix without the patch number.
    ///
    /// Returns the formatted date followed by the separator, excluding the patch.
    /// Useful for version parsing and date comparison.
    ///
    /// # Returns
    ///
    /// A string in the format: `{formatted_date}{separator}`
    ///
    /// # Examples
    ///
    /// ```
    /// let version = Version {
    ///     date: /* 2025-09-15 UTC */,
    ///     format: "%Y.%m.%d".to_string(),
    ///     separator: "-".to_string(),
    ///     patch: 5,
    /// };
    ///
    /// assert_eq!(version.get_prefix_without_patch(), "2025.09.15-");
    /// ```
    ///
    /// Custom format:
    /// ```
    /// let version = Version {
    ///     date: /* 2025-09-15 UTC */,
    ///     format: "%Y%m%d".to_string(),
    ///     separator: "_v".to_string(),
    ///     patch: 10,
    /// };
    ///
    /// assert_eq!(version.get_prefix_without_patch(), "20250915_v");
    /// ```
    pub fn get_prefix_without_patch(&self) -> String {
        format!("{}{}", self.date.format(&self.format), self.separator)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{TimeZone, Utc};

    // Helper function to create a Version with a fixed date for testing
    fn create_version_with_date(year: i32, month: u32, day: u32) -> Version {
        let mut version = Version::new(None, None, None);
        version.date = Utc.with_ymd_and_hms(year, month, day, 0, 0, 0).unwrap();
        version
    }

    #[test]
    fn test_new_with_all_defaults() {
        let version = Version::new(None, None, None);

        assert_eq!(version.format, DEFAULT_FORMAT);
        assert_eq!(version.separator, DEFAULT_SEPARATOR);
        assert_eq!(version.patch, 0);

        let now = Utc::now();
        let diff = (now - version.date).num_seconds().abs();
        assert!(diff < 2, "Date should be within 2 seconds of now");
    }

    #[test]
    fn test_new_with_custom_format() {
        let custom_format = "%Y-%m-%d %H:%M:%S".to_string();
        let version = Version::new(Some(custom_format.clone()), None, None);

        assert_eq!(version.format, custom_format);
        assert_eq!(version.separator, DEFAULT_SEPARATOR);
        assert_eq!(version.patch, 0);
    }

    #[test]
    fn test_new_with_custom_separator() {
        let custom_separator = "_".to_string();
        let version = Version::new(None, Some(custom_separator.clone()), None);

        assert_eq!(version.format, DEFAULT_FORMAT);
        assert_eq!(version.separator, custom_separator);
        assert_eq!(version.patch, 0);
    }

    #[test]
    fn test_new_with_custom_patch() {
        let patch_number = 42;
        let version = Version::new(None, None, Some(patch_number));

        assert_eq!(version.format, DEFAULT_FORMAT);
        assert_eq!(version.separator, DEFAULT_SEPARATOR);
        assert_eq!(version.patch, patch_number);
    }

    #[test]
    fn test_new_with_all_custom_values() {
        let custom_format = "%Y.%m.%d".to_string();
        let custom_separator = "+".to_string();
        let patch_number = 123;

        let version = Version::new(
            Some(custom_format.clone()),
            Some(custom_separator.clone()),
            Some(patch_number),
        );

        assert_eq!(version.format, custom_format);
        assert_eq!(version.separator, custom_separator);
        assert_eq!(version.patch, patch_number);
    }

    #[test]
    fn test_set_patch_from_last_matching_date_with_patch() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09.15-5";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 6);
    }

    #[test]
    fn test_set_patch_from_last_matching_date_zero_patch() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09.15-0";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 1);
    }

    #[test]
    fn test_set_patch_from_last_different_date() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09.14-5";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 0); // Should remain unchanged
    }

    #[test]
    fn test_set_patch_from_last_no_separator() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09.15";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 0); // Should remain unchanged
    }

    #[test]
    fn test_set_patch_from_last_empty_string() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 0); // Should remain unchanged
    }

    #[test]
    fn test_set_patch_from_last_shorter_than_date() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 0); // Should remain unchanged
    }

    #[test]
    fn test_set_patch_from_last_invalid_patch_number() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09.15-abc";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 0); // Should remain unchanged when parse fails
    }

    #[test]
    fn test_set_patch_from_last_max_patch_overflow() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = format!("2025.09.15-{}", u16::MAX);

        let result = version.set_patch_from_last(&last);

        assert!(result.is_err());
        if let Err(error) = result {
            assert_eq!(error.kind(), ErrorKind::ValueValidation);
            assert!(
                error
                    .to_string()
                    .contains("exceeds the maximum allowed value")
            );
        }
    }

    #[test]
    fn test_set_patch_from_last_near_max_patch() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = format!("2025.09.15-{}", u16::MAX - 1);

        let result = version.set_patch_from_last(&last);

        assert!(result.is_ok());
        assert_eq!(version.patch, u16::MAX);
    }

    #[test]
    fn test_set_patch_from_last_custom_format() {
        let mut version = Version::new(Some("%d/%m/%Y".to_string()), None, None);
        version.date = Utc.with_ymd_and_hms(2025, 9, 15, 0, 0, 0).unwrap();
        let last = "15/09/2025-3";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 4);
    }

    #[test]
    fn test_set_patch_from_last_custom_separator() {
        let mut version = Version::new(None, Some("_".to_string()), None);
        version.date = Utc.with_ymd_and_hms(2025, 9, 15, 0, 0, 0).unwrap();
        let last = "2025.09.15_7";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 8);
    }

    #[test]
    fn test_set_patch_from_last_wrong_separator() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09.15_5"; // Using '_' instead of '-'

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 0); // Should remain unchanged
    }

    #[test]
    fn test_set_patch_from_last_multiple_separators() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09.15-5-extra";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 0); // Should remain unchanged as "5-extra" is not a valid u16
    }

    #[test]
    fn test_set_patch_from_last_negative_patch() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09.15--5";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 0); // Should remain unchanged as "-5" is not a valid u16
    }

    #[test]
    fn test_set_patch_from_last_large_valid_patch() {
        let mut version = create_version_with_date(2025, 9, 15);
        let last = "2025.09.15-1000";

        let result = version.set_patch_from_last(last);

        assert!(result.is_ok());
        assert_eq!(version.patch, 1001);
    }

    #[test]
    fn test_generate_with_defaults() {
        let version = Version::new(None, None, None);
        let generated = version.generate();

        let expected_date_part = version.date.format(DEFAULT_FORMAT).to_string();
        let expected = format!("{}{}{}", expected_date_part, DEFAULT_SEPARATOR, 0);

        assert_eq!(generated, expected);
    }

    #[test]
    fn test_generate_with_custom_values() {
        let custom_format = "%Y%m%d";
        let custom_separator = "_v";
        let patch_number = 5;

        let version = Version::new(
            Some(custom_format.to_string()),
            Some(custom_separator.to_string()),
            Some(patch_number),
        );

        let generated = version.generate();
        let expected_date_part = version.date.format(custom_format).to_string();
        let expected = format!("{}{}{}", expected_date_part, custom_separator, patch_number);

        assert_eq!(generated, expected);
    }

    #[test]
    fn test_generate_with_complex_format() {
        let complex_format = "%Y-%m-%d_%H%M%S";
        let separator = ".patch.";
        let patch_number = 999;

        let version = Version::new(
            Some(complex_format.to_string()),
            Some(separator.to_string()),
            Some(patch_number),
        );

        let generated = version.generate();
        let expected_date_part = version.date.format(complex_format).to_string();
        let expected = format!("{}{}{}", expected_date_part, separator, patch_number);

        assert_eq!(generated, expected);
    }

    #[test]
    fn test_patch_boundary_values() {
        let version_zero = Version::new(None, None, Some(0));
        assert_eq!(version_zero.patch, 0);

        let version_max = Version::new(None, None, Some(u16::MAX));
        assert_eq!(version_max.patch, u16::MAX);
        let generated_max = version_max.generate();
        assert!(generated_max.ends_with(&u16::MAX.to_string()));
    }

    #[test]
    fn test_empty_separator() {
        let version = Version::new(None, Some("".to_string()), Some(42));
        let generated = version.generate();

        let expected_date_part = version.date.format(DEFAULT_FORMAT).to_string();
        let expected = format!("{}{}", expected_date_part, 42);

        assert_eq!(generated, expected);
    }

    #[test]
    fn test_empty_format_string() {
        let version = Version::new(Some("".to_string()), None, Some(1));
        let generated = version.generate();

        let expected = format!("{}{}", DEFAULT_SEPARATOR, 1);
        assert_eq!(generated, expected);
    }

    #[test]
    fn test_version_debug_trait() {
        let version = Version::new(Some("%Y".to_string()), Some("-".to_string()), Some(1));

        let debug_output = format!("{:?}", version);
        assert!(debug_output.contains("Version"));
        assert!(debug_output.contains("date"));
        assert!(debug_output.contains("format"));
        assert!(debug_output.contains("separator"));
        assert!(debug_output.contains("patch"));
    }

    #[test]
    fn test_multiple_versions_have_close_dates() {
        let version1 = Version::new(None, None, None);
        let version2 = Version::new(None, None, None);

        let diff = (version2.date - version1.date).num_milliseconds().abs();
        assert!(
            diff < 100,
            "Versions created consecutively should have very close dates"
        );
    }

    #[test]
    fn test_generate_consistency() {
        let version = Version::new(Some("%Y%m%d".to_string()), Some("-".to_string()), Some(42));

        let result1 = version.generate();
        let result2 = version.generate();
        let result3 = version.generate();

        assert_eq!(result1, result2);
        assert_eq!(result2, result3);
    }

    #[test]
    fn test_get_prefix_without_patch_with_defaults() {
        let version = Version::new(None, None, None);
        let generated = version.get_prefix_without_patch();

        let expected_date_part = version.date.format(DEFAULT_FORMAT).to_string();
        let expected = format!("{}{}", expected_date_part, DEFAULT_SEPARATOR);

        assert_eq!(generated, expected);
    }

    #[test]
    fn test_get_prefix_without_patch_with_custom_values() {
        let version = Version::new(Some("%Y%m%d".to_string()), Some("_v".to_string()), Some(10));
        let generated = version.get_prefix_without_patch();

        let expected_date_part = version.date.format("%Y%m%d").to_string();
        let expected = format!("{}{}", expected_date_part, "_v".to_string());

        assert_eq!(generated, expected);
    }
}