semver-parser-0.9.0/.gitignore000064400000000000000000000000271320607376700145030ustar0000000000000000target Cargo.lock *.bk semver-parser-0.9.0/.travis.yml000064400000000000000000000012111331176664300146170ustar0000000000000000language: rust cache: cargo # this is a long way of saying, "please test 1.22.1, stable, beta, and nightly, but run rustfmt only on stable" matrix: include: - rust: "1.22.1" env: RUN_RUSTFMT=false - rust: "stable" env: RUN_RUSTFMT=true - rust: "beta" env: RUN_RUSTFMT=false - rust: "nightly" env: RUN_RUSTFMT=false allow_failures: # bugs may affect nightly; test so we're aware, but don't fail the build - rust: nightly before_script: - if [ "${RUN_RUSTFMT}" = "true" ]; then rustup component add rustfmt-preview; fi script: - cargo test - if [ "${RUN_RUSTFMT}" = "true" ]; then cargo fmt -- --check; fi semver-parser-0.9.0/Cargo.toml.orig000064400000000000000000000011001331176761600153730ustar0000000000000000[package] name = "semver-parser" version = "0.9.0" # remember to update html_root_url authors = ["Steve Klabnik "] license = "MIT/Apache-2.0" repository = "https://github.com/steveklabnik/semver-parser" homepage = "https://github.com/steveklabnik/semver-parser" documentation = "https://docs.rs/semver-parser" description = """ Parsing of the semver spec. """ keywords = ["parser", "semver", "version", "semantic"] categories = ["Development tools", "Parsing"] readme = "README.md" [badges] travis-ci = { repository = "steveklabnik/semver-parser" } semver-parser-0.9.0/Cargo.toml0000644000000020340000000000000116710ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "semver-parser" version = "0.9.0" authors = ["Steve Klabnik "] description = "Parsing of the semver spec.\n" homepage = "https://github.com/steveklabnik/semver-parser" documentation = "https://docs.rs/semver-parser" readme = "README.md" keywords = ["parser", "semver", "version", "semantic"] categories = ["Development tools", "Parsing"] license = "MIT/Apache-2.0" repository = "https://github.com/steveklabnik/semver-parser" [badges.travis-ci] repository = "steveklabnik/semver-parser" semver-parser-0.9.0/LICENSE-APACHE000064400000000000000000000251371306650563700144500ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. semver-parser-0.9.0/LICENSE-MIT000064400000000000000000000020411306650563700141450ustar0000000000000000Copyright (c) 2016 Steve Klabnik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. semver-parser-0.9.0/README.md000064400000000000000000000001201331176760200137570ustar0000000000000000# `semver-parser` Parsing for the semver spec. We'll have better docs at 1.0. semver-parser-0.9.0/src/comparator.rs000064400000000000000000000004601331176263500160140ustar0000000000000000use range::VersionReq; /// A single range set combining a number of ranges with an or (`||`). /// /// If any range in this set matches, the whole set matches. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub struct Comparator { /// Set of ranges. pub ranges: Vec, } semver-parser-0.9.0/src/lexer.rs000064400000000000000000000204441331176664300147730ustar0000000000000000//! Lexer for semver ranges. //! //! Breaks a string of input into an iterator of tokens that can be used with a parser. //! //! This should be used with the [`parser`] module. //! //! [`parser`]: ../parser/index.html //! //! # Examples //! //! Example without errors: //! //! ```rust //! use semver_parser::lexer::{Lexer, Token}; //! //! let mut l = Lexer::new("foo 123 *"); //! //! assert_eq!(Some(Ok(Token::AlphaNumeric("foo"))), l.next()); //! assert_eq!(Some(Ok(Token::Whitespace(3, 4))), l.next()); //! assert_eq!(Some(Ok(Token::Numeric(123))), l.next()); //! assert_eq!(Some(Ok(Token::Whitespace(7, 8))), l.next()); //! assert_eq!(Some(Ok(Token::Star)), l.next()); //! assert_eq!(None, l.next()); //! ``` //! //! Example with error: //! //! ```rust //! use semver_parser::lexer::{Lexer, Token, Error}; //! //! let mut l = Lexer::new("foo / *"); //! //! assert_eq!(Some(Ok(Token::AlphaNumeric("foo"))), l.next()); //! assert_eq!(Some(Ok(Token::Whitespace(3, 4))), l.next()); //! assert_eq!(Some(Err(Error::UnexpectedChar('/'))), l.next()); //! ``` use self::Error::*; use self::Token::*; use std::str; macro_rules! scan_while { ($slf:expr, $start:expr, $first:pat $(| $rest:pat)*) => {{ let mut __end = $start; loop { if let Some((idx, c)) = $slf.one() { __end = idx; match c { $first $(| $rest)* => $slf.step(), _ => break, } continue; } else { __end = $slf.input.len(); } break; } __end }} } /// Semver tokens. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Token<'input> { /// `=` Eq, /// `>` Gt, /// `<` Lt, /// `<=` LtEq, /// `>=` GtEq, /// '^` Caret, /// '~` Tilde, /// '*` Star, /// `.` Dot, /// `,` Comma, /// `-` Hyphen, /// `+` Plus, /// '||' Or, /// any number of whitespace (`\t\r\n `) and its span. Whitespace(usize, usize), /// Numeric component, like `0` or `42`. Numeric(u64), /// Alphanumeric component, like `alpha1` or `79deadbe`. AlphaNumeric(&'input str), } impl<'input> Token<'input> { /// Check if the current token is a whitespace token. pub fn is_whitespace(&self) -> bool { match *self { Whitespace(..) => true, _ => false, } } /// Check if the current token is a wildcard token. pub fn is_wildcard(&self) -> bool { match *self { Star | AlphaNumeric("X") | AlphaNumeric("x") => true, _ => false, } } } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Error { /// Unexpected character. UnexpectedChar(char), } /// Lexer for semver tokens belonging to a range. #[derive(Debug)] pub struct Lexer<'input> { input: &'input str, chars: str::CharIndices<'input>, // lookahead c1: Option<(usize, char)>, c2: Option<(usize, char)>, } impl<'input> Lexer<'input> { /// Construct a new lexer for the given input. pub fn new(input: &str) -> Lexer { let mut chars = input.char_indices(); let c1 = chars.next(); let c2 = chars.next(); Lexer { input: input, chars: chars, c1: c1, c2: c2, } } /// Shift all lookahead storage by one. fn step(&mut self) { self.c1 = self.c2; self.c2 = self.chars.next(); } fn step_n(&mut self, n: usize) { for _ in 0..n { self.step(); } } /// Access the one character, or set it if it is not set. fn one(&mut self) -> Option<(usize, char)> { self.c1 } /// Access two characters. fn two(&mut self) -> Option<(usize, char, char)> { self.c1 .and_then(|(start, c1)| self.c2.map(|(_, c2)| (start, c1, c2))) } /// Consume a component. /// /// A component can either be an alphanumeric or numeric. /// Does not permit leading zeroes if numeric. fn component(&mut self, start: usize) -> Result, Error> { let end = scan_while!(self, start, '0'...'9' | 'A'...'Z' | 'a'...'z'); let input = &self.input[start..end]; let mut it = input.chars(); let (a, b) = (it.next(), it.next()); // exactly zero if a == Some('0') && b.is_none() { return Ok(Numeric(0)); } if a != Some('0') { if let Ok(numeric) = input.parse::() { return Ok(Numeric(numeric)); } } Ok(AlphaNumeric(input)) } /// Consume whitespace. fn whitespace(&mut self, start: usize) -> Result, Error> { let end = scan_while!(self, start, ' ' | '\t' | '\n' | '\r'); Ok(Whitespace(start, end)) } } impl<'input> Iterator for Lexer<'input> { type Item = Result, Error>; fn next(&mut self) -> Option { loop { // two subsequent char tokens. if let Some((_, a, b)) = self.two() { let two = match (a, b) { ('<', '=') => Some(LtEq), ('>', '=') => Some(GtEq), ('|', '|') => Some(Or), _ => None, }; if let Some(two) = two { self.step_n(2); return Some(Ok(two)); } } // single char and start of numeric tokens. if let Some((start, c)) = self.one() { let tok = match c { ' ' | '\t' | '\n' | '\r' => { self.step(); return Some(self.whitespace(start)); } '=' => Eq, '>' => Gt, '<' => Lt, '^' => Caret, '~' => Tilde, '*' => Star, '.' => Dot, ',' => Comma, '-' => Hyphen, '+' => Plus, '0'...'9' | 'a'...'z' | 'A'...'Z' => { self.step(); return Some(self.component(start)); } c => return Some(Err(UnexpectedChar(c))), }; self.step(); return Some(Ok(tok)); }; return None; } } } #[cfg(test)] mod tests { use super::*; fn lex(input: &str) -> Vec { Lexer::new(input).map(Result::unwrap).collect::>() } #[test] pub fn simple_tokens() { assert_eq!( lex("=><<=>=^~*.,-+||"), vec![ Eq, Gt, Lt, LtEq, GtEq, Caret, Tilde, Star, Dot, Comma, Hyphen, Plus, Or ] ); } #[test] pub fn whitespace() { assert_eq!( lex(" foo \t\n\rbar"), vec![ Whitespace(0, 2), AlphaNumeric("foo"), Whitespace(5, 9), AlphaNumeric("bar"), ] ); } #[test] pub fn components() { assert_eq!(lex("42"), vec![Numeric(42)]); assert_eq!(lex("0"), vec![Numeric(0)]); assert_eq!(lex("01"), vec![AlphaNumeric("01")]); assert_eq!(lex("01"), vec![AlphaNumeric("01")]); assert_eq!(lex("5885644aa"), vec![AlphaNumeric("5885644aa")]); assert_eq!(lex("beta2"), vec![AlphaNumeric("beta2")]); assert_eq!(lex("beta.2"), vec![AlphaNumeric("beta"), Dot, Numeric(2)]); } #[test] pub fn is_wildcard() { assert_eq!(Star.is_wildcard(), true); assert_eq!(AlphaNumeric("x").is_wildcard(), true); assert_eq!(AlphaNumeric("X").is_wildcard(), true); assert_eq!(AlphaNumeric("other").is_wildcard(), false); } #[test] pub fn empty() { assert_eq!(lex(""), vec![]); } #[test] pub fn numeric_all_numbers() { let expected: Vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9] .into_iter() .map(Numeric) .collect::>(); let actual: Vec<_> = lex("0 1 2 3 4 5 6 7 8 9") .into_iter() .filter(|t| !t.is_whitespace()) .collect(); assert_eq!(actual, expected); } } semver-parser-0.9.0/src/lib.rs000064400000000000000000000027431331176762500144250ustar0000000000000000//! Collection of structures and helper functions for parsing semantic version. //! //! This crate contains data structures for holding version data and comparison of versions //! according to [Semantic versioning](http://semver.org/). //! Main structs are [`version::Version`] representing version itself and [`range::VersionReq`] as a //! collection of [`range::Predicate`] //! representing data for version comparison. //! //! # Examples //! //! ``` //! use semver_parser::range; //! use semver_parser::version; //! //! # fn try_main() -> Result<(), String> { //! let r = range::parse("1.0.0")?; //! //! assert_eq!(range::Predicate { //! op: range::Op::Compatible, //! major: 1, //! minor: Some(0), //! patch: Some(0), //! pre: Vec::new(), //! }, //! r.predicates[0] //! ); //! //! let m = version::parse("1.0.0")?; //! for p in &r.predicates { //! match p.op { //! range::Op::Compatible => { //! assert_eq!(p.major, m.major); //! } //! _ => { //! unimplemented!(); //! } //! } //! } //! # Ok(()) //! # } //! # //! # fn main() { //! # try_main().unwrap(); //! # } //! ``` //! [`version::Version`]: ./version/struct.Version.html //! [`range::Predicate`]: ./range/struct.Predicate.html //! [`range::VersionReq`]: ./range/struct.VersionReq.html #![doc(html_root_url = "https://docs.rs/semver-parser/0.9.0")] pub mod comparator; pub mod lexer; pub mod parser; pub mod range; pub mod version; semver-parser-0.9.0/src/parser.rs000064400000000000000000000272561331176754700151640ustar0000000000000000//! Recursive-descent parser for semver ranges. //! //! The parsers is divided into a set of functions, each responsible for parsing a subset of the //! grammar. //! //! # Examples //! //! ```rust //! use semver_parser::parser::Parser; //! use semver_parser::range::Op; //! //! let mut p = Parser::new("^1").expect("a broken parser"); //! //! assert_eq!(Ok(Op::Compatible), p.op()); //! assert_eq!(Ok(Some(1)), p.component()); //! ``` //! //! Example parsing a range: //! //! ```rust //! use semver_parser::parser::Parser; //! use semver_parser::range::{Op, Predicate}; //! //! let mut p = Parser::new("^1.0").expect("a broken parser"); //! //! assert_eq!(Ok(Some(Predicate { //! op: Op::Compatible, //! major: 1, //! minor: Some(0), //! patch: None, //! pre: vec![], //! })), p.predicate()); //! //! let mut p = Parser::new("^*").expect("a broken parser"); //! //! assert_eq!(Ok(None), p.predicate()); //! ``` use self::Error::*; use comparator::Comparator; use lexer::{self, Lexer, Token}; use range::{Op, Predicate, VersionReq, WildcardVersion}; use std::fmt; use std::mem; use version::{Identifier, Version}; /// Evaluate if parser contains the given pattern as a separator, surrounded by whitespace. macro_rules! has_ws_separator { ($slf:expr, $pat:pat) => {{ $slf.skip_whitespace()?; match $slf.peek() { $pat => { // pop the separator. $slf.pop()?; // strip suffixing whitespace. $slf.skip_whitespace()?; true } _ => false, } }}; } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Error<'input> { /// Needed more tokens for parsing, but none are available. UnexpectedEnd, /// Unexpected token. UnexpectedToken(Token<'input>), /// An error occurred in the lexer. Lexer(lexer::Error), /// More input available. MoreInput(Vec>), /// Encountered empty predicate in a set of predicates. EmptyPredicate, /// Encountered an empty range. EmptyRange, } impl<'input> From for Error<'input> { fn from(value: lexer::Error) -> Self { Error::Lexer(value) } } impl<'input> fmt::Display for Error<'input> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; match *self { UnexpectedEnd => write!(fmt, "expected more input"), UnexpectedToken(ref token) => write!(fmt, "encountered unexpected token: {:?}", token), Lexer(ref error) => write!(fmt, "lexer error: {:?}", error), MoreInput(ref tokens) => write!(fmt, "expected end of input, but got: {:?}", tokens), EmptyPredicate => write!(fmt, "encountered empty predicate"), EmptyRange => write!(fmt, "encountered empty range"), } } } /// impl for backwards compatibility. impl<'input> From> for String { fn from(value: Error<'input>) -> Self { value.to_string() } } /// A recursive-descent parser for parsing version requirements. pub struct Parser<'input> { /// Source of token. lexer: Lexer<'input>, /// Lookaehead. c1: Option>, } impl<'input> Parser<'input> { /// Construct a new parser for the given input. pub fn new(input: &'input str) -> Result, Error<'input>> { let mut lexer = Lexer::new(input); let c1 = if let Some(c1) = lexer.next() { Some(c1?) } else { None }; Ok(Parser { lexer: lexer, c1: c1, }) } /// Pop one token. #[inline(always)] fn pop(&mut self) -> Result, Error<'input>> { let c1 = if let Some(c1) = self.lexer.next() { Some(c1?) } else { None }; mem::replace(&mut self.c1, c1).ok_or_else(|| UnexpectedEnd) } /// Peek one token. #[inline(always)] fn peek(&mut self) -> Option<&Token<'input>> { self.c1.as_ref() } /// Skip whitespace if present. fn skip_whitespace(&mut self) -> Result<(), Error<'input>> { match self.peek() { Some(&Token::Whitespace(_, _)) => self.pop().map(|_| ()), _ => Ok(()), } } /// Parse an optional comma separator, then if that is present a predicate. pub fn comma_predicate(&mut self) -> Result, Error<'input>> { let has_comma = has_ws_separator!(self, Some(&Token::Comma)); if let Some(predicate) = self.predicate()? { Ok(Some(predicate)) } else if has_comma { Err(EmptyPredicate) } else { Ok(None) } } /// Parse an optional or separator `||`, then if that is present a range. fn or_range(&mut self) -> Result, Error<'input>> { if !has_ws_separator!(self, Some(&Token::Or)) { return Ok(None); } Ok(Some(self.range()?)) } /// Parse a single component. /// /// Returns `None` if the component is a wildcard. pub fn component(&mut self) -> Result, Error<'input>> { match self.pop()? { Token::Numeric(number) => Ok(Some(number)), ref t if t.is_wildcard() => Ok(None), tok => Err(UnexpectedToken(tok)), } } /// Parse a single numeric. pub fn numeric(&mut self) -> Result> { match self.pop()? { Token::Numeric(number) => Ok(number), tok => Err(UnexpectedToken(tok)), } } /// Optionally parse a dot, then a component. /// /// The second component of the tuple indicates if a wildcard has been encountered, and is /// always `false` if the first component is `Some`. /// /// If a dot is not encountered, `(None, false)` is returned. /// /// If a wildcard is encountered, `(None, true)` is returned. pub fn dot_component(&mut self) -> Result<(Option, bool), Error<'input>> { match self.peek() { Some(&Token::Dot) => {} _ => return Ok((None, false)), } // pop the peeked dot. self.pop()?; self.component().map(|n| (n, n.is_none())) } /// Parse a dot, then a numeric. pub fn dot_numeric(&mut self) -> Result> { match self.pop()? { Token::Dot => {} tok => return Err(UnexpectedToken(tok)), } self.numeric() } /// Parse an string identifier. /// /// Like, `foo`, or `bar`. pub fn identifier(&mut self) -> Result> { let identifier = match self.pop()? { Token::AlphaNumeric(identifier) => { // TODO: Borrow? Identifier::AlphaNumeric(identifier.to_string()) } Token::Numeric(n) => Identifier::Numeric(n), tok => return Err(UnexpectedToken(tok)), }; Ok(identifier) } /// Parse all pre-release identifiers, separated by dots. /// /// Like, `abcdef.1234`. fn pre(&mut self) -> Result, Error<'input>> { match self.peek() { Some(&Token::Hyphen) => {} _ => return Ok(vec![]), } // pop the peeked hyphen. self.pop()?; self.parts() } /// Parse a dot-separated set of identifiers. fn parts(&mut self) -> Result, Error<'input>> { let mut parts = Vec::new(); parts.push(self.identifier()?); loop { match self.peek() { Some(&Token::Dot) => {} _ => break, } // pop the peeked hyphen. self.pop()?; parts.push(self.identifier()?); } Ok(parts) } /// Parse optional build metadata. /// /// Like, `` (empty), or `+abcdef`. fn plus_build_metadata(&mut self) -> Result, Error<'input>> { match self.peek() { Some(&Token::Plus) => {} _ => return Ok(vec![]), } // pop the plus. self.pop()?; self.parts() } /// Optionally parse a single operator. /// /// Like, `~`, or `^`. pub fn op(&mut self) -> Result> { use self::Token::*; let op = match self.peek() { Some(&Eq) => Op::Ex, Some(&Gt) => Op::Gt, Some(&GtEq) => Op::GtEq, Some(&Lt) => Op::Lt, Some(&LtEq) => Op::LtEq, Some(&Tilde) => Op::Tilde, Some(&Caret) => Op::Compatible, // default op _ => return Ok(Op::Compatible), }; // remove the matched token. self.pop()?; self.skip_whitespace()?; Ok(op) } /// Parse a single predicate. /// /// Like, `^1`, or `>=2.0.0`. pub fn predicate(&mut self) -> Result, Error<'input>> { // empty predicate, treated the same as wildcard. if self.peek().is_none() { return Ok(None); } let mut op = self.op()?; let major = match self.component()? { Some(major) => major, None => return Ok(None), }; let (minor, minor_wildcard) = self.dot_component()?; let (patch, patch_wildcard) = self.dot_component()?; let pre = self.pre()?; // TODO: avoid illegal combinations, like `1.*.0`. if minor_wildcard { op = Op::Wildcard(WildcardVersion::Minor); } if patch_wildcard { op = Op::Wildcard(WildcardVersion::Patch); } // ignore build metadata self.plus_build_metadata()?; Ok(Some(Predicate { op: op, major: major, minor: minor, patch: patch, pre: pre, })) } /// Parse a single range. /// /// Like, `^1.0` or `>=3.0.0, <4.0.0`. pub fn range(&mut self) -> Result> { let mut predicates = Vec::new(); if let Some(predicate) = self.predicate()? { predicates.push(predicate); while let Some(next) = self.comma_predicate()? { predicates.push(next); } } Ok(VersionReq { predicates: predicates, }) } /// Parse a comparator. /// /// Like, `1.0 || 2.0` or `^1 || >=3.0.0, <4.0.0`. pub fn comparator(&mut self) -> Result> { let mut ranges = Vec::new(); ranges.push(self.range()?); while let Some(next) = self.or_range()? { ranges.push(next); } Ok(Comparator { ranges: ranges }) } /// Parse a version. /// /// Like, `1.0.0` or `3.0.0-beta.1`. pub fn version(&mut self) -> Result> { self.skip_whitespace()?; let major = self.numeric()?; let minor = self.dot_numeric()?; let patch = self.dot_numeric()?; let pre = self.pre()?; let build = self.plus_build_metadata()?; self.skip_whitespace()?; Ok(Version { major: major, minor: minor, patch: patch, pre: pre, build: build, }) } /// Check if we have reached the end of input. pub fn is_eof(&mut self) -> bool { self.c1.is_none() } /// Get the rest of the tokens in the parser. /// /// Useful for debugging. pub fn tail(&mut self) -> Result>, Error<'input>> { let mut out = Vec::new(); if let Some(t) = self.c1.take() { out.push(t); } while let Some(t) = self.lexer.next() { out.push(t?); } Ok(out) } } semver-parser-0.9.0/src/range.rs000064400000000000000000000626161331176754700147630ustar0000000000000000//! Version range and requirements data and functions (used for version comparison). //! //! This module contains [`Predicate`] struct which holds data for comparison //! [`version::Version`] structs: [`VersionReq`] struct as a collection of //! [`Predicate`]s, functions for parsing those structs and some helper data structures //! and functions. //! //! # Examples //! //! Parsing version range and matching it with concrete version: //! //! ``` //! use semver_parser::range; //! use semver_parser::version; //! //! # fn try_main() -> Result<(), String> { //! let r = range::parse("1.0.0")?; //! //! assert_eq!(range::Predicate { //! op: range::Op::Compatible, //! major: 1, //! minor: Some(0), //! patch: Some(0), //! pre: Vec::new(), //! }, //! r.predicates[0] //! ); //! //! let m = version::parse("1.0.0")?; //! for p in &r.predicates { //! match p.op { //! range::Op::Compatible => { //! assert_eq!(p.major, m.major); //! } //! _ => { //! unimplemented!(); //! } //! } //! } //! # Ok(()) //! # } //! # //! # fn main() { //! # try_main().unwrap(); //! # } //! ``` //! //! [`Predicate`]: ./struct.Predicate.html //! [`VersionReq`]: ./struct.VersionReq.html //! [`version::Version`]: ../version/struct.Version.html use parser::{self, Parser}; use std::str::FromStr; use version::Identifier; /// Struct holding collection of version requirements. /// /// High-level collection of requirements for versions. Requirements are [`Predicate`] structs. /// /// # Examples /// /// Simple single-predicate `VersionReq`: /// /// ``` /// use semver_parser::range; /// /// # fn try_main() -> Result<(), String> { /// let r = range::parse("1.0.0")?; /// /// assert_eq!(range::Predicate { /// op: range::Op::Compatible, /// major: 1, /// minor: Some(0), /// patch: Some(0), /// pre: Vec::new(), /// }, /// r.predicates[0] /// ); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// /// Multiple predicates in `VersionReq`: /// /// ``` /// use semver_parser::range; /// /// # fn try_main() -> Result<(), String> { /// let r = range::parse("> 0.0.9, <= 2.5.3")?; /// /// assert_eq!(range::Predicate { /// op: range::Op::Gt, /// major: 0, /// minor: Some(0), /// patch: Some(9), /// pre: Vec::new(), /// }, /// r.predicates[0] /// ); /// /// assert_eq!(range::Predicate { /// op: range::Op::LtEq, /// major: 2, /// minor: Some(5), /// patch: Some(3), /// pre: Vec::new(), /// }, /// r.predicates[1] /// ); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// /// [`Predicate`]: ./struct.Predicate.html #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub struct VersionReq { /// Collection of predicates. pub predicates: Vec, } /// Enum representing a `*` version part. /// /// This is one of variants of the [`Op`] enum wich is part of [`Predicate`] enum. /// All variants represent some "match-all" cases for specific numeric parts of version. /// /// # Examples /// /// Parsing wildcard predicate and checking that its predicates are empty. /// /// ``` /// use semver_parser::range; /// /// # fn try_main() -> Result<(), String> { /// let r = range::parse("*")?; /// /// assert!(r.predicates.is_empty()); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// [`Op`]: ./enum.Op.html /// [`Predicate`]: ./struct.Predicate.html #[derive(PartialOrd, Ord, PartialEq, Eq, Debug, Hash, Clone)] pub enum WildcardVersion { /// Wildcard minor version `1.*.3`. Minor, /// Wildcard patch version `1.2.*`. Patch, } /// Enum representing operation in [`Predicate`]. /// /// This enum represents an operation for comparing two [`version::Version`]s. /// /// # Examples /// /// Parsing `Op` from string: /// /// ``` /// use semver_parser::range; /// use std::str::FromStr; /// /// # fn try_main() -> Result<(), String> { /// let exact = range::Op::from_str("=")?; /// assert_eq!(exact, range::Op::Ex); /// let gt_eq = range::Op::from_str(">=")?; /// assert_eq!(gt_eq, range::Op::GtEq); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// [`Predicate`]: ./struct.Predicate.html /// [`version::Version`]: ../version/struct.Version.html #[derive(PartialOrd, Ord, PartialEq, Eq, Debug, Clone, Hash)] pub enum Op { /// Exact, `=`. Ex, /// Greater than, `>`. Gt, /// Greater than or equal to, `>=`. GtEq, /// Less than, `<`. Lt, /// Less than or equal to, `<=`. LtEq, /// [Tilde](http://doc.crates.io/specifying-dependencies.html#tilde-requirements) /// requirements, like `~1.0.0` - a minimal version with some ability to update. Tilde, /// [Compatible](http://doc.crates.io/specifying-dependencies.html#caret-requirements) /// by definition of semver, indicated by `^`. Compatible, /// `x.y.*`, `x.*`, `*`. Wildcard(WildcardVersion), } impl FromStr for Op { type Err = String; fn from_str(s: &str) -> Result { match s { "=" => Ok(Op::Ex), ">" => Ok(Op::Gt), ">=" => Ok(Op::GtEq), "<" => Ok(Op::Lt), "<=" => Ok(Op::LtEq), "~" => Ok(Op::Tilde), "^" => Ok(Op::Compatible), _ => Err(String::from("Could not parse Op")), } } } /// Struct representing a version comparison predicate. /// /// Struct contaions operation code and data for comparison of [`version::Version`]s. /// /// # Examples /// /// Parsing [`Predicate`] from string and checking its fields: /// /// ``` /// use semver_parser::range; /// /// # fn try_main() -> Result<(), String> { /// let p = range::parse_predicate(">=1.1")?.expect("non-empty"); /// assert_eq!(p.op, range::Op::GtEq); /// assert_eq!(p.major, 1); /// assert_eq!(p.minor.unwrap(), 1); /// assert!(p.patch.is_none()); /// assert!(p.pre.is_empty()); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// [`Predicate`]: ./struct.Predicate.html /// [`version::Version`]: ../version/struct.Version.html #[derive(PartialEq, Eq, Debug, Clone, Hash, PartialOrd, Ord)] pub struct Predicate { /// Operation code for this predicate, like "greater than" or "exact match". pub op: Op, /// Major version. pub major: u64, /// Optional minor version. pub minor: Option, /// Optional patch version. pub patch: Option, /// Collection of `Identifier`s of version, like `"alpha1"` in `"1.2.3-alpha1"`. pub pre: Vec, } /// Function parsing [`Predicate`] from string. /// /// Function parsing [`Predicate`] from string to `Result<`[`Predicate`]`, String>`, /// where `Err` will contain error message in case of failed parsing. /// /// # Examples /// /// Parsing [`Predicate`] from string and cheking its fields: /// /// ``` /// use semver_parser::range; /// /// # fn try_main() -> Result<(), String> { /// let p = range::parse_predicate(">=1.1")?.expect("non-empty"); /// assert_eq!(p.op, range::Op::GtEq); /// assert_eq!(p.major, 1); /// assert_eq!(p.minor.unwrap(), 1); /// assert!(p.patch.is_none()); /// assert!(p.pre.is_empty()); /// /// let f = range::parse_predicate("not-a-version-predicate"); /// assert!(f.is_err()); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// [`Predicate`]: ./struct.Predicate.html pub fn parse_predicate<'input>( input: &'input str, ) -> Result, parser::Error<'input>> { let mut parser = Parser::new(input)?; let predicate = parser.predicate()?; if !parser.is_eof() { return Err(parser::Error::MoreInput(parser.tail()?)); } Ok(predicate) } /// Function for parsing [`VersionReq`] from string. /// /// Function for parsing [`VersionReq`] from string to `Result<`[`VersionReq`]`, String>`, /// where `Err` will contain error message in case of failed parsing. /// /// # Examples /// /// Simple single-predicate [`VersionReq`]: /// /// ``` /// use semver_parser::range; /// /// # fn try_main() -> Result<(), String> { /// let r = range::parse("1.0.0")?; /// /// assert_eq!(range::Predicate { /// op: range::Op::Compatible, /// major: 1, /// minor: Some(0), /// patch: Some(0), /// pre: Vec::new(), /// }, /// r.predicates[0] /// ); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// /// Multiple predicates in [`VersionReq`]: /// /// ``` /// use semver_parser::range; /// /// # fn try_main() -> Result<(), String> { /// let r = range::parse("> 0.0.9, <= 2.5.3")?; /// /// assert_eq!(range::Predicate { /// op: range::Op::Gt, /// major: 0, /// minor: Some(0), /// patch: Some(9), /// pre: Vec::new(), /// }, /// r.predicates[0] /// ); /// /// assert_eq!(range::Predicate { /// op: range::Op::LtEq, /// major: 2, /// minor: Some(5), /// patch: Some(3), /// pre: Vec::new(), /// }, /// r.predicates[1] /// ); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// /// [`VersionReq`]: ./struct.VersionReq.html pub fn parse<'input>(input: &'input str) -> Result> { let mut parser = Parser::new(input)?; let range = parser.range()?; if !parser.is_eof() { return Err(parser::Error::MoreInput(parser.tail()?)); } Ok(range) } #[cfg(test)] mod tests { use super::*; use range; use version::Identifier; #[test] fn test_parsing_wildcards() { assert_eq!( Op::Wildcard(WildcardVersion::Patch), range::parse("1.0.*").unwrap().predicates[0].op ); assert_eq!( Op::Wildcard(WildcardVersion::Patch), range::parse("1.*.*").unwrap().predicates[0].op ); assert_eq!( Op::Wildcard(WildcardVersion::Minor), parse("1.*.0").unwrap().predicates[0].op ); } #[test] fn test_parsing_default() { let r = range::parse("1.0.0").unwrap(); assert_eq!( Predicate { op: Op::Compatible, major: 1, minor: Some(0), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_exact_01() { let r = range::parse("=1.0.0").unwrap(); assert_eq!( Predicate { op: Op::Ex, major: 1, minor: Some(0), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_exact_02() { let r = range::parse("=0.9.0").unwrap(); assert_eq!( Predicate { op: Op::Ex, major: 0, minor: Some(9), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_exact_03() { let r = range::parse("=0.1.0-beta2.a").unwrap(); assert_eq!( Predicate { op: Op::Ex, major: 0, minor: Some(1), patch: Some(0), pre: vec![ Identifier::AlphaNumeric(String::from("beta2")), Identifier::AlphaNumeric(String::from("a")), ], }, r.predicates[0] ); } #[test] pub fn test_parsing_greater_than() { let r = range::parse("> 1.0.0").unwrap(); assert_eq!( Predicate { op: Op::Gt, major: 1, minor: Some(0), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); } #[test] pub fn test_parsing_greater_than_01() { let r = range::parse(">= 1.0.0").unwrap(); assert_eq!( Predicate { op: Op::GtEq, major: 1, minor: Some(0), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); } #[test] pub fn test_parsing_greater_than_02() { let r = range::parse(">= 2.1.0-alpha2").unwrap(); assert_eq!( Predicate { op: Op::GtEq, major: 2, minor: Some(1), patch: Some(0), pre: vec![Identifier::AlphaNumeric(String::from("alpha2"))], }, r.predicates[0] ); } #[test] pub fn test_parsing_less_than() { let r = range::parse("< 1.0.0").unwrap(); assert_eq!( Predicate { op: Op::Lt, major: 1, minor: Some(0), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); } #[test] pub fn test_parsing_less_than_eq() { let r = range::parse("<= 2.1.0-alpha2").unwrap(); assert_eq!( Predicate { op: Op::LtEq, major: 2, minor: Some(1), patch: Some(0), pre: vec![Identifier::AlphaNumeric(String::from("alpha2"))], }, r.predicates[0] ); } #[test] pub fn test_parsing_tilde() { let r = range::parse("~1").unwrap(); assert_eq!( Predicate { op: Op::Tilde, major: 1, minor: None, patch: None, pre: Vec::new(), }, r.predicates[0] ); } #[test] pub fn test_parsing_compatible() { let r = range::parse("^0").unwrap(); assert_eq!( Predicate { op: Op::Compatible, major: 0, minor: None, patch: None, pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_blank() { let r = range::parse("").unwrap(); assert!(r.predicates.is_empty()); } #[test] fn test_parsing_wildcard() { let r = range::parse("*").unwrap(); assert!(r.predicates.is_empty()); } #[test] fn test_uppercase_prereleases() { assert_eq!( vec![Identifier::AlphaNumeric("Foo".to_string())], range::parse("0-Foo").unwrap().predicates[0].pre ); assert_eq!( vec![Identifier::AlphaNumeric("X".to_string())], range::parse("0-X").unwrap().predicates[0].pre ); } #[test] fn test_empty_prerelease() { assert!(range::parse("0-").is_err()); } #[test] fn test_parsing_x() { let r = range::parse("x").unwrap(); assert!(r.predicates.is_empty()); } #[test] fn test_parsing_capital_x() { let r = range::parse("X").unwrap(); assert!(r.predicates.is_empty()); } /// TODO: this should probably be using WildcardVersion::Minor #[test] fn test_parsing_wildcard_star_star() { let r = range::parse("1.*.*").unwrap(); assert_eq!( Predicate { op: Op::Wildcard(WildcardVersion::Patch), major: 1, minor: None, patch: None, pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_minor_wildcard_star() { let r = range::parse("1.*").unwrap(); assert_eq!( Predicate { op: Op::Wildcard(WildcardVersion::Minor), major: 1, minor: None, patch: None, pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_minor_wildcard_star_patch() { let r = range::parse("1.*.0").unwrap(); assert_eq!( Predicate { op: Op::Wildcard(WildcardVersion::Minor), major: 1, minor: None, patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_minor_wildcard_x() { let r = range::parse("1.x").unwrap(); assert_eq!( Predicate { op: Op::Wildcard(WildcardVersion::Minor), major: 1, minor: None, patch: None, pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_minor_wildcard_capital_x() { let r = range::parse("1.X").unwrap(); assert_eq!( Predicate { op: Op::Wildcard(WildcardVersion::Minor), major: 1, minor: None, patch: None, pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_patch_wildcard_star() { let r = range::parse("1.2.*").unwrap(); assert_eq!( Predicate { op: Op::Wildcard(WildcardVersion::Patch), major: 1, minor: Some(2), patch: None, pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_patch_wildcard_x() { let r = range::parse("1.2.x").unwrap(); assert_eq!( Predicate { op: Op::Wildcard(WildcardVersion::Patch), major: 1, minor: Some(2), patch: None, pre: Vec::new(), }, r.predicates[0] ); } #[test] fn test_parsing_patch_wildcard_capital_x() { let r = range::parse("1.2.X").unwrap(); assert_eq!( Predicate { op: Op::Wildcard(WildcardVersion::Patch), major: 1, minor: Some(2), patch: None, pre: Vec::new(), }, r.predicates[0] ); } #[test] pub fn test_multiple_01() { let r = range::parse("> 0.0.9, <= 2.5.3").unwrap(); assert_eq!( Predicate { op: Op::Gt, major: 0, minor: Some(0), patch: Some(9), pre: Vec::new(), }, r.predicates[0] ); assert_eq!( Predicate { op: Op::LtEq, major: 2, minor: Some(5), patch: Some(3), pre: Vec::new(), }, r.predicates[1] ); } #[test] pub fn test_multiple_02() { let r = range::parse("0.3.0, 0.4.0").unwrap(); assert_eq!( Predicate { op: Op::Compatible, major: 0, minor: Some(3), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); assert_eq!( Predicate { op: Op::Compatible, major: 0, minor: Some(4), patch: Some(0), pre: Vec::new(), }, r.predicates[1] ); } #[test] pub fn test_multiple_03() { let r = range::parse("<= 0.2.0, >= 0.5.0").unwrap(); assert_eq!( Predicate { op: Op::LtEq, major: 0, minor: Some(2), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); assert_eq!( Predicate { op: Op::GtEq, major: 0, minor: Some(5), patch: Some(0), pre: Vec::new(), }, r.predicates[1] ); } #[test] pub fn test_multiple_04() { let r = range::parse("0.1.0, 0.1.4, 0.1.6").unwrap(); assert_eq!( Predicate { op: Op::Compatible, major: 0, minor: Some(1), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); assert_eq!( Predicate { op: Op::Compatible, major: 0, minor: Some(1), patch: Some(4), pre: Vec::new(), }, r.predicates[1] ); assert_eq!( Predicate { op: Op::Compatible, major: 0, minor: Some(1), patch: Some(6), pre: Vec::new(), }, r.predicates[2] ); } #[test] pub fn test_multiple_05() { let r = range::parse(">=0.5.1-alpha3, <0.6").unwrap(); assert_eq!( Predicate { op: Op::GtEq, major: 0, minor: Some(5), patch: Some(1), pre: vec![Identifier::AlphaNumeric(String::from("alpha3"))], }, r.predicates[0] ); assert_eq!( Predicate { op: Op::Lt, major: 0, minor: Some(6), patch: None, pre: Vec::new(), }, r.predicates[1] ); } #[test] pub fn test_multiple_06() { let r = range::parse("<= 0.2.0 >= 0.5.0").unwrap(); assert_eq!( Predicate { op: Op::LtEq, major: 0, minor: Some(2), patch: Some(0), pre: Vec::new(), }, r.predicates[0] ); assert_eq!( Predicate { op: Op::GtEq, major: 0, minor: Some(5), patch: Some(0), pre: Vec::new(), }, r.predicates[1] ); } #[test] fn test_parse_build_metadata_with_predicate() { assert_eq!( range::parse("^1.2.3+meta").unwrap().predicates[0].op, Op::Compatible ); assert_eq!( range::parse("~1.2.3+meta").unwrap().predicates[0].op, Op::Tilde ); assert_eq!( range::parse("=1.2.3+meta").unwrap().predicates[0].op, Op::Ex ); assert_eq!( range::parse("<=1.2.3+meta").unwrap().predicates[0].op, Op::LtEq ); assert_eq!( range::parse(">=1.2.3+meta").unwrap().predicates[0].op, Op::GtEq ); assert_eq!( range::parse("<1.2.3+meta").unwrap().predicates[0].op, Op::Lt ); assert_eq!( range::parse(">1.2.3+meta").unwrap().predicates[0].op, Op::Gt ); } #[test] pub fn test_parse_errors() { assert!(range::parse("\0").is_err()); assert!(range::parse(">= >= 0.0.2").is_err()); assert!(range::parse(">== 0.0.2").is_err()); assert!(range::parse("a.0.0").is_err()); assert!(range::parse("1.0.0-").is_err()); assert!(range::parse(">=").is_err()); assert!(range::parse("> 0.1.0,").is_err()); assert!(range::parse("> 0.3.0, ,").is_err()); assert!(range::parse("> 0. 1").is_err()); } #[test] pub fn test_large_major_version() { assert!(range::parse("18446744073709551617.0.0").is_err()); } #[test] pub fn test_large_minor_version() { assert!(range::parse("0.18446744073709551617.0").is_err()); } #[test] pub fn test_large_patch_version() { assert!(range::parse("0.0.18446744073709551617").is_err()); } #[test] pub fn test_op_partialord_lt() { let expect_less = Op::Ex; let other = Op::Gt; assert!(expect_less.lt(&other)); } #[test] pub fn test_op_partialord_le() { let strictly_lt = Op::Ex; let other = Op::Lt; assert!(strictly_lt.le(&other)); assert!(other.le(&other)); } #[test] pub fn test_op_partialord_gt() { let expect_gt = Op::Compatible; let other = Op::GtEq; assert!(expect_gt.gt(&other)); } #[test] pub fn test_op_partialord_ge() { let strictly_gt = Op::Compatible; let other = Op::Tilde; assert!(strictly_gt.ge(&other)); assert!(other.ge(&other)); } #[test] pub fn test_wildcard_partialord_lt() { let expect_less = WildcardVersion::Minor; let other = WildcardVersion::Patch; assert!(expect_less.lt(&other)); } #[test] pub fn test_wildcard_partialord_le() { let strictly_lt = WildcardVersion::Minor; let other = WildcardVersion::Patch; assert!(strictly_lt.le(&other)); assert!(other.le(&other)); } #[test] pub fn test_wildcard_partialord_gt() { let expect_greater = WildcardVersion::Patch; let other = WildcardVersion::Minor; assert!(expect_greater.gt(&other)); } #[test] pub fn test_wildcard_partialord_ge() { let strictly_gt = WildcardVersion::Patch; let other = WildcardVersion::Minor; assert!(strictly_gt.ge(&other)); assert!(other.ge(&other)); } } semver-parser-0.9.0/src/version.rs000064400000000000000000000314331331176664300153410ustar0000000000000000//! Version data and functions. //! //! This module contains [`Version`] struct, [`parse`] function for building //! [`Version`] struct from string and some helper data structures and functions. //! //! # Examples //! //! Parsing `Version` from string and checking its fields: //! //! ``` //! use semver_parser::version; //! //! # fn try_main() -> Result<(), String> { //! let version = version::parse("1.2.3-alpha1")?; //! //! assert_eq!(version.major, 1); //! assert_eq!(version.minor, 2); //! assert_eq!(version.patch, 3); //! //! let expected_pre = vec![ //! version::Identifier::AlphaNumeric(String::from("alpha1")), //! ]; //! //! assert_eq!(expected_pre, version.pre); //! # Ok(()) //! # } //! # //! # fn main() { //! # try_main().unwrap(); //! # } //! ``` //! [`Version`]: ./struct.Version.html //! [`parse`]: ./fn.parse.html use parser::{self, Parser}; use std::fmt; /// Structure representing version data. /// /// `Version` struct has some public fields representing version data, like major/minor version /// string, patch number and vectors of prefix and build identifiers. /// /// # Examples /// /// Parsing `Version` from string and checking its fields: /// /// ``` /// use semver_parser::version; /// /// # fn try_main() -> Result<(), String> { /// let version = version::parse("0.1.2-alpha1")?; /// assert_eq!(version.major, 0); /// assert_eq!(version.minor, 1); /// assert_eq!(version.patch, 2); /// let expected_pre = vec![version::Identifier::AlphaNumeric(String::from("alpha1"))]; /// assert_eq!(expected_pre, version.pre); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` #[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq)] pub struct Version { /// Major version as number (`0` in `"0.1.2"`). pub major: u64, /// Minor version as number (`1` in `"0.1.2"`). pub minor: u64, /// Patch version as number (`2` in `"0.1.2"`). pub patch: u64, /// Pre-release metadata as a vector of `Identifier` (`"alpha1"` in `"0.1.2-alpha1"` /// or `7` (numeric) in `"0.1.2-7"`, `"pre"` and `0` (numeric) in `"0.1.2-pre.0"`). pub pre: Vec, /// Build metadata as a vector of `Identifier` (`"build1"` in `"0.1.2+build1"` /// or `7` (numeric) in `"0.1.2+7"`, `"build"` and `0` (numeric) in `"0.1.2+pre.0"`). pub build: Vec, } /// Helper enum for holding data of alphanumeric or numeric suffix identifiers. /// /// This enum is used to hold suffix parts of `pre` and `build` fields of /// [`Version`] struct. Theses suffixes may be either numeric or alphanumeric. /// /// # Examples /// /// Parsing [`Version`] with pre-release part composed of two `Identifier`s: /// /// ``` /// use semver_parser::version; /// /// # fn try_main() -> Result<(), String> { /// let version = version::parse("0.1.2-alpha1.0")?; /// /// let expected_pre = vec![ /// version::Identifier::AlphaNumeric(String::from("alpha1")), /// version::Identifier::Numeric(0), /// ]; /// /// assert_eq!(expected_pre, version.pre); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// [`Version`]: ./struct.Version.html #[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq)] pub enum Identifier { /// An identifier that's solely numbers. Numeric(u64), /// An identifier with letters and numbers. AlphaNumeric(String), } /// Function for parsing version string to [`Version`]. /// /// Returns `Result<`[`Version`]`, String>`, where `String` represents an error while parsing. /// /// # Examples /// /// Parsing [`Version`] from string and checking its fields: /// /// ``` /// use semver_parser::version; /// /// # fn try_main() -> Result<(), String> { /// let version = version::parse("0.1.2-alpha1")?; /// assert_eq!(version.major, 0); /// assert_eq!(version.minor, 1); /// assert_eq!(version.patch, 2); /// let expected_pre = vec![version::Identifier::AlphaNumeric(String::from("alpha1"))]; /// assert_eq!(expected_pre, version.pre); /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// [`Version`]: ./struct.Version.html pub fn parse<'input>(input: &'input str) -> Result> { let mut parser = Parser::new(input)?; let version = parser.version()?; if !parser.is_eof() { return Err(parser::Error::MoreInput(parser.tail()?)); } Ok(version) } impl fmt::Display for Version { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch)); if !self.pre.is_empty() { let strs: Vec<_> = self.pre.iter().map(ToString::to_string).collect(); try!(write!(f, "-{}", strs.join("."))); } if !self.build.is_empty() { let strs: Vec<_> = self.build.iter().map(ToString::to_string).collect(); try!(write!(f, "+{}", strs.join("."))); } Ok(()) } } impl fmt::Display for Identifier { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Identifier::Numeric(ref id) => id.fmt(f), Identifier::AlphaNumeric(ref id) => id.fmt(f), } } } #[cfg(test)] mod tests { use super::*; use version; #[test] fn parse_empty() { let version = ""; let parsed = version::parse(version); assert!( parsed.is_err(), "empty string incorrectly considered a valid parse" ); } #[test] fn parse_blank() { let version = " "; let parsed = version::parse(version); assert!( parsed.is_err(), "blank string incorrectly considered a valid parse" ); } #[test] fn parse_no_minor_patch() { let version = "1"; let parsed = version::parse(version); assert!( parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version) ); } #[test] fn parse_no_patch() { let version = "1.2"; let parsed = version::parse(version); assert!( parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version) ); } #[test] fn parse_empty_pre() { let version = "1.2.3-"; let parsed = version::parse(version); assert!( parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version) ); } #[test] fn parse_letters() { let version = "a.b.c"; let parsed = version::parse(version); assert!( parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version) ); } #[test] fn parse_with_letters() { let version = "1.2.3 a.b.c"; let parsed = version::parse(version); assert!( parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version) ); } #[test] fn parse_basic_version() { let version = "1.2.3"; let parsed = version::parse(version).unwrap(); assert_eq!(1, parsed.major); assert_eq!(2, parsed.minor); assert_eq!(3, parsed.patch); } #[test] fn parse_trims_input() { let version = " 1.2.3 "; let parsed = version::parse(version).unwrap(); assert_eq!(1, parsed.major); assert_eq!(2, parsed.minor); assert_eq!(3, parsed.patch); } #[test] fn parse_no_major_leading_zeroes() { let version = "01.0.0"; let parsed = version::parse(version); assert!( parsed.is_err(), "01 incorrectly considered a valid major version" ); } #[test] fn parse_no_minor_leading_zeroes() { let version = "0.01.0"; let parsed = version::parse(version); assert!( parsed.is_err(), "01 incorrectly considered a valid minor version" ); } #[test] fn parse_no_patch_leading_zeroes() { let version = "0.0.01"; let parsed = version::parse(version); assert!( parsed.is_err(), "01 incorrectly considered a valid patch version" ); } #[test] fn parse_no_major_overflow() { let version = "98765432109876543210.0.0"; let parsed = version::parse(version); assert!( parsed.is_err(), "98765432109876543210 incorrectly considered a valid major version" ); } #[test] fn parse_no_minor_overflow() { let version = "0.98765432109876543210.0"; let parsed = version::parse(version); assert!( parsed.is_err(), "98765432109876543210 incorrectly considered a valid minor version" ); } #[test] fn parse_no_patch_overflow() { let version = "0.0.98765432109876543210"; let parsed = version::parse(version); assert!( parsed.is_err(), "98765432109876543210 incorrectly considered a valid patch version" ); } #[test] fn parse_basic_prerelease() { let version = "1.2.3-pre"; let parsed = version::parse(version).unwrap(); let expected_pre = vec![Identifier::AlphaNumeric(String::from("pre"))]; assert_eq!(expected_pre, parsed.pre); } #[test] fn parse_prerelease_alphanumeric() { let version = "1.2.3-alpha1"; let parsed = version::parse(version).unwrap(); let expected_pre = vec![Identifier::AlphaNumeric(String::from("alpha1"))]; assert_eq!(expected_pre, parsed.pre); } #[test] fn parse_prerelease_zero() { let version = "1.2.3-pre.0"; let parsed = version::parse(version).unwrap(); let expected_pre = vec![ Identifier::AlphaNumeric(String::from("pre")), Identifier::Numeric(0), ]; assert_eq!(expected_pre, parsed.pre); } #[test] fn parse_basic_build() { let version = "1.2.3+build"; let parsed = version::parse(version).unwrap(); let expected_build = vec![Identifier::AlphaNumeric(String::from("build"))]; assert_eq!(expected_build, parsed.build); } #[test] fn parse_build_alphanumeric() { let version = "1.2.3+build5"; let parsed = version::parse(version).unwrap(); let expected_build = vec![Identifier::AlphaNumeric(String::from("build5"))]; assert_eq!(expected_build, parsed.build); } #[test] fn parse_pre_and_build() { let version = "1.2.3-alpha1+build5"; let parsed = version::parse(version).unwrap(); let expected_pre = vec![Identifier::AlphaNumeric(String::from("alpha1"))]; assert_eq!(expected_pre, parsed.pre); let expected_build = vec![Identifier::AlphaNumeric(String::from("build5"))]; assert_eq!(expected_build, parsed.build); } #[test] fn parse_complex_metadata_01() { let version = "1.2.3-1.alpha1.9+build5.7.3aedf "; let parsed = version::parse(version).unwrap(); let expected_pre = vec![ Identifier::Numeric(1), Identifier::AlphaNumeric(String::from("alpha1")), Identifier::Numeric(9), ]; assert_eq!(expected_pre, parsed.pre); let expected_build = vec![ Identifier::AlphaNumeric(String::from("build5")), Identifier::Numeric(7), Identifier::AlphaNumeric(String::from("3aedf")), ]; assert_eq!(expected_build, parsed.build); } #[test] fn parse_complex_metadata_02() { let version = "0.4.0-beta.1+0851523"; let parsed = version::parse(version).unwrap(); let expected_pre = vec![ Identifier::AlphaNumeric(String::from("beta")), Identifier::Numeric(1), ]; assert_eq!(expected_pre, parsed.pre); let expected_build = vec![Identifier::AlphaNumeric(String::from("0851523"))]; assert_eq!(expected_build, parsed.build); } #[test] fn parse_metadata_overflow() { let version = "0.4.0-beta.1+98765432109876543210"; let parsed = version::parse(version).unwrap(); let expected_pre = vec![ Identifier::AlphaNumeric(String::from("beta")), Identifier::Numeric(1), ]; assert_eq!(expected_pre, parsed.pre); let expected_build = vec![ Identifier::AlphaNumeric(String::from("98765432109876543210")), ]; assert_eq!(expected_build, parsed.build); } #[test] fn parse_regression_01() { let version = "0.0.0-WIP"; let parsed = version::parse(version).unwrap(); assert_eq!(0, parsed.major); assert_eq!(0, parsed.minor); assert_eq!(0, parsed.patch); let expected_pre = vec![Identifier::AlphaNumeric(String::from("WIP"))]; assert_eq!(expected_pre, parsed.pre); } }