bumpversion 0.0.9

Update all version strings in your project and optionally commit and tag the changes
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
//! Parsing support for Python-style format strings used in version templates.
//!
//! Provides utilities to split format strings into literal text and argument placeholders,
//! and to unescape double curly braces.
pub use parser::ParseError;
use std::collections::HashMap;

/// A segment of a format string: either literal text or a placeholder.
///
/// `Value::String` holds literal content, while `Value::Argument` represents `{name}`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Value {
    /// Literal string content.
    String(String),
    /// Placeholder argument name.
    Argument(String),
}

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::String(s) => write!(f, "{s}"),
            Self::Argument(arg) => write!(f, "{{{arg}}}"),
        }
    }
}

impl Value {
    /// If this is an argument placeholder, return its name, otherwise `None`.
    ///
    /// # Examples
    /// ```
    /// use bumpversion::f_string::Value;
    /// assert_eq!(Value::Argument("x".to_string()).as_argument(), Some("x"));
    /// assert_eq!(Value::String("x".to_string()).as_argument(), None);
    /// ```
    #[must_use]
    pub fn as_argument(&self) -> Option<&str> {
        match self {
            Self::Argument(arg) => Some(arg),
            Self::String(_) => None,
        }
    }

    /// Returns `true` if this value is a placeholder (`Argument`).
    ///
    /// # Examples
    /// ```
    /// use bumpversion::f_string::Value;
    /// assert!(Value::Argument("y".to_string()).is_argument());
    /// assert!(!Value::String("y".to_string()).is_argument());
    /// ```
    #[must_use]
    pub fn is_argument(&self) -> bool {
        matches!(self, Self::Argument(_))
    }
}

impl<'a> From<parser::Value<'a>> for Value {
    fn from(value: parser::Value<'a>) -> Self {
        match value {
            parser::Value::String(s) => Self::String(s.clone()),
            parser::Value::Argument(s) => Self::Argument(s.to_string()),
        }
    }
}

pub mod parser {
    //! Internal module implementing the parser for format strings.
    //!
    //! Users should call `escape_double_curly_braces` or `parse_format_arguments`.
    use winnow::combinator::{alt, delimited, repeat};
    use winnow::error::InputError;
    use winnow::prelude::*;

    use winnow::token::take_while;

    #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
    /// Parsed format string segment.
    pub enum Value<'a> {
        /// Literal string content.
        String(String),
        /// Placeholder argument name.
        Argument(&'a str),
    }

    fn any_except_curly_bracket0<'a>(s: &mut &'a str) -> ModalResult<&'a str, InputError<&'a str>> {
        take_while(0.., |c| c != '{' && c != '}')
            .context("any_except_curly_bracket0")
            .parse_next(s)
    }

    fn any_except_curly_bracket1<'a>(s: &mut &'a str) -> ModalResult<&'a str, InputError<&'a str>> {
        take_while(1.., |c| c != '{' && c != '}')
            .context("any_except_curly_bracket1")
            .parse_next(s)
    }

    fn text_including_escaped_brackets<'a>(
        s: &mut &'a str,
    ) -> ModalResult<String, InputError<&'a str>> {
        repeat(
            1..,
            alt((any_except_curly_bracket1, "{{".value("{"), "}}".value("}"))),
        )
        .fold(String::new, |mut string, c| {
            string.push_str(c);
            string
        })
        .context("text_including_escaped_brackets")
        .parse_next(s)
    }

    fn non_escaped_bracket_argument<'a>(
        s: &mut &'a str,
    ) -> ModalResult<Value<'a>, InputError<&'a str>> {
        delimited("{", any_except_curly_bracket0, "}")
            .map(Value::Argument)
            .context("non_escaped_bracket_argument")
            .parse_next(s)
    }

    fn text_or_argument<'a>(s: &mut &'a str) -> ModalResult<Value<'a>, InputError<&'a str>> {
        alt((
            text_including_escaped_brackets.map(Value::String),
            non_escaped_bracket_argument,
        ))
        .context("text_or_argument")
        .parse_next(s)
    }

    #[derive(thiserror::Error, Debug, PartialEq, Eq)]
    #[error("invalid format: {format_string:?}")]
    /// Parser error for invalid Python-style format strings.
    pub struct ParseError {
        /// The input string that failed to parse.
        pub format_string: String,
    }

    /// Unescape doubled braces (`{{` -> `{`, `}}` -> `}`) in `value`.
    ///
    /// # Errors
    /// Returns `ParseError` if the input is not valid.
    pub fn escape_double_curly_braces(value: &str) -> Result<String, ParseError> {
        let test = text_including_escaped_brackets
            .parse(value)
            .map_err(|_| ParseError {
                format_string: value.to_string(),
            })?;
        Ok(test)
    }

    /// Parse a format string into a sequence of `Value` segments.
    ///
    /// # Examples
    /// ```no_run
    /// use bumpversion::f_string::parser::parse_format_arguments;
    /// let parts = parse_format_arguments("v{major}.{minor}.{patch}")?;
    /// # Ok::<(), bumpversion::f_string::ParseError>(())
    /// ```
    pub fn parse_format_arguments(value: &str) -> Result<Vec<Value<'_>>, ParseError> {
        let test = repeat(0.., text_or_argument)
            .parse(value)
            .map_err(|_| ParseError {
                format_string: value.to_string(),
            })?;
        Ok(test)
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use color_eyre::eyre;
        use similar_asserts::assert_eq as sim_assert_eq;

        #[test]
        fn parses_complex_arguments() -> eyre::Result<()> {
            crate::tests::init();

            sim_assert_eq!(
                parse_format_arguments("this is a {test} value")?,
                vec![
                    Value::String("this is a ".to_string()),
                    Value::Argument("test"),
                    Value::String(" value".to_string()),
                ]
            );

            sim_assert_eq!(
                parse_format_arguments("{jane!s}")?,
                vec![Value::Argument("jane!s")]
            );

            sim_assert_eq!(
                parse_format_arguments("Magic wand: {bag['wand']:^10}")?,
                vec![
                    Value::String("Magic wand: ".to_string()),
                    Value::Argument("bag['wand']:^10"),
                ]
            );
            Ok(())
        }

        #[test]
        fn parses_version_pattern() {
            sim_assert_eq!(
                parse_format_arguments(
                    "{major}.{minor}.{patch}.{dev}{$PR_NUMBER}.dev{distance_to_latest_tag}"
                ),
                Ok(vec![
                    Value::Argument("major"),
                    Value::String(".".to_string()),
                    Value::Argument("minor"),
                    Value::String(".".to_string()),
                    Value::Argument("patch"),
                    Value::String(".".to_string()),
                    Value::Argument("dev"),
                    Value::Argument("$PR_NUMBER"),
                    Value::String(".dev".to_string()),
                    Value::Argument("distance_to_latest_tag"),
                ])
            );
        }

        #[test]
        fn escapes_double_curly_brackets() {
            sim_assert_eq!(
                text_including_escaped_brackets.parse(" hello world"),
                Ok(" hello world".to_string())
            );

            sim_assert_eq!(
                text_including_escaped_brackets.parse(" hello {{ world }}"),
                Ok(" hello { world }".to_string())
            );

            sim_assert_eq!(
                non_escaped_bracket_argument.parse("{test}"),
                Ok(Value::Argument("test"))
            );

            sim_assert_eq!(
                repeat(1.., text_or_argument).parse("this is a {test} for parsing {arguments}"),
                Ok(vec![
                    Value::String("this is a ".to_string()),
                    Value::Argument("test"),
                    Value::String(" for parsing ".to_string()),
                    Value::Argument("arguments"),
                ])
            );

            sim_assert_eq!(
                parse_format_arguments("this }} {{ is a "),
                Ok(vec![Value::String("this } { is a ".to_string())])
            );

            sim_assert_eq!(
                non_escaped_bracket_argument.parse("{}"),
                Ok(Value::Argument(""))
            );

            sim_assert_eq!(
                text_including_escaped_brackets.parse(" hello {{ world }}"),
                Ok(" hello { world }".to_string())
            );

            sim_assert_eq!(
                parse_format_arguments("this }} {{ is a {test}"),
                Ok(vec![
                    Value::String("this } { is a ".to_string()),
                    Value::Argument("test"),
                ])
            );

            sim_assert_eq!(
                parse_format_arguments("this }} {{ is a {test} for parsing {arguments}"),
                Ok(vec![
                    Value::String("this } { is a ".to_string()),
                    Value::Argument("test"),
                    Value::String(" for parsing ".to_string()),
                    Value::Argument("arguments"),
                ])
            );
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A parsed Python-style format string.
///
/// Stores literal and placeholder segments and can be formatted using a map of values.
pub struct PythonFormatString(pub Vec<Value>);

impl std::fmt::Display for PythonFormatString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for value in &self.0 {
            write!(f, "{value}")?;
        }
        Ok(())
    }
}

impl FromIterator<Value> for PythonFormatString {
    fn from_iter<T: IntoIterator<Item = Value>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

impl IntoIterator for PythonFormatString {
    type Item = Value;
    type IntoIter = <Vec<Value> as IntoIterator>::IntoIter;
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a PythonFormatString {
    type Item = &'a Value;
    type IntoIter = std::slice::Iter<'a, Value>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl AsRef<Vec<Value>> for PythonFormatString {
    fn as_ref(&self) -> &Vec<Value> {
        &self.0
    }
}

impl std::str::FromStr for PythonFormatString {
    type Err = parser::ParseError;

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

#[derive(thiserror::Error, Debug, PartialEq, Eq, PartialOrd, Hash)]
#[error("missing argument {0:?}")]
/// Error returned when a required placeholder is missing during formatting.
pub struct MissingArgumentError(String);

impl PythonFormatString {
    /// Parse a Python-style format string.
    pub fn parse(value: &str) -> Result<Self, parser::ParseError> {
        let arguments = parser::parse_format_arguments(value)?;
        Ok(Self(arguments.into_iter().map(Into::into).collect()))
    }

    /// Format this string with the given `values`.
    ///
    /// If `strict` is `true`, missing placeholders result in an error.
    pub fn format<K, V>(
        &self,
        values: &HashMap<K, V>,
        strict: bool,
    ) -> Result<String, MissingArgumentError>
    where
        K: std::borrow::Borrow<str>,
        K: std::hash::Hash + Eq,
        V: AsRef<str>,
    {
        self.0.iter().try_fold(String::new(), |mut acc, value| {
            let value = match value {
                Value::Argument(arg) => {
                    let as_timestamp = || {
                        // try to parse as timestamp of format "utcnow:%Y-%m-%dT%H:%M:%SZ"
                        arg.split_once(':').and_then(|(arg, format)| {
                            values.get(arg).and_then(|value| {
                                let timestamp =
                                    chrono::DateTime::parse_from_rfc3339(value.as_ref()).ok()?;
                                Some(timestamp.format(format).to_string())
                            })
                        })
                    };
                    let value = values
                        .get(arg)
                        .map(|value| value.as_ref().to_string())
                        .or_else(as_timestamp);

                    match value {
                        Some(value) => Ok(value),
                        None if strict => Err(MissingArgumentError(arg.clone())),
                        None => Ok(String::new()),
                    }
                }
                Value::String(s) => Ok(s.clone()),
            }?;
            acc.push_str(&value);
            Ok(acc)
        })
    }

    /// Iterate over all placeholder argument names in this format string.
    pub fn named_arguments(&self) -> impl Iterator<Item = &str> {
        self.0.iter().filter_map(|value| value.as_argument())
    }

    /// Iterate over the parsed [`Value`] segments.
    pub fn iter(&self) -> std::slice::Iter<'_, Value> {
        self.0.iter()
    }
}

#[cfg(test)]
mod tests {
    use super::{PythonFormatString, Value};
    use color_eyre::eyre;
    use similar_asserts::assert_eq as sim_assert_eq;
    use std::collections::HashMap;

    #[test]
    fn parse_f_string_simple() -> eyre::Result<()> {
        crate::tests::init();
        let fstring = PythonFormatString::parse("this is a formatted {value}!")?;
        sim_assert_eq!(
            fstring.as_ref().as_slice(),
            [
                Value::String("this is a formatted ".to_string()),
                Value::Argument("value".to_string()),
                Value::String("!".to_string()),
            ]
        );

        let strict = true;
        sim_assert_eq!(
            fstring
                .format(
                    &[("value", "text"), ("other", "not used")]
                        .into_iter()
                        .collect::<HashMap<&str, &str>>(),
                    strict
                )
                .as_deref(),
            Ok("this is a formatted text!")
        );
        Ok(())
    }

    #[test]
    fn parse_f_string_iter() -> eyre::Result<()> {
        crate::tests::init();
        let fstring = PythonFormatString::parse("this is a formatted {value}!")?;
        sim_assert_eq!(
            fstring.iter().collect::<Vec<_>>(),
            vec![
                &Value::String("this is a formatted ".to_string()),
                &Value::Argument("value".to_string()),
                &Value::String("!".to_string()),
            ]
        );
        Ok(())
    }

    #[test]
    fn parse_f_string_with_dollar_sign_argument() -> eyre::Result<()> {
        crate::tests::init();
        let fstring = PythonFormatString::parse("this is a formatted {$value1}, and {another1}!")?;
        sim_assert_eq!(
            fstring.as_ref().as_slice(),
            [
                Value::String("this is a formatted ".to_string()),
                Value::Argument("$value1".to_string()),
                Value::String(", and ".to_string()),
                Value::Argument("another1".to_string()),
                Value::String("!".to_string()),
            ]
        );

        let strict = true;
        sim_assert_eq!(
            fstring
                .format(
                    &[
                        ("$value1", "text"),
                        ("another1", "more"),
                        ("other", "unused")
                    ]
                    .into_iter()
                    .collect::<HashMap<&str, &str>>(),
                    strict
                )
                .as_deref(),
            Ok("this is a formatted text, and more!")
        );
        Ok(())
    }

    #[test]
    fn parse_f_string_with_missing_argument() -> eyre::Result<()> {
        crate::tests::init();
        let fstring = PythonFormatString::parse("this is a formatted {$value1}, and {another1}!")?;
        sim_assert_eq!(
            fstring.as_ref().as_slice(),
            [
                Value::String("this is a formatted ".to_string()),
                Value::Argument("$value1".to_string()),
                Value::String(", and ".to_string()),
                Value::Argument("another1".to_string()),
                Value::String("!".to_string()),
            ]
        );

        let strict = false;
        sim_assert_eq!(
            fstring
                .format(
                    &[
                        // ("$value1", "text"), // missing
                        ("another1", "more"),
                        ("other", "unused")
                    ]
                    .into_iter()
                    .collect::<HashMap<&str, &str>>(),
                    strict
                )
                .as_deref(),
            Ok("this is a formatted , and more!")
        );
        Ok(())
    }

    #[test]
    fn parse_f_string_with_missing_argument_strict() -> eyre::Result<()> {
        crate::tests::init();
        let fstring = PythonFormatString::parse("this is a formatted {$value1}, and {another1}!")?;
        sim_assert_eq!(
            fstring.as_ref().as_slice(),
            [
                Value::String("this is a formatted ".to_string()),
                Value::Argument("$value1".to_string()),
                Value::String(", and ".to_string()),
                Value::Argument("another1".to_string()),
                Value::String("!".to_string()),
            ]
        );

        let strict = true;
        sim_assert_eq!(
            fstring.format(
                &[
                    // ("$value1", "text"), // missing
                    ("another1", "more"),
                    ("other", "unused")
                ]
                .into_iter()
                .collect::<HashMap<&str, &str>>(),
                strict
            ),
            Err(super::MissingArgumentError("$value1".to_string())),
        );
        Ok(())
    }

    #[test]
    fn f_string_display() -> eyre::Result<()> {
        crate::tests::init();
        let raw_fstring = "this is a formatted {$value1}, and {another1}!";
        let fstring = PythonFormatString::parse(raw_fstring)?;
        sim_assert_eq!(&fstring.to_string(), raw_fstring);
        Ok(())
    }
}