git-conventional-0.12.9/.cargo_vcs_info.json0000644000000001360000000000100144050ustar { "git": { "sha1": "ceb9b98e53934cbb3049eee13260a0114430f8df" }, "path_in_vcs": "" }git-conventional-0.12.9/Cargo.lock0000644000000054670000000000100123740ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "git-conventional" version = "0.12.9" dependencies = [ "indoc", "serde", "serde_test", "unicase", "winnow", ] [[package]] name = "indoc" version = "2.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5" [[package]] name = "memchr" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "proc-macro2" version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f4f29d145265ec1c483c7c654450edde0bfe043d3938d6972630663356d9500" dependencies = [ "proc-macro2", ] [[package]] name = "serde" version = "1.0.163" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2113ab51b87a539ae008b5c6c02dc020ffa39afd2d83cffcb3f4eb2722cebec2" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.163" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c805777e3930c8883389c602315a24224bcc738b63905ef87cd1420353ea93e" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_test" version = "1.0.177" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f901ee573cab6b3060453d2d5f0bae4e6d628c23c0a962ff9b5f1d7c8d4f1ed" dependencies = [ "serde", ] [[package]] name = "syn" version = "2.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6f671d4b5ffdb8eadec19c0ae67fe2639df8684bd7bc4b83d986b8db549cf01" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicase" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" dependencies = [ "version_check", ] [[package]] name = "unicode-ident" version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" [[package]] name = "version_check" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "winnow" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e49d2d35d3fad69b39b94139037ecfb4f359f08958b9c11e7315ce770462419" dependencies = [ "memchr", ] git-conventional-0.12.9/Cargo.toml0000644000000106600000000000100124060ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.74" name = "git-conventional" version = "0.12.9" authors = [ "Ed Page ", "Jean Mertz ", ] build = false include = [ "build.rs", "src/**/*", "Cargo.toml", "Cargo.lock", "LICENSE*", "README.md", "benches/**/*", "examples/**/*", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A parser library for the Conventional Commit specification." homepage = "https://github.com/crate-ci/git-conventional" documentation = "http://docs.rs/git-conventional/" readme = "README.md" keywords = [ "parser", "git", "conventional-commit", "commit", "conventional", ] categories = ["parser-implementations"] license = "MIT OR Apache-2.0" repository = "https://github.com/crate-ci/git-conventional" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", "--generate-link-to-definition", ] [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" min = 1 replace = "{{version}}" search = "Unreleased" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = "...{{tag_name}}" search = '\.\.\.HEAD' [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" min = 1 replace = "{{date}}" search = "ReleaseDate" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = """ ## [Unreleased] - ReleaseDate """ search = "" [[package.metadata.release.pre-release-replacements]] exactly = 1 file = "CHANGELOG.md" replace = """ [Unreleased]: https://github.com/crate-ci/git-conventional/compare/{{tag_name}}...HEAD""" search = "" [features] [lib] name = "git_conventional" path = "src/lib.rs" [dependencies.serde] version = "1.0.163" features = ["derive"] optional = true [dependencies.unicase] version = "2.5" [dependencies.winnow] version = "0.7.0" [dev-dependencies.indoc] version = "2.0" [dev-dependencies.serde_test] version = "1.0" [lints.clippy] bool_assert_comparison = "allow" branches_sharing_code = "allow" checked_conversions = "warn" collapsible_else_if = "allow" create_dir = "warn" dbg_macro = "warn" debug_assert_with_mut_call = "warn" doc_markdown = "warn" empty_enum = "warn" enum_glob_use = "warn" expl_impl_clone_on_copy = "warn" explicit_deref_methods = "warn" explicit_into_iter_loop = "warn" fallible_impl_from = "warn" filter_map_next = "warn" flat_map_option = "warn" float_cmp_const = "warn" fn_params_excessive_bools = "warn" from_iter_instead_of_collect = "warn" if_same_then_else = "allow" implicit_clone = "warn" imprecise_flops = "warn" inconsistent_struct_constructor = "warn" inefficient_to_string = "warn" infinite_loop = "warn" invalid_upcast_comparisons = "warn" large_digit_groups = "warn" large_stack_arrays = "warn" large_types_passed_by_value = "warn" let_and_return = "allow" linkedlist = "warn" lossy_float_literal = "warn" macro_use_imports = "warn" mem_forget = "warn" mutex_integer = "warn" needless_continue = "warn" needless_for_each = "warn" negative_feature_names = "warn" path_buf_push_overwrite = "warn" ptr_as_ptr = "warn" rc_mutex = "warn" redundant_feature_names = "warn" ref_option_ref = "warn" rest_pat_in_fully_bound_structs = "warn" result_large_err = "allow" same_functions_in_if_condition = "warn" self_named_module_files = "warn" semicolon_if_nothing_returned = "warn" str_to_string = "warn" string_add = "warn" string_add_assign = "warn" string_lit_as_bytes = "warn" string_to_string = "warn" todo = "warn" trait_duplication_in_bounds = "warn" uninlined_format_args = "warn" verbose_file_reads = "warn" wildcard_imports = "warn" zero_sized_map_values = "warn" [lints.rust] unreachable_pub = "warn" unsafe_op_in_unsafe_fn = "warn" unused_lifetimes = "warn" unused_macro_rules = "warn" unused_qualifications = "warn" [lints.rust.rust_2018_idioms] level = "warn" priority = -1 git-conventional-0.12.9/Cargo.toml.orig000064400000000000000000000073521046102023000160730ustar 00000000000000[workspace] resolver = "2" [workspace.package] repository = "https://github.com/crate-ci/git-conventional" license = "MIT OR Apache-2.0" edition = "2021" rust-version = "1.74" # MSRV include = [ "build.rs", "src/**/*", "Cargo.toml", "Cargo.lock", "LICENSE*", "README.md", "benches/**/*", "examples/**/*" ] [workspace.lints.rust] rust_2018_idioms = { level = "warn", priority = -1 } unreachable_pub = "warn" unsafe_op_in_unsafe_fn = "warn" unused_lifetimes = "warn" unused_macro_rules = "warn" unused_qualifications = "warn" [workspace.lints.clippy] bool_assert_comparison = "allow" branches_sharing_code = "allow" checked_conversions = "warn" collapsible_else_if = "allow" create_dir = "warn" dbg_macro = "warn" debug_assert_with_mut_call = "warn" doc_markdown = "warn" empty_enum = "warn" enum_glob_use = "warn" expl_impl_clone_on_copy = "warn" explicit_deref_methods = "warn" explicit_into_iter_loop = "warn" fallible_impl_from = "warn" filter_map_next = "warn" flat_map_option = "warn" float_cmp_const = "warn" fn_params_excessive_bools = "warn" from_iter_instead_of_collect = "warn" if_same_then_else = "allow" implicit_clone = "warn" imprecise_flops = "warn" inconsistent_struct_constructor = "warn" inefficient_to_string = "warn" infinite_loop = "warn" invalid_upcast_comparisons = "warn" large_digit_groups = "warn" large_stack_arrays = "warn" large_types_passed_by_value = "warn" let_and_return = "allow" # sometimes good to name what you are returning linkedlist = "warn" lossy_float_literal = "warn" macro_use_imports = "warn" mem_forget = "warn" mutex_integer = "warn" needless_continue = "warn" needless_for_each = "warn" negative_feature_names = "warn" path_buf_push_overwrite = "warn" ptr_as_ptr = "warn" rc_mutex = "warn" redundant_feature_names = "warn" ref_option_ref = "warn" rest_pat_in_fully_bound_structs = "warn" result_large_err = "allow" same_functions_in_if_condition = "warn" self_named_module_files = "warn" semicolon_if_nothing_returned = "warn" str_to_string = "warn" string_add = "warn" string_add_assign = "warn" string_lit_as_bytes = "warn" string_to_string = "warn" todo = "warn" trait_duplication_in_bounds = "warn" uninlined_format_args = "warn" verbose_file_reads = "warn" wildcard_imports = "warn" zero_sized_map_values = "warn" [package] name = "git-conventional" version = "0.12.9" description = "A parser library for the Conventional Commit specification." authors = ["Ed Page ", "Jean Mertz "] homepage = "https://github.com/crate-ci/git-conventional" documentation = "http://docs.rs/git-conventional/" readme = "README.md" categories = ["parser-implementations"] keywords = ["parser", "git", "conventional-commit", "commit", "conventional"] repository.workspace = true license.workspace = true edition.workspace = true rust-version.workspace = true include.workspace = true [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs", "--generate-link-to-definition"] [package.metadata.release] pre-release-replacements = [ {file="CHANGELOG.md", search="Unreleased", replace="{{version}}", min=1}, {file="CHANGELOG.md", search="\\.\\.\\.HEAD", replace="...{{tag_name}}", exactly=1}, {file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}", min=1}, {file="CHANGELOG.md", search="", replace="\n## [Unreleased] - ReleaseDate\n", exactly=1}, {file="CHANGELOG.md", search="", replace="\n[Unreleased]: https://github.com/crate-ci/git-conventional/compare/{{tag_name}}...HEAD", exactly=1}, ] [features] [dependencies] winnow = "0.7.0" unicase = "2.5" serde = { version = "1.0.163", optional = true, features = ["derive"] } [dev-dependencies] indoc = "2.0" serde_test = "1.0" [lints] workspace = true git-conventional-0.12.9/LICENSE-APACHE000064400000000000000000000261361046102023000151310ustar 00000000000000 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. git-conventional-0.12.9/LICENSE-MIT000064400000000000000000000020461046102023000146330ustar 00000000000000Copyright (c) Individual contributors 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. git-conventional-0.12.9/README.md000064400000000000000000000030371046102023000144570ustar 00000000000000# `code>conventional::Commit` [![codecov](https://codecov.io/gh/crate-ci/git-conventional/branch/master/graph/badge.svg)](https://codecov.io/gh/crate-ci/git-conventional) [![Documentation](https://img.shields.io/badge/docs-master-blue.svg)][Documentation] ![License](https://img.shields.io/crates/l/git-conventional.svg) [![Crates Status](https://img.shields.io/crates/v/git-conventional.svg)][Crates.io] > A Rust parser library for the [Conventional Commit](https://www.conventionalcommits.org) spec. ## Quick Start 1. Add the crate to your `Cargo.toml`: ```console $ cargo add git_conventional ``` 2. Parse a commit and lookup what you need ```rust let commit = git_conventional::Commit::parse("feat(conventional commit): this is it!").unwrap(); assert_eq!(commit.type_(), git_conventional::Type::FEAT); assert_eq!(commit.scope().unwrap(), "conventional commit"); assert_eq!(commit.description(), "this is it!"); assert_eq!(commit.body(), None); ``` ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or ) * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [Crates.io]: https://crates.io/crates/git-conventional [Documentation]: https://docs.rs/git-conventional git-conventional-0.12.9/src/commit.rs000064400000000000000000000454671046102023000156420ustar 00000000000000//! The conventional commit type and its simple, and typed implementations. use std::fmt; use std::ops::Deref; use std::str::FromStr; use winnow::error::ContextError; use winnow::Parser; use crate::parser::parse; use crate::{Error, ErrorKind}; const BREAKING_PHRASE: &str = "BREAKING CHANGE"; const BREAKING_ARROW: &str = "BREAKING-CHANGE"; /// A conventional commit. #[cfg_attr(feature = "serde", derive(serde::Serialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct Commit<'a> { ty: Type<'a>, scope: Option>, description: &'a str, body: Option<&'a str>, breaking: bool, #[cfg_attr(feature = "serde", serde(skip))] breaking_description: Option<&'a str>, footers: Vec>, } impl<'a> Commit<'a> { /// Create a new Conventional Commit based on the provided commit message /// string. /// /// # Errors /// /// This function returns an error if the commit does not conform to the /// Conventional Commit specification. pub fn parse(string: &'a str) -> Result { let (ty, scope, breaking, description, body, footers) = parse:: .parse(string) .map_err(|err| Error::with_nom(string, err))?; let breaking_description = footers .iter() .find_map(|(k, _, v)| (k == &BREAKING_PHRASE || k == &BREAKING_ARROW).then_some(*v)) .or_else(|| breaking.then_some(description)); let breaking = breaking_description.is_some(); let footers: Result, Error> = footers .into_iter() .map(|(k, s, v)| Ok(Footer::new(FooterToken::new_unchecked(k), s.parse()?, v))) .collect(); let footers = footers?; Ok(Self { ty: Type::new_unchecked(ty), scope: scope.map(Scope::new_unchecked), description, body, breaking, breaking_description, footers, }) } /// The type of the commit. pub fn type_(&self) -> Type<'a> { self.ty } /// The optional scope of the commit. pub fn scope(&self) -> Option> { self.scope } /// The commit description. pub fn description(&self) -> &'a str { self.description } /// The commit body, containing a more detailed explanation of the commit /// changes. pub fn body(&self) -> Option<&'a str> { self.body } /// A flag to signal that the commit contains breaking changes. /// /// This flag is set either when the commit has an exclamation mark after /// the message type and scope, e.g.: /// ```text /// feat(scope)!: this is a breaking change /// ``` /// /// Or when the `BREAKING CHANGE: ` footer is defined: /// ```text /// feat: my commit description /// /// BREAKING CHANGE: this is a breaking change /// ``` pub fn breaking(&self) -> bool { self.breaking } /// Explanation for the breaking change. /// /// Note: if no `BREAKING CHANGE` footer is provided, the `description` is expected to describe /// the breaking change. pub fn breaking_description(&self) -> Option<&'a str> { self.breaking_description } /// Any footer. /// /// A footer is similar to a Git trailer, with the exception of not /// requiring whitespace before newlines. /// /// See: pub fn footers(&self) -> &[Footer<'a>] { &self.footers } } impl fmt::Display for Commit<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.type_().as_str())?; if let Some(scope) = &self.scope() { f.write_fmt(format_args!("({scope})"))?; } f.write_fmt(format_args!(": {}", &self.description()))?; if let Some(body) = &self.body() { f.write_fmt(format_args!("\n\n{body}"))?; } for footer in self.footers() { write!(f, "\n\n{footer}")?; } Ok(()) } } /// A single footer. /// /// A footer is similar to a Git trailer, with the exception of not requiring /// whitespace before newlines. /// /// See: #[cfg_attr(feature = "serde", derive(serde::Serialize))] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub struct Footer<'a> { token: FooterToken<'a>, sep: FooterSeparator, value: &'a str, } impl<'a> Footer<'a> { /// Piece together a footer. pub const fn new(token: FooterToken<'a>, sep: FooterSeparator, value: &'a str) -> Self { Self { token, sep, value } } /// The token of the footer. pub const fn token(&self) -> FooterToken<'a> { self.token } /// The separator between the footer token and its value. pub const fn separator(&self) -> FooterSeparator { self.sep } /// The value of the footer. pub const fn value(&self) -> &'a str { self.value } /// A flag to signal that the footer describes a breaking change. pub fn breaking(&self) -> bool { self.token.breaking() } } impl fmt::Display for Footer<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Self { token, sep, value } = self; write!(f, "{token}{sep}{value}") } } /// The type of separator between the footer token and value. #[cfg_attr(feature = "serde", derive(serde::Serialize))] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] #[non_exhaustive] pub enum FooterSeparator { /// ":" Value, /// " #" Ref, } impl FooterSeparator { /// Access `str` representation of `FooterSeparator` pub fn as_str(self) -> &'static str { match self { FooterSeparator::Value => ":", FooterSeparator::Ref => " #", } } } impl Deref for FooterSeparator { type Target = str; fn deref(&self) -> &Self::Target { self.as_str() } } impl PartialEq<&'_ str> for FooterSeparator { fn eq(&self, other: &&str) -> bool { self.as_str() == *other } } impl fmt::Display for FooterSeparator { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self) } } impl FromStr for FooterSeparator { type Err = Error; fn from_str(sep: &str) -> Result { match sep { ":" => Ok(FooterSeparator::Value), " #" => Ok(FooterSeparator::Ref), _ => { Err(Error::new(ErrorKind::InvalidFooter).set_context(Box::new(format!("{sep:?}")))) } } } } macro_rules! unicase_components { ($($ty:ident),+) => ( $( /// A component of the conventional commit. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct $ty<'a>(unicase::UniCase<&'a str>); impl<'a> $ty<'a> { /// See `parse` for ensuring the data is valid. pub const fn new_unchecked(value: &'a str) -> Self { $ty(unicase::UniCase::unicode(value)) } /// Access `str` representation pub fn as_str(&self) -> &'a str { &self.0.into_inner() } } impl Deref for $ty<'_> { type Target = str; fn deref(&self) -> &Self::Target { self.as_str() } } impl PartialEq<&'_ str> for $ty<'_> { fn eq(&self, other: &&str) -> bool { *self == $ty::new_unchecked(*other) } } impl fmt::Display for $ty<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } #[cfg(feature = "serde")] impl serde::Serialize for $ty<'_> { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { serializer.serialize_str(self) } } )+ ) } unicase_components![Type, Scope, FooterToken]; impl<'a> Type<'a> { /// Parse a `str` into a `Type`. pub fn parse(sep: &'a str) -> Result { let t = crate::parser::type_:: .parse(sep) .map_err(|err| Error::with_nom(sep, err))?; Ok(Type::new_unchecked(t)) } } /// Common commit types impl Type<'static> { /// Commit type when introducing new features (correlates with `minor` in semver) pub const FEAT: Type<'static> = Type::new_unchecked("feat"); /// Commit type when patching a bug (correlates with `patch` in semver) pub const FIX: Type<'static> = Type::new_unchecked("fix"); /// Possible commit type when reverting changes. pub const REVERT: Type<'static> = Type::new_unchecked("revert"); /// Possible commit type for changing documentation. pub const DOCS: Type<'static> = Type::new_unchecked("docs"); /// Possible commit type for changing code style. pub const STYLE: Type<'static> = Type::new_unchecked("style"); /// Possible commit type for refactoring code structure. pub const REFACTOR: Type<'static> = Type::new_unchecked("refactor"); /// Possible commit type for performance optimizations. pub const PERF: Type<'static> = Type::new_unchecked("perf"); /// Possible commit type for addressing tests. pub const TEST: Type<'static> = Type::new_unchecked("test"); /// Possible commit type for other things. pub const CHORE: Type<'static> = Type::new_unchecked("chore"); } impl<'a> Scope<'a> { /// Parse a `str` into a `Scope`. pub fn parse(sep: &'a str) -> Result { let t = crate::parser::scope:: .parse(sep) .map_err(|err| Error::with_nom(sep, err))?; Ok(Scope::new_unchecked(t)) } } impl<'a> FooterToken<'a> { /// Parse a `str` into a `FooterToken`. pub fn parse(sep: &'a str) -> Result { let t = crate::parser::token:: .parse(sep) .map_err(|err| Error::with_nom(sep, err))?; Ok(FooterToken::new_unchecked(t)) } /// A flag to signal that the footer describes a breaking change. pub fn breaking(&self) -> bool { self == &BREAKING_PHRASE || self == &BREAKING_ARROW } } #[cfg(test)] mod test { use super::*; use crate::ErrorKind; use indoc::indoc; #[cfg(feature = "serde")] use serde_test::Token; #[test] fn test_valid_simple_commit() { let commit = Commit::parse("type(my scope): hello world").unwrap(); assert_eq!(commit.type_(), "type"); assert_eq!(commit.scope().unwrap(), "my scope"); assert_eq!(commit.description(), "hello world"); } #[test] fn test_trailing_whitespace_without_body() { let commit = Commit::parse("type(my scope): hello world\n\n\n").unwrap(); assert_eq!(commit.type_(), "type"); assert_eq!(commit.scope().unwrap(), "my scope"); assert_eq!(commit.description(), "hello world"); } #[test] fn test_trailing_1_nl() { let commit = Commit::parse("type: hello world\n").unwrap(); assert_eq!(commit.type_(), "type"); assert_eq!(commit.scope(), None); assert_eq!(commit.description(), "hello world"); } #[test] fn test_trailing_2_nl() { let commit = Commit::parse("type: hello world\n\n").unwrap(); assert_eq!(commit.type_(), "type"); assert_eq!(commit.scope(), None); assert_eq!(commit.description(), "hello world"); } #[test] fn test_trailing_3_nl() { let commit = Commit::parse("type: hello world\n\n\n").unwrap(); assert_eq!(commit.type_(), "type"); assert_eq!(commit.scope(), None); assert_eq!(commit.description(), "hello world"); } #[test] fn test_parenthetical_statement() { let commit = Commit::parse("type: hello world (#1)").unwrap(); assert_eq!(commit.type_(), "type"); assert_eq!(commit.scope(), None); assert_eq!(commit.description(), "hello world (#1)"); } #[test] fn test_multiline_description() { let err = Commit::parse( "chore: Automate fastlane when a file in the fastlane directory is\nchanged (hopefully)", ).unwrap_err(); assert_eq!(ErrorKind::InvalidBody, err.kind()); } #[test] fn test_issue_12_case_1() { // Looks like it was test_trailing_2_nl that triggered this to fail originally let commit = Commit::parse("chore: add .hello.txt (#1)\n\n").unwrap(); assert_eq!(commit.type_(), "chore"); assert_eq!(commit.scope(), None); assert_eq!(commit.description(), "add .hello.txt (#1)"); } #[test] fn test_issue_12_case_2() { // Looks like it was test_trailing_2_nl that triggered this to fail originally let commit = Commit::parse("refactor: use fewer lines (#3)\n\n").unwrap(); assert_eq!(commit.type_(), "refactor"); assert_eq!(commit.scope(), None); assert_eq!(commit.description(), "use fewer lines (#3)"); } #[test] fn test_breaking_change() { let commit = Commit::parse("feat!: this is a breaking change").unwrap(); assert_eq!(Type::FEAT, commit.type_()); assert!(commit.breaking()); assert_eq!( commit.breaking_description(), Some("this is a breaking change") ); let commit = Commit::parse(indoc!( "feat: message BREAKING CHANGE: breaking change" )) .unwrap(); assert_eq!(Type::FEAT, commit.type_()); assert_eq!("breaking change", commit.footers().first().unwrap().value()); assert!(commit.breaking()); assert_eq!(commit.breaking_description(), Some("breaking change")); let commit = Commit::parse(indoc!( "fix: message BREAKING-CHANGE: it's broken" )) .unwrap(); assert_eq!(Type::FIX, commit.type_()); assert_eq!("it's broken", commit.footers().first().unwrap().value()); assert!(commit.breaking()); assert_eq!(commit.breaking_description(), Some("it's broken")); } #[test] fn test_conjoined_footer() { let commit = Commit::parse( "fix(example): fix keepachangelog config example Fixes: #123, #124, #125", ) .unwrap(); assert_eq!(Type::FIX, commit.type_()); assert_eq!(commit.body(), None); assert_eq!( commit.footers(), [Footer::new( FooterToken("Fixes".into()), FooterSeparator::Value, "#123, #124, #125" ),] ); } #[test] fn test_windows_line_endings() { let commit = Commit::parse("feat: thing\r\n\r\nbody\r\n\r\ncloses #1234\r\n\r\n\r\nBREAKING CHANGE: something broke\r\n\r\n") .unwrap(); assert_eq!(commit.body(), Some("body")); assert_eq!( commit.footers(), [ Footer::new(FooterToken("closes".into()), FooterSeparator::Ref, "1234"), Footer::new( FooterToken("BREAKING CHANGE".into()), FooterSeparator::Value, "something broke" ), ] ); assert_eq!(commit.breaking_description(), Some("something broke")); } #[test] fn test_extra_line_endings() { let commit = Commit::parse("feat: thing\n\n\n\n\nbody\n\n\n\n\ncloses #1234\n\n\n\n\n\nBREAKING CHANGE: something broke\n\n\n\n") .unwrap(); assert_eq!(commit.body(), Some("body")); assert_eq!( commit.footers(), [ Footer::new(FooterToken("closes".into()), FooterSeparator::Ref, "1234"), Footer::new( FooterToken("BREAKING CHANGE".into()), FooterSeparator::Value, "something broke" ), ] ); assert_eq!(commit.breaking_description(), Some("something broke")); } #[test] fn test_fake_footer() { let commit = indoc! {" fix: something something First line of the body IMPORTANT: Please see something else for details. Another line here. "}; let commit = Commit::parse(commit).unwrap(); assert_eq!(Type::FIX, commit.type_()); assert_eq!(None, commit.scope()); assert_eq!("something something", commit.description()); assert_eq!( Some(indoc!( " First line of the body IMPORTANT: Please see something else for details. Another line here." )), commit.body() ); let empty_footer: &[Footer<'_>] = &[]; assert_eq!(empty_footer, commit.footers()); } #[test] fn test_valid_complex_commit() { let commit = indoc! {" chore: improve changelog readability Change date notation from YYYY-MM-DD to YYYY.MM.DD to make it a tiny bit easier to parse while reading. BREAKING CHANGE: Just kidding! "}; let commit = Commit::parse(commit).unwrap(); assert_eq!(Type::CHORE, commit.type_()); assert_eq!(None, commit.scope()); assert_eq!("improve changelog readability", commit.description()); assert_eq!( Some(indoc!( "Change date notation from YYYY-MM-DD to YYYY.MM.DD to make it a tiny bit easier to parse while reading." )), commit.body() ); assert_eq!("Just kidding!", commit.footers().first().unwrap().value()); } #[test] fn test_missing_type() { let err = Commit::parse("").unwrap_err(); assert_eq!(ErrorKind::MissingType, err.kind()); } #[cfg(feature = "serde")] #[test] fn test_commit_serialize() { let commit = Commit::parse("type(my scope): hello world").unwrap(); serde_test::assert_ser_tokens( &commit, &[ Token::Struct { name: "Commit", len: 6, }, Token::Str("ty"), Token::Str("type"), Token::Str("scope"), Token::Some, Token::Str("my scope"), Token::Str("description"), Token::Str("hello world"), Token::Str("body"), Token::None, Token::Str("breaking"), Token::Bool(false), Token::Str("footers"), Token::Seq { len: Some(0) }, Token::SeqEnd, Token::StructEnd, ], ); } } git-conventional-0.12.9/src/error.rs000064400000000000000000000074441046102023000154740ustar 00000000000000//! All errors related to Conventional Commits. use std::fmt; /// The error returned when parsing a commit fails. pub struct Error { kind: ErrorKind, context: Option>, commit: Option, } impl Error { /// Create a new error from a `ErrorKind`. pub(crate) fn new(kind: ErrorKind) -> Self { Self { kind, context: None, commit: None, } } pub(crate) fn with_nom( commit: &str, err: winnow::error::ParseError<&str, winnow::error::ContextError>, ) -> Self { use winnow::error::StrContext; use ErrorKind::{ InvalidBody, InvalidFormat, InvalidScope, MissingDescription, MissingType, }; let mut kind = InvalidFormat; for context in err.inner().context() { kind = match context { StrContext::Label(string) => match *string { crate::parser::SUMMARY => MissingType, crate::parser::TYPE => MissingType, crate::parser::SCOPE => InvalidScope, crate::parser::DESCRIPTION => MissingDescription, crate::parser::BODY => InvalidBody, _ => kind, }, _ => kind, }; } Self { kind, context: None, commit: Some(commit.to_owned()), } } pub(crate) fn set_context(mut self, context: Box) -> Self { self.context = Some(context); self } /// The kind of error. pub fn kind(&self) -> ErrorKind { self.kind } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Error") .field("kind", &self.kind) .field("context", &self.context.as_ref().map(|s| s.to_string())) .field("commit", &self.commit) .finish() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(context) = self.context.as_ref() { write!(f, "{}: {}", self.kind, context) } else { write!(f, "{}", self.kind) } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } } /// All possible error kinds returned when parsing a conventional commit. #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum ErrorKind { /// The commit type is missing from the commit message. MissingType, /// The scope has an invalid format. InvalidScope, /// The description of the commit is missing. MissingDescription, /// The body of the commit has an invalid format. InvalidBody, /// The footer of the commit has an invalid format. InvalidFooter, /// Any other part of the commit does not conform to the conventional commit /// spec. InvalidFormat, } impl fmt::Display for ErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match self { ErrorKind::MissingType => { "Missing type in the commit summary, expected `type: description`" } ErrorKind::InvalidScope => { "Incorrect scope syntax in commit summary, expected `type(scope): description`" } ErrorKind::MissingDescription => { "Missing description in commit summary, expected `type: description`" } ErrorKind::InvalidBody => "Incorrect body syntax", ErrorKind::InvalidFooter => "Incorrect footer syntax", ErrorKind::InvalidFormat => "Incorrect conventional commit format", }; f.write_str(s) } } git-conventional-0.12.9/src/lib.rs000064400000000000000000000042071046102023000151030ustar 00000000000000//! A parser library for the [Conventional Commit] specification. //! //! [conventional commit]: https://www.conventionalcommits.org //! //! # Example //! //! ```rust //! use indoc::indoc; //! //! let message = indoc!(" //! docs(example)!: add tested usage example //! //! This example is tested using Rust's doctest capabilities. Having this //! example helps people understand how to use the parser. //! //! BREAKING CHANGE: Going from nothing to something, meaning anyone doing //! nothing before suddenly has something to do. That sounds like a change //! in your break. //! //! Co-Authored-By: Lisa Simpson //! Closes #12 //! "); //! //! let commit = git_conventional::Commit::parse(message).unwrap(); //! //! // You can access all components of the subject. //! assert_eq!(commit.type_(), git_conventional::Type::DOCS); //! assert_eq!(commit.scope().unwrap(), "example"); //! assert_eq!(commit.description(), "add tested usage example"); //! //! // And the free-form commit body. //! assert!(commit.body().unwrap().contains("helps people understand")); //! //! // If a commit is marked with a bang (`!`) OR has a footer with the key //! // "BREAKING CHANGE", it is considered a "breaking" commit. //! assert!(commit.breaking()); //! //! // You can access each footer individually. //! assert!(commit.footers()[0].value().contains("That sounds like a change")); //! //! // Footers provide access to their token and value. //! assert_eq!(commit.footers()[1].token(), "Co-Authored-By"); //! assert_eq!(commit.footers()[1].value(), "Lisa Simpson "); //! //! // Two types of separators are supported, regular ": ", and " #": //! assert_eq!(commit.footers()[2].separator(), " #"); //! assert_eq!(commit.footers()[2].value(), "12"); //! ``` #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![warn(missing_docs)] #![warn(clippy::print_stderr)] #![warn(clippy::print_stdout)] mod commit; mod error; mod lines; mod parser; pub use commit::{Commit, Footer, FooterSeparator, FooterToken, Scope, Type}; pub use error::{Error, ErrorKind}; #[doc = include_str!("../README.md")] #[cfg(doctest)] pub struct ReadmeDoctests; git-conventional-0.12.9/src/lines.rs000064400000000000000000000014101046102023000154400ustar 00000000000000#[derive(Clone, Debug)] pub(crate) struct LinesWithTerminator<'a> { data: &'a str, } impl<'a> LinesWithTerminator<'a> { pub(crate) fn new(data: &'a str) -> LinesWithTerminator<'a> { LinesWithTerminator { data } } } impl<'a> Iterator for LinesWithTerminator<'a> { type Item = &'a str; #[inline] fn next(&mut self) -> Option<&'a str> { match self.data.find('\n') { None if self.data.is_empty() => None, None => { let line = self.data; self.data = ""; Some(line) } Some(end) => { let line = &self.data[..end + 1]; self.data = &self.data[end + 1..]; Some(line) } } } } git-conventional-0.12.9/src/parser.rs000064400000000000000000000410041046102023000156250ustar 00000000000000#![allow(clippy::let_unit_value)] // for clarify and to ensure the right type is selected use std::str; use winnow::ascii::line_ending; use winnow::combinator::alt; use winnow::combinator::repeat; use winnow::combinator::trace; use winnow::combinator::{cut_err, eof, fail, opt, peek}; use winnow::combinator::{delimited, preceded, terminated}; use winnow::error::{AddContext, ErrMode, ParserError, StrContext}; use winnow::prelude::*; use winnow::token::{take, take_till, take_while}; type CommitDetails<'a> = ( &'a str, Option<&'a str>, bool, &'a str, Option<&'a str>, Vec<(&'a str, &'a str, &'a str)>, ); pub(crate) fn parse< 'a, E: ParserError<&'a str> + AddContext<&'a str, StrContext> + std::fmt::Debug, >( i: &mut &'a str, ) -> ModalResult, E> { message.parse_next(i) } // ::= "0x000D" // ::= "0x000A" // ::= [], fn is_line_ending(c: char) -> bool { c == '\n' || c == '\r' } // ::= "(" | ")" fn is_parens(c: char) -> bool { c == '(' || c == ')' } // ::= "U+FEFF" // ::= "U+0009" // ::= "U+000B" // ::= "U+000C" // ::= "U+0020" // ::= "U+00A0" // /* See: https://www.ecma-international.org/ecma-262/11.0/index.html#sec-white-space */ // ::= "Any other Unicode 'Space_Separator' code point" // /* Any non-newline whitespace: */ // ::= | | | | | | fn is_whitespace(c: char) -> bool { c.is_whitespace() } fn whitespace<'a, E: ParserError<&'a str> + AddContext<&'a str, StrContext> + std::fmt::Debug>( i: &mut &'a str, ) -> ModalResult<&'a str, E> { take_while(0.., is_whitespace).parse_next(i) } // ::= , +, , (+,