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 612 613 614 615 616 617 618 619 620 621 622
#![warn(missing_docs)] /*! Lenient parser for Semantic Version numbers. ## Motivation This crate aims to provide an alternative parser for [semver `Version`s](https://crates.io/crates/semver). Instead of adhering to the semver specification, this parser is more lenient in what it allows. The differenc include: - Minor and Path are optional an default to 0 (e.g. "1" parses as "1.0.0") - Pre-release identifier may be separated by `.` as well (e.g. "1.2.3.rc1" parses as "1.2.3-rc1") - Some pre-release identifiers are parsed as build identifier (e.g. "1.2.3.Final" parses as "1.2.3+Final") - Additional numeric identifiers are parsed as build identifier (e.g "1.2.3.4.5" parses as "1.2.3+4.5") - A leading `v` or `V` is allowed (e.g. "v1.2.3" parses as "1.2.3") - Numbers that overflow an u64 are treated as strings (e.g. "1.2.3-9876543210987654321098765432109876543210" parses without error) This diagram shows lenient parsing grammar ![have a look at doc/railroad.svg](https://knutwalker.s3.eu-central-1.amazonaws.com/lenient-semver/doc/railroad.svg) ## Examples ```rust # use semver_v100 as semver; use semver::Version; let version = lenient_semver::parse("1.2.3"); assert_eq!(version, Ok(Version::new(1, 2, 3))); // examples of a version that would not be accepted by semver_parser assert_eq!( lenient_semver::parse("1.2.M1").unwrap(), Version::parse("1.2.0-M1").unwrap() ); assert!(Version::parse("1.2.M1").is_err()); assert_eq!( lenient_semver::parse("1").unwrap(), Version::parse("1.0.0").unwrap() ); assert!(Version::parse("1").is_err()); assert_eq!( lenient_semver::parse("1.2.3.Final").unwrap(), Version::parse("1.2.3+Final").unwrap() ); assert!(Version::parse("1.2.3.Final").is_err()); assert_eq!( lenient_semver::parse("1.2.3.4.5").unwrap(), Version::parse("1.2.3+4.5").unwrap() ); assert!(Version::parse("1.2.3.4.5").is_err()); assert_eq!( lenient_semver::parse("v1.2.3").unwrap(), Version::parse("1.2.3").unwrap() ); assert!(Version::parse("v1.2.3").is_err()); assert_eq!( lenient_semver::parse("1.2.9876543210987654321098765432109876543210").unwrap(), Version::parse("1.2.0-9876543210987654321098765432109876543210").unwrap() ); assert!(Version::parse("1.2.9876543210987654321098765432109876543210").is_err()); ``` ## Parsing into custom versions The parser is not fixed on returning a `semver::Version`, it instead parses into a `lenient_semver::VersionBuilder`. The default features for this crate contain a `VersionBuilder` implementation for `semver::Version`, but any implementation can be used with `parse_into`. ### Examples ```rust # // This example is replicated in the tests module # // Please try to keep them in sync use lenient_semver::VersionBuilder; /// Simpler version struct that lives only on the stack #[derive(Debug, Default)] struct MyVersion { numbers: [u64; 3], is_pre_release: bool, } /// The VersionBuilder trait is generic over the lifetime of the input string. /// We don't store references to those strings, so we don't care about the specific lifetime. impl VersionBuilder<'_> for MyVersion { /// We will modify the target struct directly type Out = Self; /// Construct a new builder instance. /// One can only expect `set_major` to be called before `build`, all other methods are optional. fn new() -> Self { Self::default() } /// Construct the final result. In this case, we can just return ourselves. fn build(self) -> Self::Out { self } /// Called when the major component was found. fn set_major(&mut self, major: u64) { self.numbers[0] = major; } /// Called when the minor component was found. fn set_minor(&mut self, minor: u64) { self.numbers[1] = minor; } /// Called when the patch component was found. fn set_patch(&mut self, patch: u64) { self.numbers[2] = patch; } /// Called when any pre-relase metadata identifier was found. /// This identifier can just numeric, no attempts at parsing it into a number have been made. /// For this implementation, we don't care about the value, just it's presence. fn add_pre_release(&mut self, _pre_release: &str) { self.is_pre_release = true } } let input = "1.3.3.7-alpha21+build.42"; let my_version = lenient_semver::parse_into::<MyVersion>(input).unwrap(); assert_eq!([1, 3, 3], my_version.numbers); assert!(my_version.is_pre_release); ``` The VersionBuilder has empty default implementation for the various methods, making it easy to use it for use-cases beyond just parsing. The following example implements a function that checks if a given string represents any form of pre-release version. ```rust # // This example is replicated in the tests module # // Please try to keep them in sync use lenient_semver::VersionBuilder; /// newtype around bool, so we can implement the VersionBuilder trait for it #[derive(Debug, Default)] struct IsPreRelease(bool); impl VersionBuilder<'_> for IsPreRelease { /// Here we parse into a different value than Self type Out = bool; fn new() -> Self { Self::default() } /// Return the wrapped bool fn build(self) -> Self::Out { self.0 } /// We only care about this method and can ignore all the other ones fn add_pre_release(&mut self, _pre_release: &str) { self.0 = true; } } /// This method also return false for invalid version strings, /// which is technically true, as those are not pre-release versions. /// Usually you would want to have a better error handling. fn is_pre_release(v: &str) -> bool { lenient_semver::parse_into::<IsPreRelease>(v).unwrap_or_default() } assert!(is_pre_release("1.2.3-pre") == true); assert!(is_pre_release("1.2.3") == false); assert!(is_pre_release("1.2.3+build") == false); ``` ## Features `lenient_semver` comes with a number of features: | feature name | default enabled | transitive dependencies | purpose | -------------: | --------------- | ----------------------- | -------- | semver | **yes** | `semver = "1"` | Provides `VersionBuilder` implementation for `semver = "1"`. | semver011 | no | `semver = "0.11"` | Provides `VersionBuilder` implementation for `semver = "0.11"`. | semver010 | no | `semver = "0.10"` | Provides `VersionBuilder` implementation for `semver = "0.10"`. | parse_partial | no | | Provides `parse_partial` method for partially parsing a version from the beginning of a string. | version_lite | no | `lenient_version = "*"` | A custom Version as alternative to `semver::Version` that complements some leneient features, such as additional numbers beyond patch. | version_semver | no | `lenient_version = "*"` | Add conversions From `lenient_version` Into `semver::Version`. | version_serde | no | `serde = "1"` | Serde Deserializer and Serializer implementation for `lenient_version`. ### Examples #### `semver` ```toml lenient_semver = { version = "*", features = [ "semver" ] } ``` ```rust # #[cfg(not(feature = "semver"))] # compile_error!("Please run doc tests with --all-features"); # use semver_v100 as semver; use semver::Version; // This features is enabled by default and is usable through `parse` directly. let version = lenient_semver::parse("v1.2.3.Final").unwrap(); assert_eq!(version, Version::parse("1.2.3+Final").unwrap()); // It can also be used with `parse_into`. let version = lenient_semver::parse_into::<Version>("v1.2.3.Final").unwrap(); assert_eq!(version, Version::parse("1.2.3+Final").unwrap()); ``` #### `semver011` ```toml lenient_semver = { version = "*", features = [ "semver011" ] } ``` ```rust # #[cfg(not(feature = "semver011"))] # compile_error!("Please run doc tests with --all-features"); # use semver_v011 as semver; // Rename is just for demonstration and not required use semver::Version as Version011; // The default parse is fixed to the latest semver::Version, // so we need to use `parse_into`. let version = lenient_semver::parse_into::<Version011>("v1.2.3.Final").unwrap(); assert_eq!(version, Version011::parse("1.2.3+Final").unwrap()); ``` #### `semver010` ```toml lenient_semver = { version = "*", features = [ "semver010" ] } ``` ```rust # #[cfg(not(feature = "semver010"))] # compile_error!("Please run doc tests with --all-features"); # use semver_v010 as semver; // Rename is just for demonstration and not required use semver::Version as Version010; // The default parse is fixed to the latest semver::Version, // so we need to use `parse_into`. let version = lenient_semver::parse_into::<Version010>("v1.2.3.Final").unwrap(); assert_eq!(version, Version010::parse("1.2.3+Final").unwrap()); ``` #### `version_lite` ```toml lenient_semver = { version = "*", features = [ "version_lite" ] } ``` With this features, lenient_semver now comes with it's own version. That particular implementation supports numbers beyond patch directly. Note that lenient_semver still parses those additional number without complaining, but they are added as build attribute to semver Versions. ```rust # #[cfg(not(feature = "version_lite"))] # compile_error!("Please run doc tests with --all-features"); use lenient_semver::Version; let version = lenient_semver::parse_into::<Version>("1.3.3.7").unwrap(); assert_eq!(version, Version::parse("1.3.3.7").unwrap()); // Version::parse delegates to this parser ``` The native support allows such version to be compared properly, which does not work with semver. ```rust # #[cfg(not(all(feature = "version_lite", feature = "semver011")))] # compile_error!("Please run doc tests with --all-features"); # use semver_v011 as semver; use lenient_semver::Version; let version_a = Version::parse("1.3.3.7").unwrap(); let version_b = Version::parse("1.3.3.8").unwrap(); assert!(version_a < version_b); // with semver pre 1.0, that fails: let version_a = lenient_semver::parse_into::<semver::Version>("1.3.3.7").unwrap(); let version_b = lenient_semver::parse_into::<semver::Version>("1.3.3.8").unwrap(); assert_eq!(version_a < version_b, false); assert_eq!(version_a, version_b); ``` Furthermore, `Version` does not own the data for the metadata identifiers. The metadata can be disassociated, so the version can reference a different owner. ```rust # // This example is replicated in the tests module # // Please try to keep them in sync # #[cfg(not(feature = "version_lite"))] # compile_error!("Please run doc tests with --all-features"); use lenient_semver::{Version, VersionBuilder}; let input = "1.3.3.7-beta.21+build.42"; // make an owned copy, so we don't cheat by using the 'static lifetime. let input = String::from(input); // This version references slices from the `input` String let version = lenient_semver::parse_into::<Version>(input.as_ref()).unwrap(); // Which prevents us from dropping the input // drop(input); // We can disassociate the metadata, which allows the new version to reference something else let (mut version, pre, build) = version.disassociate_metadata(); // We still get the referenced input slices, so we create owned copies let pre: Option<String> = pre.map(ToOwned::to_owned); let build: Option<String> = build.map(ToOwned::to_owned); // now we can safely drop the input drop(input); // We can also re-add the cloned identifiers. // The version would now be bound to the lifetime of this method. // Just for fun, we swap pre-release and build if let Some(pre) = pre.as_deref() { version.add_build(pre); } if let Some(build) = build.as_deref() { version.add_pre_release(build); } assert_eq!("1.3.3.7-build.42+beta.21".to_string(), version.to_string()); ``` #### `version_semver` ```toml lenient_semver = { version = "*", features = [ "version_semver" ] } ``` If you need to store an owned copy of the version information, you should copy into `semver::Version` or your custom version type instead. If you only ever intend to store the version information, it might make more sense to parse directly into `semver::Version` instead. ```rust # #[cfg(all(not(feature = "version_lite"), not(feature = "version_semver")))] # compile_error!("Please run doc tests with --all-features"); # use semver_v100 as semver; use semver::Version; let input = String::from("v1.3.3.7-beta-21+build-42"); let version = lenient_semver::Version::parse(&input).unwrap(); let version = Version::from(version); assert_eq!("1.3.3-beta-21+7.build-42", &version.to_string()); ``` #### `version_serde` ```toml lenient_semver = { version = "*", features = [ "version_serde" ] } ``` This feature also enabled `version_lite` and brings serde support for the own Version type. Since `lenient_semver::Version` does not take ownership of the metadata identifiers, the lifetime of the deserialization result is bound to the input. ```rust # // This example is replicated in the tests module # // Please try to keep them in sync # #[cfg(any(not(feature = "version_lite"), not(feature = "version_serde")))] # compile_error!("Please run doc tests with --all-features"); use lenient_semver::{Version, VersionBuilder}; use serde::Deserialize; #[derive(Debug, Deserialize)] struct DependencySpec<'input> { /// Refer to name as owned value name: String, /// Borrows from the input string #[serde(borrow)] version: Version<'input>, } let input = " { \"name\": \"lenient_semver\", \"version\": \"1.3.3.7+build.42\" }"; // make an owned copy, so we don't cheat by using the 'static lifetime. let input = String::from(input); // use serde as one would normally do let dep: DependencySpec = serde_json::from_str(input.as_ref()).unwrap(); // cannot move out of `input` because it is borrowed // drop(input); let mut expected = Version::new(1, 3, 3); expected.add_additional(7); expected.add_build("build.42"); assert_eq!(dep.version, expected); // now we can drop the input drop(input); ``` #### `parse_partial` ```toml lenient_semver = { version = "*", features = [ "parse_partial" ] } ``` This feature enables the `partial` feature of the parser. The partial parser will not try to consume all input. Instead it parses the version as far as possible and will return the unconsumed input alongside the parsed version. ```rust # // This example is replicated in the tests module # // Please try to keep them in sync # #[cfg(not(feature = "parse_partial"))] # compile_error!("Please run doc tests with --all-features"); use lenient_semver::{Version, VersionBuilder, parser}; let input = "1.2.3 42+build 1.3.3.7 // end"; // parse first version let (version, remainder) = parser::parse_partial::<Version>(input).unwrap(); let expected = Version::new(1, 2, 3); assert_eq!(version, expected); // trailing whitespace is considered part of a version and consumed as well assert_eq!("42+build 1.3.3.7 // end", remainder); // parse second version let (version, remainder) = parser::parse_partial::<Version>(remainder).unwrap(); let mut expected = Version::new(42, 0, 0); expected.add_build("build"); assert_eq!(version, expected); assert_eq!("1.3.3.7 // end", remainder); // parse last version let (version, remainder) = parser::parse_partial::<Version>(remainder).unwrap(); let mut expected = Version::new(1, 3, 3); expected.add_additional(7); assert_eq!(version, expected); assert_eq!("// end", remainder); // parse partial still expects to parse something. // It will fail with `UnexpectedInput` or `MissingMajorNumber` if the input does not match at least a major version. // let's try to parse the remaining input let error = parser::parse_partial::<Version>(remainder).unwrap_err(); assert_eq!(error.error_kind(), parser::ErrorKind::UnexpectedInput); assert_eq!(error.error_line(), "Unexpected `/`"); // or an empty string let error = parser::parse_partial::<Version>(" ").unwrap_err(); assert_eq!(error.error_kind(), parser::ErrorKind::MissingMajorNumber); assert_eq!( error.error_line(), "Could not parse the major identifier: No input" ); // The rules of when a certain number will be parsed are even more relaxed let (version, remainder) = parser::parse_partial::<Version>("1foobar").unwrap(); let expected = Version::new(1, 0, 0); assert_eq!(version, expected); assert_eq!(remainder, "foobar"); // Furthermore, the characters `*` and `?` are allowed to appear everywhere where other alphabetic character are allowed. // This relaxes the rule that only a-z, A-Z, and 0-9 are allowed. // Those characters have no special meaning and will be parsed as pre-release or build segment. let (version, remainder) = parser::parse_partial::<Version>("1.2.*+final?").unwrap(); let mut expected = Version::new(1, 2, 0); expected.add_pre_release("*"); expected.add_build("final?"); assert_eq!(version, expected); assert_eq!(remainder, ""); ``` */ pub use lenient_semver_parser::{self as parser, VersionBuilder}; #[cfg(feature = "version_lite")] pub use lenient_version::{Version, Version as VersionLite}; /// Parse a string slice into a Version. /// /// This parser does not require semver-specification conformant input and is more lenient in what it allows. /// The differenc include: /// /// - Minor and Path are optional an default to 0 (e.g. "1" parses as "1.0.0") /// - Pre-release identifier may be separated by `.` as well (e.g. "1.2.3.rc1" parses as "1.2.3-rc1") /// - Some pre-release identifiers are parsed as build identifier (e.g. "1.2.3.Final" parses as "1.2.3+Final") /// - Additional numeric identifiers are parsed as build identifier (e.g "1.2.3.4.5" parses as "1.2.3+4.5") /// - A leading `v` or `V` is allowed (e.g. "v1.2.3" parses as "1.2.3") /// - Numbers that overflow an u64 are treated as strings (e.g. "1.2.3-9876543210987654321098765432109876543210" parses without error) /// /// This diagram shows lenient parsing grammar /// /// ![have a look at doc/railroad.svg](https://knutwalker.s3.eu-central-1.amazonaws.com/lenient-semver/doc/railroad.svg) /// /// ## Examples /// /// ```rust /// # use semver_v100 as semver;; /// use semver::Version; /// /// let version = lenient_semver::parse("1.2.3"); /// assert_eq!(version, Ok(Version::new(1, 2, 3))); /// /// // examples of a version that would not be accepted by semver_parser /// assert_eq!( /// lenient_semver::parse("1.2.M1").unwrap(), /// Version::parse("1.2.0-M1").unwrap() /// ); /// assert!(Version::parse("1.2.M1").is_err()); /// /// assert_eq!( /// lenient_semver::parse("1").unwrap(), /// Version::parse("1.0.0").unwrap() /// ); /// assert!(Version::parse("1").is_err()); /// /// assert_eq!( /// lenient_semver::parse("1.2.3.Final").unwrap(), /// Version::parse("1.2.3+Final").unwrap() /// ); /// assert!(Version::parse("1.2.3.Final").is_err()); /// /// assert_eq!( /// lenient_semver::parse("1.2.3.4.5").unwrap(), /// Version::parse("1.2.3+4.5").unwrap() /// ); /// assert!(Version::parse("1.2.3.4.5").is_err()); /// /// assert_eq!( /// lenient_semver::parse("v1.2.3").unwrap(), /// Version::parse("1.2.3").unwrap() /// ); /// assert!(Version::parse("v1.2.3").is_err()); /// /// assert_eq!( /// lenient_semver::parse("1.2.9876543210987654321098765432109876543210").unwrap(), /// Version::parse("1.2.0-9876543210987654321098765432109876543210").unwrap() /// ); /// assert!(Version::parse("1.2.9876543210987654321098765432109876543210").is_err()); /// ``` /// /// This method is fixed to return a [`semver_v100::Version`]. /// A more flexible variant is [`parse_into`]. #[cfg(feature = "semver")] pub fn parse(input: &str) -> Result<semver_v100::Version, parser::Error> { parser::parse::<semver_v100::Version>(input) } /// Parse a string slice into a Version. /// /// This parser does not require semver-specification conformant input and is more lenient in what it allows. /// The differenc include: /// /// - Minor and Path are optional an default to 0 (e.g. "1" parses as "1.0.0") /// - Pre-release identifier may be separated by `.` as well (e.g. "1.2.3.rc1" parses as "1.2.3-rc1") /// - Some pre-release identifiers are parsed as build identifier (e.g. "1.2.3.Final" parses as "1.2.3+Final") /// - Additional numeric identifiers are parsed as build identifier (e.g "1.2.3.4.5" parses as "1.2.3+4.5") /// - A leading `v` or `V` is allowed (e.g. "v1.2.3" parses as "1.2.3") /// - Numbers that overflow an u64 are treated as strings (e.g. "1.2.3-9876543210987654321098765432109876543210" parses without error) /// /// This diagram shows lenient parsing grammar /// /// ![have a look at doc/railroad.svg](https://knutwalker.s3.eu-central-1.amazonaws.com/lenient-semver/doc/railroad.svg) /// /// This method can parse anything that implements [`VersionBuilder`]. /// /// ## Examples /// /// ```rust /// use lenient_semver::Version; /// /// let version = lenient_semver::parse_into::<Version>("1.2.3"); /// assert_eq!(version, Ok(Version::new(1, 2, 3))); /// /// // examples of a version that would not be accepted by semver_parser /// assert_eq!( /// lenient_semver::parse_into::<Version>("1.2.M1").unwrap(), /// Version::parse("1.2.0-M1").unwrap() /// ); /// /// assert_eq!( /// lenient_semver::parse_into::<Version>("1").unwrap(), /// Version::parse("1.0.0").unwrap() /// ); /// /// assert_eq!( /// lenient_semver::parse_into::<Version>("1.2.3.Final").unwrap(), /// Version::parse("1.2.3+Final").unwrap() /// ); /// /// assert_eq!( /// lenient_semver::parse_into::<Version>("1.2.3.4.5").unwrap(), /// Version::parse("1.2.3.4.5").unwrap() /// ); /// /// assert_eq!( /// lenient_semver::parse_into::<Version>("v1.2.3").unwrap(), /// Version::parse("1.2.3").unwrap() /// ); /// /// assert_eq!( /// lenient_semver::parse_into::<Version>("1.2.9876543210987654321098765432109876543210").unwrap(), /// Version::parse("1.2.0-9876543210987654321098765432109876543210").unwrap() /// ); /// ``` pub fn parse_into<'input, V>(input: &'input str) -> Result<V::Out, parser::Error<'input>> where V: VersionBuilder<'input>, { parser::parse::<V>(input) } #[cfg(test)] mod tests;