gix-validate-0.8.5/.cargo_vcs_info.json0000644000000001520000000000100134220ustar { "git": { "sha1": "4f98e94e0e8b79ed2899b35bef40f3c30b3025b0" }, "path_in_vcs": "gix-validate" }gix-validate-0.8.5/Cargo.toml0000644000000021660000000000100114270ustar # 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-validate" version = "0.8.5" authors = ["Sebastian Thiel "] build = false include = [ "src/**/*", "LICENSE-*", ] autobins = false autoexamples = false autotests = false autobenches = false description = "Validation functions for various kinds of names in git" readme = false license = "MIT OR Apache-2.0" repository = "https://github.com/Byron/gitoxide" [lib] name = "gix_validate" path = "src/lib.rs" test = true doctest = false [dependencies.bstr] version = "1.3.0" features = ["std"] default-features = false [dependencies.thiserror] version = "1.0.34" [dev-dependencies] gix-validate-0.8.5/Cargo.toml.orig000064400000000000000000000010411046102023000150770ustar 00000000000000[package] name = "gix-validate" version = "0.8.5" repository = "https://github.com/Byron/gitoxide" license = "MIT OR Apache-2.0" description = "Validation functions for various kinds of names in git" authors = ["Sebastian Thiel "] edition = "2021" include = ["src/**/*", "LICENSE-*"] rust-version = "1.65" [lib] doctest = false test = true [dependencies] thiserror = "1.0.34" bstr = { version = "1.3.0", default-features = false, features = ["std"] } [dev-dependencies] gix-testtools = { path = "../tests/tools" } gix-validate-0.8.5/LICENSE-APACHE000064400000000000000000000247461046102023000141550ustar 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-validate-0.8.5/LICENSE-MIT000064400000000000000000000017771046102023000136640ustar 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-validate-0.8.5/src/lib.rs000064400000000000000000000005011046102023000141130ustar 00000000000000//! Validation for various kinds of git related items. #![deny(missing_docs, rust_2018_idioms)] #![forbid(unsafe_code)] /// #[allow(clippy::empty_docs)] pub mod reference; /// #[allow(clippy::empty_docs)] pub mod tag; /// #[allow(clippy::empty_docs)] pub mod submodule; /// #[allow(clippy::empty_docs)] pub mod path; gix-validate-0.8.5/src/path.rs000064400000000000000000000306241046102023000143120ustar 00000000000000use bstr::{BStr, ByteSlice}; /// #[allow(clippy::empty_docs)] pub mod component { /// The error returned by [`component()`](super::component()). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("A path component must not be empty")] Empty, #[error("Path separators like / or \\ are not allowed")] PathSeparator, #[error("Windows path prefixes are not allowed")] WindowsPathPrefix, #[error("Windows device-names may have side-effects and are not allowed")] WindowsReservedName, #[error("Trailing spaces or dots, and the following characters anywhere, are forbidden in Windows paths, along with non-printable ones: <>:\"|?*")] WindowsIllegalCharacter, #[error("The .git name may never be used")] DotGitDir, #[error("The .gitmodules file must not be a symlink")] SymlinkedGitModules, } /// Further specify what to check for in [`component()`](super::component()) /// /// Note that the `Default` implementation maximizes safety by enabling all protections. #[derive(Debug, Copy, Clone)] pub struct Options { /// This flag should be turned on when on Windows, but can be turned on when on other platforms /// as well to prevent path components that can cause trouble on Windows. pub protect_windows: bool, /// If `true`, protections for the MacOS HFS+ filesystem will be active, checking for /// special directories that we should never write while ignoring codepoints just like HFS+ would. /// /// This field is equivalent to `core.protectHFS`. pub protect_hfs: bool, /// If `true`, protections for Windows NTFS specific features will be active. This adds special handling /// for `8.3` filenames and alternate data streams, both of which could be used to mask the true name of /// what would be created on disk. /// /// This field is equivalent to `core.protectNTFS`. pub protect_ntfs: bool, } impl Default for Options { fn default() -> Self { Options { protect_windows: true, protect_hfs: true, protect_ntfs: true, } } } /// The mode of the component, if it's the leaf of a path. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Mode { /// The item is a symbolic link. Symlink, } } /// Assure the given `input` resembles a valid name for a tree or blob, and in that sense, a path component. /// `mode` indicates the kind of `input` and it should be `Some` if `input` is the last component in the underlying /// path. /// /// `input` must not make it possible to exit the repository, or to specify absolute paths. pub fn component( input: &BStr, mode: Option, component::Options { protect_windows, protect_hfs, protect_ntfs, }: component::Options, ) -> Result<&BStr, component::Error> { if input.is_empty() { return Err(component::Error::Empty); } if protect_windows { if input.find_byteset(b"/\\").is_some() { return Err(component::Error::PathSeparator); } if input.chars().nth(1) == Some(':') { return Err(component::Error::WindowsPathPrefix); } } else if input.find_byte(b'/').is_some() { return Err(component::Error::PathSeparator); } if protect_hfs { if is_dot_hfs(input, "git") { return Err(component::Error::DotGitDir); } if is_symlink(mode) && is_dot_hfs(input, "gitmodules") { return Err(component::Error::SymlinkedGitModules); } } if protect_ntfs { if is_dot_git_ntfs(input) { return Err(component::Error::DotGitDir); } if is_symlink(mode) && is_dot_ntfs(input, "gitmodules", "gi7eba") { return Err(component::Error::SymlinkedGitModules); } if protect_windows { if let Some(err) = check_win_devices_and_illegal_characters(input) { return Err(err); } } } if !(protect_hfs | protect_ntfs) { if input.eq_ignore_ascii_case(b".git") { return Err(component::Error::DotGitDir); } if is_symlink(mode) && input.eq_ignore_ascii_case(b".gitmodules") { return Err(component::Error::SymlinkedGitModules); } } Ok(input) } /// Return `true` if the path component at `input` looks like a Windows device, like `CON` /// or `LPT1` (case-insensitively). /// /// This is relevant only on Windows, where one may be tricked into reading or writing to such devices. /// When reading from `CON`, a console-program may block until the user provided input. pub fn component_is_windows_device(input: &BStr) -> bool { is_win_device(input) } fn is_win_device(input: &BStr) -> bool { let Some(in3) = input.get(..3) else { return false }; if in3.eq_ignore_ascii_case(b"AUX") && is_done_windows(input.get(3..)) { return true; } if in3.eq_ignore_ascii_case(b"NUL") && is_done_windows(input.get(3..)) { return true; } if in3.eq_ignore_ascii_case(b"PRN") && is_done_windows(input.get(3..)) { return true; } // Note that the following allows `COM0`, even though `LPT0` is not allowed. // Even though tests seem to indicate that neither `LPT0` nor `COM0` are valid // device names, it's unclear this truly is the case in all possible versions and editions // of Windows. // Hence, justification for this asymmetry is merely to do exactly the same as Git does, // and to have exactly the same behaviour during validation (for worktree-writes). if in3.eq_ignore_ascii_case(b"COM") && input.get(3).map_or(false, |n| *n >= b'1' && *n <= b'9') && is_done_windows(input.get(4..)) { return true; } if in3.eq_ignore_ascii_case(b"LPT") && input.get(3).map_or(false, u8::is_ascii_digit) && is_done_windows(input.get(4..)) { return true; } if in3.eq_ignore_ascii_case(b"CON") && (is_done_windows(input.get(3..)) || (input.get(3..6).map_or(false, |n| n.eq_ignore_ascii_case(b"IN$")) && is_done_windows(input.get(6..))) || (input.get(3..7).map_or(false, |n| n.eq_ignore_ascii_case(b"OUT$")) && is_done_windows(input.get(7..)))) { return true; } false } fn check_win_devices_and_illegal_characters(input: &BStr) -> Option { if is_win_device(input) { return Some(component::Error::WindowsReservedName); } if input.iter().any(|b| *b < 0x20 || b":<>\"|?*".contains(b)) { return Some(component::Error::WindowsIllegalCharacter); } if input.ends_with(b".") || input.ends_with(b" ") { return Some(component::Error::WindowsIllegalCharacter); } None } fn is_symlink(mode: Option) -> bool { mode.map_or(false, |m| m == component::Mode::Symlink) } fn is_dot_hfs(input: &BStr, search_case_insensitive: &str) -> bool { let mut input = input.chars().filter(|c| match *c as u32 { // Case-insensitive HFS+ skips these code points as "ignorable" when comparing filenames. See: // https://github.com/git/git/commit/6162a1d323d24fd8cbbb1a6145a91fb849b2568f // https://developer.apple.com/library/archive/technotes/tn/tn1150.html#StringComparisonAlgorithm // https://github.com/apple-oss-distributions/hfs/blob/main/core/UCStringCompareData.h 0x200c | // ZERO WIDTH NON-JOINER 0x200d | // ZERO WIDTH JOINER 0x200e | // LEFT-TO-RIGHT MARK 0x200f | // RIGHT-TO-LEFT MARK 0x202a | // LEFT-TO-RIGHT EMBEDDING 0x202b | // RIGHT-TO-LEFT EMBEDDING 0x202c | // POP DIRECTIONAL FORMATTING 0x202d | // LEFT-TO-RIGHT OVERRIDE 0x202e | // RIGHT-TO-LEFT OVERRIDE 0x206a | // INHIBIT SYMMETRIC SWAPPING 0x206b | // ACTIVATE SYMMETRIC SWAPPING 0x206c | // INHIBIT ARABIC FORM SHAPING 0x206d | // ACTIVATE ARABIC FORM SHAPING 0x206e | // NATIONAL DIGIT SHAPES 0x206f | // NOMINAL DIGIT SHAPES 0xfeff => false, // ZERO WIDTH NO-BREAK SPACE _ => true }); if input.next() != Some('.') { return false; } let mut comp = search_case_insensitive.chars(); loop { match (comp.next(), input.next()) { (Some(a), Some(b)) => { if !a.eq_ignore_ascii_case(&b) { return false; } } (None, None) => return true, _ => return false, } } } fn is_dot_git_ntfs(input: &BStr) -> bool { if input .get(..4) .map_or(false, |input| input.eq_ignore_ascii_case(b".git")) { return is_done_ntfs(input.get(4..)); } if input .get(..5) .map_or(false, |input| input.eq_ignore_ascii_case(b"git~1")) { return is_done_ntfs(input.get(5..)); } false } /// The `search_case_insensitive` name is the actual name to look for (in a case-insensitive way). /// Opposed to that there is the special `ntfs_shortname_prefix` which is derived from `search_case_insensitive` /// but looks more like a hash, one that NTFS uses to disambiguate things, for when there is a lot of files /// with the same prefix. fn is_dot_ntfs(input: &BStr, search_case_insensitive: &str, ntfs_shortname_prefix: &str) -> bool { if input.first() == Some(&b'.') { let end_pos = 1 + search_case_insensitive.len(); if input.get(1..end_pos).map_or(false, |input| { input.eq_ignore_ascii_case(search_case_insensitive.as_bytes()) }) { is_done_ntfs(input.get(end_pos..)) } else { false } } else { let search_case_insensitive: &[u8] = search_case_insensitive.as_bytes(); if search_case_insensitive .get(..6) .zip(input.get(..6)) .map_or(false, |(ntfs_prefix, first_6_of_input)| { first_6_of_input.eq_ignore_ascii_case(ntfs_prefix) && input.get(6) == Some(&b'~') // It's notable that only `~1` to `~4` are possible before the disambiguation algorithm // switches to using the `ntfs_shortname_prefix`, which is checked hereafter. && input.get(7).map_or(false, |num| (b'1'..=b'4').contains(num)) }) { return is_done_ntfs(input.get(8..)); } let ntfs_shortname_prefix: &[u8] = ntfs_shortname_prefix.as_bytes(); let mut saw_tilde = false; let mut pos = 0; while pos < 8 { let Some(b) = input.get(pos).copied() else { return false; }; if saw_tilde { if !b.is_ascii_digit() { return false; } } else if b == b'~' { saw_tilde = true; pos += 1; let Some(b) = input.get(pos).copied() else { return false; }; if !(b'1'..=b'9').contains(&b) { return false; } } else if pos >= 6 || b & 0x80 == 0x80 || ntfs_shortname_prefix .get(pos) .map_or(true, |ob| !b.eq_ignore_ascii_case(ob)) { return false; } pos += 1; } is_done_ntfs(input.get(pos..)) } } /// Check if trailing filename bytes leave a match to special files like `.git` unchanged in NTFS. fn is_done_ntfs(input: Option<&[u8]>) -> bool { // Skip spaces and dots. Then return true if we are at the end or a colon. let Some(input) = input else { return true }; for b in input.bytes() { if b == b':' { return true; } if b != b' ' && b != b'.' { return false; } } true } /// Check if trailing filename bytes leave a match to Windows reserved device names unchanged. fn is_done_windows(input: Option<&[u8]>) -> bool { // Skip spaces. Then return true if we are at the end or a dot or colon. let Some(input) = input else { return true }; let skip = input.bytes().take_while(|b| *b == b' ').count(); let Some(next) = input.get(skip) else { return true }; *next == b'.' || *next == b':' } gix-validate-0.8.5/src/reference.rs000064400000000000000000000046271046102023000153200ustar 00000000000000/// #[allow(clippy::empty_docs)] pub mod name { use std::convert::Infallible; /// The error used in [name()][super::name()] and [`name_partial()`][super::name_partial()] #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("A reference must be a valid tag name as well")] Tag(#[from] crate::tag::name::Error), #[error("Standalone references must be all uppercased, like 'HEAD'")] SomeLowercase, #[error("A reference name must not start with a slash '/'")] StartsWithSlash, #[error("Multiple slashes in a row are not allowed as they may change the reference's meaning")] RepeatedSlash, #[error("Names must not be a single '.', but may contain it.")] SingleDot, } impl From for Error { fn from(_: Infallible) -> Self { unreachable!("this impl is needed to allow passing a known valid partial path as parameter") } } } use bstr::BStr; /// Validate a reference name running all the tests in the book. This disallows lower-case references, but allows /// ones like `HEAD`. pub fn name(path: &BStr) -> Result<&BStr, name::Error> { validate(path, Mode::Complete) } /// Validate a partial reference name. As it is assumed to be partial, names like `some-name` is allowed /// even though these would be disallowed with when using [`name()`]. pub fn name_partial(path: &BStr) -> Result<&BStr, name::Error> { validate(path, Mode::Partial) } enum Mode { Complete, Partial, } fn validate(path: &BStr, mode: Mode) -> Result<&BStr, name::Error> { crate::tag::name(path)?; if path[0] == b'/' { return Err(name::Error::StartsWithSlash); } let mut previous = 0; let mut one_before_previous = 0; let mut saw_slash = false; for byte in path.iter() { match *byte { b'/' if previous == b'.' && one_before_previous == b'/' => return Err(name::Error::SingleDot), b'/' if previous == b'/' => return Err(name::Error::RepeatedSlash), _ => {} } if *byte == b'/' { saw_slash = true; } one_before_previous = previous; previous = *byte; } if let Mode::Complete = mode { if !saw_slash && !path.iter().all(|c| c.is_ascii_uppercase() || *c == b'_') { return Err(name::Error::SomeLowercase); } } Ok(path) } gix-validate-0.8.5/src/submodule.rs000064400000000000000000000016471046102023000153600ustar 00000000000000use bstr::{BStr, ByteSlice}; /// #[allow(clippy::empty_docs)] pub mod name { /// The error used in [name()](super::name()). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("Submodule names cannot be empty")] Empty, #[error("Submodules names must not contains '..'")] ParentComponent, } } /// Return the original `name` if it is valid, or the respective error indicating what was wrong with it. pub fn name(name: &BStr) -> Result<&BStr, name::Error> { if name.is_empty() { return Err(name::Error::Empty); } match name.find(b"..") { Some(pos) => { let &b = name.get(pos + 2).ok_or(name::Error::ParentComponent)?; if b == b'/' || b == b'\\' { Err(name::Error::ParentComponent) } else { Ok(name) } } None => Ok(name), } } gix-validate-0.8.5/src/tag.rs000064400000000000000000000037661046102023000141400ustar 00000000000000use bstr::BStr; /// #[allow(clippy::empty_docs)] pub mod name { use bstr::BString; /// The error returned by [`name()`][super::name()]. #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("A ref must not contain invalid bytes or ascii control characters: {byte:?}")] InvalidByte { byte: BString }, #[error("A ref must not contain '..' as it may be mistaken for a range")] DoubleDot, #[error("A ref must not end with '.lock'")] LockFileSuffix, #[error("A ref must not contain '@{{' which is a part of a ref-log")] ReflogPortion, #[error("A ref must not contain '*' character")] Asterisk, #[error("A ref must not start with a '.'")] StartsWithDot, #[error("A ref must not end with a '/'")] EndsWithSlash, #[error("A ref must not be empty")] Empty, } } /// Assure the given `input` resemble a valid git tag name, which is returned unchanged on success. pub fn name(input: &BStr) -> Result<&BStr, name::Error> { if input.is_empty() { return Err(name::Error::Empty); } if *input.last().expect("non-empty") == b'/' { return Err(name::Error::EndsWithSlash); } let mut previous = 0; for byte in input.iter() { match byte { b'\\' | b'^' | b':' | b'[' | b'?' | b' ' | b'~' | b'\0'..=b'\x1F' | b'\x7F' => { return Err(name::Error::InvalidByte { byte: (&[*byte][..]).into(), }) } b'*' => return Err(name::Error::Asterisk), b'.' if previous == b'.' => return Err(name::Error::DoubleDot), b'{' if previous == b'@' => return Err(name::Error::ReflogPortion), _ => {} } previous = *byte; } if input[0] == b'.' { return Err(name::Error::StartsWithDot); } if input.ends_with(b".lock") { return Err(name::Error::LockFileSuffix); } Ok(input) }