gix-mailmap-0.22.0/.cargo_vcs_info.json0000644000000001510000000000100133170ustar { "git": { "sha1": "eb6aa8f502314f886fc4ea3d52ab220763968208" }, "path_in_vcs": "gix-mailmap" }gix-mailmap-0.22.0/Cargo.toml0000644000000026320000000000100113230ustar # 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.65" name = "gix-mailmap" version = "0.22.0" authors = ["Sebastian Thiel "] include = [ "src/**/*", "LICENSE-*", ] description = "A crate of the gitoxide project for parsing mailmap files" license = "MIT OR Apache-2.0" repository = "https://github.com/Byron/gitoxide" [package.metadata.docs.rs] all-features = true features = ["document-features"] [lib] doctest = false [dependencies.bstr] version = "1.3.0" features = [ "std", "unicode", ] default-features = false [dependencies.document-features] version = "0.2.0" optional = true [dependencies.gix-actor] version = "^0.30.0" [dependencies.gix-date] version = "^0.8.3" [dependencies.serde] version = "1.0.114" features = ["derive"] optional = true default-features = false [dependencies.thiserror] version = "1.0.38" [dev-dependencies] [features] serde = [ "dep:serde", "bstr/serde", "gix-actor/serde", ] gix-mailmap-0.22.0/Cargo.toml.orig000064400000000000000000000020161046102023000150000ustar 00000000000000[package] name = "gix-mailmap" version = "0.22.0" repository = "https://github.com/Byron/gitoxide" license = "MIT OR Apache-2.0" description = "A crate of the gitoxide project for parsing mailmap files" authors = ["Sebastian Thiel "] edition = "2021" rust-version = "1.65" include = ["src/**/*", "LICENSE-*"] [lib] doctest = false [features] ## Data structures implement `serde::Serialize` and `serde::Deserialize`. serde= ["dep:serde", "bstr/serde", "gix-actor/serde"] [dependencies] gix-actor = { version = "^0.30.0", path = "../gix-actor" } gix-date = { version = "^0.8.3", path = "../gix-date" } bstr = { version = "1.3.0", default-features = false, features = ["std", "unicode"]} thiserror = "1.0.38" serde = { version = "1.0.114", optional = true, default-features = false, features = ["derive"]} document-features = { version = "0.2.0", optional = true } [dev-dependencies] gix-testtools = { path = "../tests/tools"} [package.metadata.docs.rs] all-features = true features = ["document-features"] gix-mailmap-0.22.0/LICENSE-APACHE000064400000000000000000000247461046102023000140530ustar 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 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. gix-mailmap-0.22.0/LICENSE-MIT000064400000000000000000000017771046102023000135620ustar 00000000000000Permission 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. gix-mailmap-0.22.0/src/entry.rs000064400000000000000000000040251046102023000144110ustar 00000000000000use bstr::BStr; use crate::Entry; /// Access impl<'a> Entry<'a> { /// The name to map to. pub fn new_name(&self) -> Option<&'a BStr> { self.new_name } /// The email map to. pub fn new_email(&self) -> Option<&'a BStr> { self.new_email } /// The name to look for and replace. pub fn old_name(&self) -> Option<&'a BStr> { self.old_name } /// The email to look for and replace. pub fn old_email(&self) -> &'a BStr { self.old_email } } /// Constructors indicating what kind of mapping is created. /// /// Only these combinations of values are valid. #[allow(missing_docs)] impl<'a> Entry<'a> { pub fn change_name_by_email(proper_name: impl Into<&'a BStr>, commit_email: impl Into<&'a BStr>) -> Self { Entry { new_name: Some(proper_name.into()), old_email: commit_email.into(), ..Default::default() } } pub fn change_email_by_email(proper_email: impl Into<&'a BStr>, commit_email: impl Into<&'a BStr>) -> Self { Entry { new_email: Some(proper_email.into()), old_email: commit_email.into(), ..Default::default() } } pub fn change_name_and_email_by_email( proper_name: impl Into<&'a BStr>, proper_email: impl Into<&'a BStr>, commit_email: impl Into<&'a BStr>, ) -> Self { Entry { new_name: Some(proper_name.into()), new_email: Some(proper_email.into()), old_email: commit_email.into(), ..Default::default() } } pub fn change_name_and_email_by_name_and_email( proper_name: impl Into<&'a BStr>, proper_email: impl Into<&'a BStr>, commit_name: impl Into<&'a BStr>, commit_email: impl Into<&'a BStr>, ) -> Self { Entry { new_name: Some(proper_name.into()), new_email: Some(proper_email.into()), old_name: Some(commit_name.into()), old_email: commit_email.into(), } } } gix-mailmap-0.22.0/src/lib.rs000064400000000000000000000042561046102023000140240ustar 00000000000000//! [Parse][parse()] .mailmap files as used in git repositories and remap names and emails //! using an [accelerated data-structure][Snapshot]. //! ## Feature Flags #![cfg_attr( all(doc, feature = "document-features"), doc = ::document_features::document_features!() )] #![cfg_attr(all(doc, feature = "document-features"), feature(doc_cfg, doc_auto_cfg))] #![deny(missing_docs, rust_2018_idioms)] #![forbid(unsafe_code)] use bstr::BStr; /// pub mod parse; /// Parse the given `buf` of bytes line by line into mapping [Entries][Entry]. /// /// Errors may occur per line, but it's up to the caller to stop iteration when /// one is encountered. pub fn parse(buf: &[u8]) -> parse::Lines<'_> { parse::Lines::new(buf) } /// Similar to [parse()], but will skip all lines that didn't parse correctly, silently squelching all errors. pub fn parse_ignore_errors(buf: &[u8]) -> impl Iterator> { parse(buf).filter_map(Result::ok) } mod entry; /// pub mod snapshot; /// A data-structure to efficiently store a list of entries for optimal, case-insensitive lookup by email and /// optionally name to find mappings to new names and/or emails. /// /// The memory layout is efficient, even though lots of small allocations are performed to store strings of emails and names. #[derive(Default, Clone)] pub struct Snapshot { /// Sorted by `old_email` entries_by_old_email: Vec, } /// An typical entry of a mailmap, which always contains an `old_email` by which /// the mapping is performed to replace the given `new_name` and `new_email`. /// /// Optionally, `old_name` is also used for lookup. /// /// Typically created by [parse()]. #[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Entry<'a> { #[cfg_attr(feature = "serde", serde(borrow))] /// The name to map to. pub(crate) new_name: Option<&'a BStr>, /// The email map to. pub(crate) new_email: Option<&'a BStr>, /// The name to look for and replace. pub(crate) old_name: Option<&'a BStr>, /// The email to look for and replace. pub(crate) old_email: &'a BStr, } gix-mailmap-0.22.0/src/parse.rs000064400000000000000000000074261046102023000143720ustar 00000000000000mod error { use bstr::BString; /// The error returned by [`parse()`][crate::parse()]. #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("Line {line_number} has too many names or emails, or none at all: {line:?}")] UnconsumedInput { line_number: usize, line: BString }, #[error("{line_number}: {line:?}: {message}")] Malformed { line_number: usize, line: BString, message: String, }, } } use bstr::{BStr, ByteSlice}; pub use error::Error; use crate::Entry; /// An iterator to parse mailmap lines on-demand. pub struct Lines<'a> { lines: bstr::Lines<'a>, line_no: usize, } impl<'a> Lines<'a> { pub(crate) fn new(input: &'a [u8]) -> Self { Lines { lines: input.as_bstr().lines(), line_no: 0, } } } impl<'a> Iterator for Lines<'a> { type Item = Result, Error>; fn next(&mut self) -> Option { for line in self.lines.by_ref() { self.line_no += 1; match line.first() { None => continue, Some(b) if *b == b'#' => continue, Some(_) => {} } let line = line.trim(); if line.is_empty() { continue; } return parse_line(line.into(), self.line_no).into(); } None } } fn parse_line(line: &BStr, line_number: usize) -> Result, Error> { let (name1, email1, rest) = parse_name_and_email(line, line_number)?; let (name2, email2, rest) = parse_name_and_email(rest, line_number)?; if !rest.trim().is_empty() { return Err(Error::UnconsumedInput { line_number, line: line.into(), }); } Ok(match (name1, email1, name2, email2) { (Some(proper_name), Some(commit_email), None, None) => Entry::change_name_by_email(proper_name, commit_email), (None, Some(proper_email), None, Some(commit_email)) => { Entry::change_email_by_email(proper_email, commit_email) } (Some(proper_name), Some(proper_email), None, Some(commit_email)) => { Entry::change_name_and_email_by_email(proper_name, proper_email, commit_email) } (Some(proper_name), Some(proper_email), Some(commit_name), Some(commit_email)) => { Entry::change_name_and_email_by_name_and_email(proper_name, proper_email, commit_name, commit_email) } _ => { return Err(Error::Malformed { line_number, line: line.into(), message: "Emails without a name or email to map to are invalid".into(), }) } }) } fn parse_name_and_email( line: &BStr, line_number: usize, ) -> Result<(Option<&'_ BStr>, Option<&'_ BStr>, &'_ BStr), Error> { match line.find_byte(b'<') { Some(start_bracket) => { let email = &line[start_bracket + 1..]; let closing_bracket = email.find_byte(b'>').ok_or_else(|| Error::Malformed { line_number, line: line.into(), message: "Missing closing bracket '>' in email".into(), })?; let email = email[..closing_bracket].trim().as_bstr(); if email.is_empty() { return Err(Error::Malformed { line_number, line: line.into(), message: "Email must not be empty".into(), }); } let name = line[..start_bracket].trim().as_bstr(); let rest = line[start_bracket + closing_bracket + 2..].as_bstr(); Ok(((!name.is_empty()).then_some(name), Some(email), rest)) } None => Ok((None, None, line)), } } gix-mailmap-0.22.0/src/snapshot/entry.rs000064400000000000000000000051121046102023000162460ustar 00000000000000use bstr::BString; use crate::snapshot::util::{EncodedString, EncodedStringRef}; #[derive(Clone)] pub(crate) struct NameEntry { pub(crate) new_name: Option, pub(crate) new_email: Option, pub(crate) old_name: EncodedString, } #[derive(Clone)] pub(crate) struct EmailEntry { pub(crate) new_name: Option, pub(crate) new_email: Option, pub(crate) old_email: EncodedString, pub(crate) entries_by_old_name: Vec, } impl EmailEntry { pub fn merge( &mut self, crate::Entry { new_name, new_email, old_name, old_email: _, }: crate::Entry<'_>, ) { let new_email = new_email.map(ToOwned::to_owned); let new_name = new_name.map(ToOwned::to_owned); match old_name { None => { self.new_email = new_email; self.new_name = new_name; } Some(old_name) => { let old_name: EncodedStringRef<'_> = old_name.into(); match self .entries_by_old_name .binary_search_by(|e| e.old_name.cmp_ref(old_name)) { Ok(pos) => { let entry = &mut self.entries_by_old_name[pos]; entry.new_name = new_name; entry.new_email = new_email; } Err(insert_pos) => self.entries_by_old_name.insert( insert_pos, NameEntry { new_name, new_email, old_name: old_name.into(), }, ), } } } } } impl<'a> From> for EmailEntry { fn from( crate::Entry { new_name, new_email, old_name, old_email, }: crate::Entry<'a>, ) -> Self { let mut new_name = new_name.map(ToOwned::to_owned); let mut new_email = new_email.map(ToOwned::to_owned); let entries_by_old_name = old_name .map(|name| { vec![NameEntry { new_name: new_name.take(), new_email: new_email.take(), old_name: name.into(), }] }) .unwrap_or_default(); EmailEntry { new_name, new_email, old_email: old_email.into(), entries_by_old_name, } } } gix-mailmap-0.22.0/src/snapshot/mod.rs000064400000000000000000000151561046102023000156750ustar 00000000000000use bstr::ByteSlice; use gix_actor::SignatureRef; use crate::Snapshot; mod signature; pub use signature::{ResolvedSignature, Signature}; mod util; use util::EncodedStringRef; mod entry; pub(crate) use entry::EmailEntry; impl Snapshot { /// Create a new snapshot from the given bytes buffer, ignoring all parse errors that may occur on a line-by-line basis. /// /// This is similar to what git does. pub fn from_bytes(buf: &[u8]) -> Self { Self::new(crate::parse_ignore_errors(buf)) } /// Create a new instance from `entries`. /// /// These can be obtained using [`crate::parse()`]. pub fn new<'a>(entries: impl IntoIterator>) -> Self { let mut snapshot = Self::default(); snapshot.merge(entries); snapshot } /// Merge the given `entries` into this instance, possibly overwriting existing mappings with /// new ones should they collide. pub fn merge<'a>(&mut self, entries: impl IntoIterator>) -> &mut Self { for entry in entries { let old_email: EncodedStringRef<'_> = entry.old_email.into(); assert!( entry.new_name.is_some() || entry.new_email.is_some(), "BUG: encountered entry without any mapped/new name or email." ); match self .entries_by_old_email .binary_search_by(|e| e.old_email.cmp_ref(old_email)) { Ok(pos) => self.entries_by_old_email[pos].merge(entry), Err(insert_pos) => { self.entries_by_old_email.insert(insert_pos, entry.into()); } }; } self } /// Transform our acceleration structure into a list of entries. /// /// Note that the order is different from how they were obtained initially, and are explicitly ordered by /// (`old_email`, `old_name`). pub fn entries(&self) -> Vec> { let mut out = Vec::with_capacity(self.entries_by_old_email.len()); for entry in &self.entries_by_old_email { if entry.new_email.is_some() || entry.new_name.is_some() { out.push(crate::Entry { new_name: entry.new_name.as_ref().map(|b| b.as_bstr()), new_email: entry.new_email.as_ref().map(|b| b.as_bstr()), old_name: None, old_email: entry.old_email.as_bstr(), }); } for name_entry in &entry.entries_by_old_name { out.push(crate::Entry { new_name: name_entry.new_name.as_ref().map(|b| b.as_bstr()), new_email: name_entry.new_email.as_ref().map(|b| b.as_bstr()), old_name: name_entry.old_name.as_bstr().into(), old_email: entry.old_email.as_bstr(), }); } } out } /// Try to resolve `signature` by its contained email and name and provide resolved/mapped names as reference. /// Return `None` if no such mapping was found. /// /// Note that opposed to what git seems to do, we also normalize the case of email addresses to match the one /// given in the mailmap. That is, if `Alex@example.com` is the current email, it will be matched and replaced with /// `alex@example.com`. This leads to better mapping results and saves entries in the mailmap. /// /// This is the fastest possible lookup as there is no allocation. pub fn try_resolve_ref(&self, signature: gix_actor::SignatureRef<'_>) -> Option> { let email: EncodedStringRef<'_> = signature.email.into(); let pos = self .entries_by_old_email .binary_search_by(|e| e.old_email.cmp_ref(email)) .ok()?; let entry = &self.entries_by_old_email[pos]; let name: EncodedStringRef<'_> = signature.name.into(); match entry.entries_by_old_name.binary_search_by(|e| e.old_name.cmp_ref(name)) { Ok(pos) => { let name_entry = &entry.entries_by_old_name[pos]; ResolvedSignature::try_new( name_entry.new_email.as_ref(), entry.old_email.as_bstr(), signature.email, name_entry.new_name.as_ref(), ) } Err(_) => ResolvedSignature::try_new( entry.new_email.as_ref(), entry.old_email.as_bstr(), signature.email, entry.new_name.as_ref(), ), } } /// Try to resolve `signature` by its contained email and name and provide resolved/mapped names as owned signature, /// with the mapped name and/or email replaced accordingly. /// /// Return `None` if no such mapping was found. pub fn try_resolve(&self, signature: gix_actor::SignatureRef<'_>) -> Option { self.try_resolve_ref(signature) .map(|new| enriched_signature(signature, new).into()) } /// Like [`try_resolve()`][Snapshot::try_resolve()], but always returns an owned signature, which might be a copy /// of `signature` if no mapping was found. /// /// Note that this method will always allocate. pub fn resolve(&self, signature: gix_actor::SignatureRef<'_>) -> gix_actor::Signature { self.try_resolve(signature).unwrap_or_else(|| signature.to_owned()) } /// Like [`try_resolve()`][Snapshot::try_resolve()], but always returns a special copy-on-write signature, which contains /// changed names or emails as `Cow::Owned`, or `Cow::Borrowed` if no mapping was found. pub fn resolve_cow<'a>(&self, signature: gix_actor::SignatureRef<'a>) -> Signature<'a> { self.try_resolve_ref(signature) .map_or_else(|| signature.into(), |new| enriched_signature(signature, new)) } } fn enriched_signature<'a>( SignatureRef { name, email, time }: SignatureRef<'a>, new: ResolvedSignature<'_>, ) -> Signature<'a> { match (new.email, new.name) { (Some(new_email), Some(new_name)) => Signature { email: new_email.to_owned().into(), name: new_name.to_owned().into(), time, }, (Some(new_email), None) => Signature { email: new_email.to_owned().into(), name: name.into(), time, }, (None, Some(new_name)) => Signature { email: email.into(), name: new_name.to_owned().into(), time, }, (None, None) => unreachable!("BUG: ResolvedSignatures don't exist here when nothing is set"), } } gix-mailmap-0.22.0/src/snapshot/signature.rs000064400000000000000000000036261046102023000171160ustar 00000000000000use std::borrow::Cow; use bstr::{BStr, BString, ByteSlice}; /// A signature like [`gix_actor::Signature`], but with all string fields being a `Cow`. #[derive(Default, PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Signature<'a> { /// The possibly mapped name. pub name: Cow<'a, BStr>, /// The possibly mapped email. pub email: Cow<'a, BStr>, /// The time stamp at which the signature is performed. pub time: gix_date::Time, } impl<'a> From> for gix_actor::Signature { fn from(s: Signature<'a>) -> Self { gix_actor::Signature { name: s.name.into_owned(), email: s.email.into_owned(), time: s.time, } } } impl<'a> From> for Signature<'a> { fn from(s: gix_actor::SignatureRef<'a>) -> Self { Signature { name: s.name.into(), email: s.email.into(), time: s.time, } } } /// A resolved signature with borrowed fields for a mapped `name` and/or `email`. pub struct ResolvedSignature<'a> { /// The mapped name. pub name: Option<&'a BStr>, /// The mapped email. pub email: Option<&'a BStr>, } impl<'a> ResolvedSignature<'a> { pub(crate) fn try_new( new_email: Option<&'a BString>, matched_email: &'a BStr, current_email: &'_ BStr, new_name: Option<&'a BString>, ) -> Option { let new_email = new_email .map(|n| n.as_bstr()) .or_else(|| (matched_email != current_email).then_some(matched_email)); match (new_email, new_name) { (None, None) => None, (new_email, new_name) => Some(ResolvedSignature { email: new_email.map(|v| v.as_bstr()), name: new_name.map(|v| v.as_bstr()), }), } } } gix-mailmap-0.22.0/src/snapshot/util.rs000064400000000000000000000057661046102023000161010ustar 00000000000000use std::{cmp::Ordering, ops::Deref}; use bstr::{BStr, BString, ByteSlice}; #[cfg_attr(test, derive(Debug))] #[derive(Clone)] pub enum EncodedString { Utf8(String), Unknown(BString), } impl EncodedString { pub fn as_bstr(&self) -> &BStr { match self { EncodedString::Utf8(v) => v.as_str().into(), EncodedString::Unknown(v) => v.as_bstr(), } } pub fn cmp_ref(&self, other: EncodedStringRef<'_>) -> Ordering { match (self, other) { (EncodedString::Utf8(a), EncodedStringRef::Utf8(b)) => { let a = a.chars().map(|c| c.to_ascii_lowercase()); let b = b.chars().map(|c| c.to_ascii_lowercase()); a.cmp(b) } (EncodedString::Unknown(a), EncodedStringRef::Unknown(b)) => a.deref().as_bstr().cmp(b), (EncodedString::Utf8(a), EncodedStringRef::Unknown(b)) => a.as_bytes().cmp(b.as_ref()), (EncodedString::Unknown(a), EncodedStringRef::Utf8(b)) => a.deref().as_bytes().cmp(b.as_bytes()), } } } #[cfg_attr(test, derive(Debug))] #[derive(Clone, Copy)] pub enum EncodedStringRef<'a> { Utf8(&'a str), Unknown(&'a BStr), } impl<'a> From<&'a BStr> for EncodedStringRef<'a> { fn from(v: &'a BStr) -> Self { match v.to_str() { Ok(v) => EncodedStringRef::Utf8(v), Err(_) => EncodedStringRef::Unknown(v), } } } impl<'a> From> for EncodedString { fn from(v: EncodedStringRef<'a>) -> Self { match v { EncodedStringRef::Utf8(v) => EncodedString::Utf8(v.to_owned()), EncodedStringRef::Unknown(v) => EncodedString::Unknown(v.to_owned()), } } } impl<'a> From<&'a BStr> for EncodedString { fn from(v: &'a BStr) -> Self { match v.to_str() { Ok(v) => EncodedString::Utf8(v.to_owned()), Err(_) => EncodedString::Unknown(v.to_owned()), } } } #[cfg(test)] mod encoded_string { use std::cmp::Ordering; use crate::snapshot::util::{EncodedString, EncodedStringRef}; #[test] fn basic_ascii_case_folding() { assert_eq!( EncodedString::Utf8("FooBar".into()).cmp_ref(EncodedStringRef::Utf8("foobar")), Ordering::Equal ); } #[test] fn no_advanced_unicode_folding() { assert_ne!( EncodedString::Utf8("Masse".into()).cmp_ref(EncodedStringRef::Utf8("Maße")), Ordering::Equal ); } #[test] fn unknown_encoding_pairs_do_not_try_to_ignore_cases() { assert_ne!( EncodedString::Utf8("Foo".into()).cmp_ref(EncodedStringRef::Unknown("foo".into())), Ordering::Equal ); assert_ne!( EncodedString::Unknown("Foo".into()).cmp_ref(EncodedStringRef::Utf8("foo")), Ordering::Equal ); assert_ne!( EncodedString::Unknown("Foo".into()).cmp_ref(EncodedStringRef::Unknown("foo".into())), Ordering::Equal ); } }