gix-submodule-0.16.0/.cargo_vcs_info.json0000644000000001530000000000100137030ustar { "git": { "sha1": "4000197ecc8cf1a5d79361620e4c114f86476703" }, "path_in_vcs": "gix-submodule" }gix-submodule-0.16.0/Cargo.toml0000644000000065370000000000100117150ustar # 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-submodule" version = "0.16.0" authors = ["Sebastian Thiel "] build = false include = [ "src/**/*", "LICENSE-*", ] autobins = false autoexamples = false autotests = false autobenches = false description = "A crate of the gitoxide project dealing git submodules" readme = false license = "MIT OR Apache-2.0" repository = "https://github.com/GitoxideLabs/gitoxide" [lib] name = "gix_submodule" path = "src/lib.rs" doctest = false [dependencies.bstr] version = "1.5.0" default-features = false [dependencies.gix-config] version = "^0.42.0" [dependencies.gix-path] version = "^0.10.13" [dependencies.gix-pathspec] version = "^0.8.1" [dependencies.gix-refspec] version = "^0.27.0" [dependencies.gix-url] version = "^0.28.1" [dependencies.thiserror] version = "2.0.0" [dev-dependencies] [lints.clippy] bool_to_int_with_if = "allow" borrow_as_ptr = "allow" cast_lossless = "allow" cast_possible_truncation = "allow" cast_possible_wrap = "allow" cast_precision_loss = "allow" cast_sign_loss = "allow" checked_conversions = "allow" copy_iterator = "allow" default_trait_access = "allow" doc_markdown = "allow" empty_docs = "allow" enum_glob_use = "allow" explicit_deref_methods = "allow" explicit_into_iter_loop = "allow" explicit_iter_loop = "allow" filter_map_next = "allow" fn_params_excessive_bools = "allow" from_iter_instead_of_collect = "allow" if_not_else = "allow" ignored_unit_patterns = "allow" implicit_clone = "allow" inconsistent_struct_constructor = "allow" inefficient_to_string = "allow" inline_always = "allow" items_after_statements = "allow" iter_not_returning_iterator = "allow" iter_without_into_iter = "allow" manual_assert = "allow" manual_is_variant_and = "allow" manual_let_else = "allow" manual_string_new = "allow" many_single_char_names = "allow" match_bool = "allow" match_same_arms = "allow" match_wild_err_arm = "allow" match_wildcard_for_single_variants = "allow" missing_errors_doc = "allow" missing_panics_doc = "allow" module_name_repetitions = "allow" must_use_candidate = "allow" mut_mut = "allow" naive_bytecount = "allow" needless_for_each = "allow" needless_pass_by_value = "allow" needless_raw_string_hashes = "allow" no_effect_underscore_binding = "allow" option_option = "allow" range_plus_one = "allow" redundant_else = "allow" return_self_not_must_use = "allow" should_panic_without_expect = "allow" similar_names = "allow" single_match_else = "allow" stable_sort_primitive = "allow" struct_excessive_bools = "allow" struct_field_names = "allow" too_long_first_doc_paragraph = "allow" too_many_lines = "allow" transmute_ptr_to_ptr = "allow" trivially_copy_pass_by_ref = "allow" unnecessary_join = "allow" unnecessary_wraps = "allow" unreadable_literal = "allow" unused_self = "allow" used_underscore_binding = "allow" wildcard_imports = "allow" [lints.clippy.pedantic] level = "warn" priority = -1 [lints.rust] gix-submodule-0.16.0/Cargo.toml.orig000064400000000000000000000016231046102023000153650ustar 00000000000000lints.workspace = true [package] name = "gix-submodule" version = "0.16.0" repository = "https://github.com/GitoxideLabs/gitoxide" license = "MIT OR Apache-2.0" description = "A crate of the gitoxide project dealing git submodules" authors = ["Sebastian Thiel "] edition = "2021" rust-version = "1.65" include = ["src/**/*", "LICENSE-*"] [lib] doctest = false [dependencies] gix-pathspec = { version = "^0.8.1", path = "../gix-pathspec" } gix-refspec = { version = "^0.27.0", path = "../gix-refspec" } gix-config = { version = "^0.42.0", path = "../gix-config" } gix-path = { version = "^0.10.13", path = "../gix-path" } gix-url = { version = "^0.28.1", path = "../gix-url" } bstr = { version = "1.5.0", default-features = false } thiserror = "2.0.0" [dev-dependencies] gix-testtools = { path = "../tests/tools" } gix-features = { path = "../gix-features", features = ["walkdir"] } gix-submodule-0.16.0/LICENSE-APACHE000064400000000000000000000247461046102023000144350ustar 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-submodule-0.16.0/LICENSE-MIT000064400000000000000000000017771046102023000141440ustar 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-submodule-0.16.0/src/access.rs000064400000000000000000000237341046102023000151030ustar 00000000000000use std::{borrow::Cow, collections::HashSet, path::Path}; use bstr::BStr; use crate::{ config, config::{Branch, FetchRecurse, Ignore, Update}, File, IsActivePlatform, }; /// High-Level Access /// /// Note that all methods perform validation of the requested value and report issues right away. /// If a bypass is needed, use [`config()`](File::config()) for direct access. impl File { /// Return the underlying configuration file. /// /// Note that it might have been merged with values from another configuration file and may /// thus not be accurately reflecting that state of a `.gitmodules` file anymore. pub fn config(&self) -> &gix_config::File<'static> { &self.config } /// Return the path at which the `.gitmodules` file lives, if it is known. pub fn config_path(&self) -> Option<&Path> { self.config.sections().filter_map(|s| s.meta().path.as_deref()).next() } /// Return the unvalidated names of the submodules for which configuration is present. /// /// Note that these exact names have to be used for querying submodule values. pub fn names(&self) -> impl Iterator { let mut seen = HashSet::<&BStr>::default(); self.config .sections_by_name("submodule") .into_iter() .flatten() .filter_map(move |s| { s.header() .subsection_name() .filter(|_| s.meta().source == crate::init::META_MARKER) .filter(|name| seen.insert(*name)) }) } /// Similar to [Self::is_active_platform()], but automatically applies it to each name to learn if a submodule is active or not. pub fn names_and_active_state<'a>( &'a self, config: &'a gix_config::File<'static>, defaults: gix_pathspec::Defaults, attributes: &'a mut (dyn FnMut( &BStr, gix_pathspec::attributes::glob::pattern::Case, bool, &mut gix_pathspec::attributes::search::Outcome, ) -> bool + 'a), ) -> Result< impl Iterator)> + 'a, crate::is_active_platform::Error, > { let mut platform = self.is_active_platform(config, defaults)?; let iter = self .names() .map(move |name| (name, platform.is_active(config, name, attributes))); Ok(iter) } /// Return a platform which allows to check if a submodule name is active or inactive. /// Use `defaults` for parsing the pathspecs used to later match on names via `submodule.active` configuration retrieved from `config`. /// /// All `submodule.active` pathspecs are considered to be top-level specs and match the name of submodules, which are active /// on inclusive match. /// The full algorithm is described as [hierarchy of rules](https://git-scm.com/docs/gitsubmodules#_active_submodules). pub fn is_active_platform( &self, config: &gix_config::File<'_>, defaults: gix_pathspec::Defaults, ) -> Result { let search = config .strings("submodule.active") .map(|patterns| -> Result<_, crate::is_active_platform::Error> { let patterns = patterns .into_iter() .map(|pattern| gix_pathspec::parse(&pattern, defaults)) .collect::, _>>()?; Ok(gix_pathspec::Search::from_specs( patterns, None, std::path::Path::new(""), )?) }) .transpose()?; Ok(IsActivePlatform { search }) } /// Given the `relative_path` (as seen from the root of the worktree) of a submodule with possibly platform-specific /// component separators, find the submodule's name associated with this path, or `None` if none was found. /// /// Note that this does a linear search and compares `relative_path` in a normalized form to the same form of the path /// associated with the submodule. pub fn name_by_path(&self, relative_path: &BStr) -> Option<&BStr> { self.names() .filter_map(|n| self.path(n).ok().map(|p| (n, p))) .find_map(|(n, p)| (p == relative_path).then_some(n)) } } /// Per-Submodule Access impl File { /// Return the path relative to the root directory of the working tree at which the submodule is expected to be checked out. /// It's an error if the path doesn't exist as it's the only way to associate a path in the index with additional submodule /// information, like the URL to fetch from. /// /// ### Deviation /// /// Git currently allows absolute paths to be used when adding submodules, but fails later as it can't find the submodule by /// relative path anymore. Let's play it safe here. pub fn path(&self, name: &BStr) -> Result, config::path::Error> { let path_bstr = self.config .string(format!("submodule.{name}.path")) .ok_or_else(|| config::path::Error::Missing { submodule: name.to_owned(), })?; if path_bstr.is_empty() { return Err(config::path::Error::Missing { submodule: name.to_owned(), }); } let path = gix_path::from_bstr(path_bstr.as_ref()); if path.is_absolute() { return Err(config::path::Error::Absolute { submodule: name.to_owned(), actual: path_bstr.into_owned(), }); } if gix_path::normalize(path, "".as_ref()).is_none() { return Err(config::path::Error::OutsideOfWorktree { submodule: name.to_owned(), actual: path_bstr.into_owned(), }); } Ok(path_bstr) } /// Retrieve the `url` field of the submodule named `name`. It's an error if it doesn't exist or is empty. pub fn url(&self, name: &BStr) -> Result { let url = self .config .string(format!("submodule.{name}.url")) .ok_or_else(|| config::url::Error::Missing { submodule: name.to_owned(), })?; if url.is_empty() { return Err(config::url::Error::Missing { submodule: name.to_owned(), }); } gix_url::Url::from_bytes(url.as_ref()).map_err(|err| config::url::Error::Parse { submodule: name.to_owned(), source: err, }) } /// Retrieve the `update` field of the submodule named `name`, if present. pub fn update(&self, name: &BStr) -> Result, config::update::Error> { let value: Update = match self.config.string(format!("submodule.{name}.update")) { Some(v) => v.as_ref().try_into().map_err(|()| config::update::Error::Invalid { submodule: name.to_owned(), actual: v.into_owned(), })?, None => return Ok(None), }; if let Update::Command(cmd) = &value { let ours = self.config.meta(); let has_value_from_foreign_section = self .config .sections_by_name("submodule") .into_iter() .flatten() .any(|s| (s.header().subsection_name() == Some(name) && s.meta() as *const _ != ours as *const _)); if !has_value_from_foreign_section { return Err(config::update::Error::CommandForbiddenInModulesConfiguration { submodule: name.to_owned(), actual: cmd.to_owned(), }); } } Ok(Some(value)) } /// Retrieve the `branch` field of the submodule named `name`, or `None` if unset. /// /// Note that `Default` is implemented for [`Branch`]. pub fn branch(&self, name: &BStr) -> Result, config::branch::Error> { let branch = match self.config.string(format!("submodule.{name}.branch")) { Some(v) => v, None => return Ok(None), }; Branch::try_from(branch.as_ref()) .map(Some) .map_err(|err| config::branch::Error { submodule: name.to_owned(), actual: branch.into_owned(), source: err, }) } /// Retrieve the `fetchRecurseSubmodules` field of the submodule named `name`, or `None` if unset. /// /// Note that if it's unset, it should be retrieved from `fetch.recurseSubmodules` in the configuration. pub fn fetch_recurse(&self, name: &BStr) -> Result, config::Error> { self.config .boolean(format!("submodule.{name}.fetchRecurseSubmodules")) .map(FetchRecurse::new) .transpose() .map_err(|value| config::Error { field: "fetchRecurseSubmodules", submodule: name.to_owned(), actual: value, }) } /// Retrieve the `ignore` field of the submodule named `name`, or `None` if unset. pub fn ignore(&self, name: &BStr) -> Result, config::Error> { self.config .string(format!("submodule.{name}.ignore")) .map(|value| { Ignore::try_from(value.as_ref()).map_err(|()| config::Error { field: "ignore", submodule: name.to_owned(), actual: value.into_owned(), }) }) .transpose() } /// Retrieve the `shallow` field of the submodule named `name`, or `None` if unset. /// /// If `true`, the submodule will be checked out with `depth = 1`. If unset, `false` is assumed. pub fn shallow(&self, name: &BStr) -> Result, gix_config::value::Error> { self.config.boolean(format!("submodule.{name}.shallow")).transpose() } } gix-submodule-0.16.0/src/config.rs000064400000000000000000000173161046102023000151060ustar 00000000000000use bstr::{BStr, BString, ByteSlice}; /// Determine how the submodule participates in `git status` queries. This setting also affects `git diff`. #[derive(Default, Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash)] pub enum Ignore { /// Submodule changes won't be considered at all, which is the fastest option. All, /// Ignore any changes to the submodule working tree, only show committed differences between the `HEAD` of the submodule /// compared to the recorded commit in the superproject. Dirty, /// Only ignore untracked files in the submodule, but show modifications to the submodule working tree as well as differences /// between the recorded commit in the superproject and the checked-out commit in the submodule. Untracked, /// No modifications to the submodule are ignored, which shows untracked files, modified files in the submodule worktree as well as /// differences between the recorded commit in the superproject and the checked-out commit in the submodule. #[default] None, } impl TryFrom<&BStr> for Ignore { type Error = (); fn try_from(value: &BStr) -> Result { Ok(match value.as_bytes() { b"all" => Ignore::All, b"dirty" => Ignore::Dirty, b"untracked" => Ignore::Untracked, b"none" => Ignore::None, _ => return Err(()), }) } } /// Determine how to recurse into this module from the superproject when fetching. /// /// Generally, a fetch is only performed if the submodule commit referenced by the superproject isn't already /// present in the submodule repository. /// /// Note that when unspecified, the `fetch.recurseSubmodules` configuration variable should be used instead. #[derive(Default, Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash)] pub enum FetchRecurse { /// Fetch only changed submodules. #[default] OnDemand, /// Fetch all populated submodules, changed or not. /// /// This skips the work needed to determine whether a submodule has changed in the first place, but may work /// more as some fetches might not be necessary. Always, /// Submodules are never fetched. Never, } impl FetchRecurse { /// Check if `boolean` is set and translate it the respective variant, or check the underlying string /// value for non-boolean options. /// On error, it returns the obtained string value which would be the invalid value. pub fn new(boolean: Result) -> Result { Ok(match boolean { Ok(value) => { if value { FetchRecurse::Always } else { FetchRecurse::Never } } Err(err) => { if err.input != "on-demand" { return Err(err.input); } FetchRecurse::OnDemand } }) } } /// Describes the branch that should be tracked on the remote. #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] pub enum Branch { /// The name of the remote branch should be the same as the one currently checked out in the superproject. CurrentInSuperproject, /// The validated remote-only branch that could be used for fetching. Name(BString), } impl Default for Branch { fn default() -> Self { Branch::Name("HEAD".into()) } } impl TryFrom<&BStr> for Branch { type Error = gix_refspec::parse::Error; fn try_from(value: &BStr) -> Result { if value == "." { return Ok(Branch::CurrentInSuperproject); } gix_refspec::parse(value, gix_refspec::parse::Operation::Fetch) .map(|spec| Branch::Name(spec.source().expect("no object").to_owned())) } } /// Determine how `git submodule update` should deal with this submodule to bring it up-to-date with the /// super-project's expectations. #[derive(Default, Debug, Clone, Hash, PartialOrd, PartialEq, Ord, Eq)] pub enum Update { /// The commit recorded in the superproject should be checked out on a detached `HEAD`. #[default] Checkout, /// The current branch in the submodule will be rebased onto the commit recorded in the superproject. Rebase, /// The commit recorded in the superproject will merged into the current branch of the submodule. Merge, /// A custom command to be called like ` hash-of-submodule-commit` that is to be executed to /// perform the submodule update. /// /// Note that this variant is only allowed if the value is coming from an override. Thus it's not allowed to distribute /// arbitrary commands via `.gitmodules` for security reasons. Command(BString), /// The submodule update is not performed at all. None, } impl TryFrom<&BStr> for Update { type Error = (); fn try_from(value: &BStr) -> Result { Ok(match value.as_bstr().as_bytes() { b"checkout" => Update::Checkout, b"rebase" => Update::Rebase, b"merge" => Update::Merge, b"none" => Update::None, command if command.first() == Some(&b'!') => Update::Command(command[1..].to_owned().into()), _ => return Err(()), }) } } /// The error returned by [File::fetch_recurse()](crate::File::fetch_recurse) and [File::ignore()](crate::File::ignore). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] #[error("The '{field}' field of submodule '{submodule}' was invalid: '{actual}'")] pub struct Error { pub field: &'static str, pub submodule: BString, pub actual: BString, } /// pub mod branch { use bstr::BString; /// The error returned by [File::branch()](crate::File::branch). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] #[error("The value '{actual}' of the 'branch' field of submodule '{submodule}' couldn't be turned into a valid fetch refspec")] pub struct Error { pub submodule: BString, pub actual: BString, pub source: gix_refspec::parse::Error, } } /// pub mod update { use bstr::BString; /// The error returned by [File::update()](crate::File::update). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("The 'update' field of submodule '{submodule}' tried to set command '{actual}' to be shared")] CommandForbiddenInModulesConfiguration { submodule: BString, actual: BString }, #[error("The 'update' field of submodule '{submodule}' was invalid: '{actual}'")] Invalid { submodule: BString, actual: BString }, } } /// pub mod url { use bstr::BString; /// The error returned by [File::url()](crate::File::url). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("The url of submodule '{submodule}' could not be parsed")] Parse { submodule: BString, source: gix_url::parse::Error, }, #[error("The submodule '{submodule}' was missing its 'url' field or it was empty")] Missing { submodule: BString }, } } /// pub mod path { use bstr::BString; /// The error returned by [File::path()](crate::File::path). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("The path '{actual}' of submodule '{submodule}' needs to be relative")] Absolute { actual: BString, submodule: BString }, #[error("The submodule '{submodule}' was missing its 'path' field or it was empty")] Missing { submodule: BString }, #[error("The path '{actual}' would lead outside of the repository worktree")] OutsideOfWorktree { actual: BString, submodule: BString }, } } gix-submodule-0.16.0/src/is_active_platform.rs000064400000000000000000000036361046102023000175130ustar 00000000000000use bstr::BStr; use crate::IsActivePlatform; /// The error returned by [File::names_and_active_state](crate::File::names_and_active_state()). #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error(transparent)] NormalizePattern(#[from] gix_pathspec::normalize::Error), #[error(transparent)] ParsePattern(#[from] gix_pathspec::parse::Error), } impl IsActivePlatform { /// Returns `true` if the submodule named `name` is active or `false` otherwise. /// `config` is the configuration that was passed to the originating [modules file](crate::File). /// `attributes(relative_path, case, is_dir, outcome)` provides a way to resolve the attributes mentioned /// in `submodule.active` pathspecs that are evaluated in the platforms git configuration. /// /// A submodule's active state is determined in the following order /// /// * it's `submodule..active` is set in `config` /// * it matches a `submodule.active` pathspec either positively or negatively via `:!` /// * it's active if it has any `url` set in `config` pub fn is_active( &mut self, config: &gix_config::File<'static>, name: &BStr, attributes: &mut dyn FnMut( &BStr, gix_pathspec::attributes::glob::pattern::Case, bool, &mut gix_pathspec::attributes::search::Outcome, ) -> bool, ) -> Result { if let Some(val) = config.boolean(format!("submodule.{name}.active")).transpose()? { return Ok(val); }; if let Some(val) = self.search.as_mut().map(|search| { search .pattern_matching_relative_path(name, Some(true), attributes) .map_or(false, |m| !m.is_excluded()) }) { return Ok(val); } Ok(config.string(format!("submodule.{name}.url")).is_some()) } } gix-submodule-0.16.0/src/lib.rs000064400000000000000000000120761046102023000144050ustar 00000000000000//! Primitives for describing git submodules. #![deny(rust_2018_idioms, missing_docs)] #![forbid(unsafe_code)] use std::{borrow::Cow, collections::BTreeMap}; use bstr::BStr; /// All relevant information about a git module, typically from `.gitmodules` files. /// /// Note that overrides from other configuration might be relevant, which is why this type /// can be used to take these into consideration when presented with other configuration /// from the superproject. #[derive(Clone)] pub struct File { config: gix_config::File<'static>, } mod access; /// pub mod config; /// pub mod is_active_platform; /// A platform to keep the state necessary to perform repeated active checks, created by [File::is_active_platform()]. pub struct IsActivePlatform { pub(crate) search: Option, } /// Mutation impl File { /// This can be used to let `config` override some values we know about submodules, namely… /// /// * `url` /// * `fetchRecurseSubmodules` /// * `ignore` /// * `update` /// * `branch` /// /// These values aren't validated yet, which will happen upon query. pub fn append_submodule_overrides(&mut self, config: &gix_config::File<'_>) -> &mut Self { let mut values = BTreeMap::<_, Vec<_>>::new(); for (module_name, section) in config .sections_by_name("submodule") .into_iter() .flatten() .filter_map(|s| s.header().subsection_name().map(|n| (n, s))) { for field in ["url", "fetchRecurseSubmodules", "ignore", "update", "branch"] { if let Some(value) = section.value(field) { values.entry((module_name, field)).or_default().push(value); } } } let values = { let mut v: Vec<_> = values.into_iter().collect(); v.sort_by_key(|a| a.0 .0); v }; let mut config_to_append = gix_config::File::new(config.meta_owned()); let mut prev_name = None; for ((module_name, field), values) in values { if prev_name.map_or(true, |pn: &BStr| pn != module_name) { config_to_append .new_section("submodule", Some(Cow::Owned(module_name.to_owned()))) .expect("all names come from valid configuration, so remain valid"); prev_name = Some(module_name); } config_to_append .section_mut("submodule", Some(module_name)) .expect("always set at this point") .push( field.try_into().expect("statically known key"), Some(values.last().expect("at least one value or we wouldn't be here")), ); } self.config.append(config_to_append); self } } /// mod init { use std::path::PathBuf; use crate::File; impl std::fmt::Debug for File { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("File") .field("config_path", &self.config_path()) .field("config", &format_args!("r#\"{}\"#", self.config)) .finish() } } /// A marker we use when listing names to not pick them up from overridden sections. pub(crate) const META_MARKER: gix_config::Source = gix_config::Source::Api; /// Lifecycle impl File { /// Parse `bytes` as git configuration, typically from `.gitmodules`, without doing any further validation. /// `path` can be provided to keep track of where the file was read from in the underlying [`config`](Self::config()) /// instance. /// `config` is used to [apply value overrides](File::append_submodule_overrides), which can be empty if overrides /// should be applied at a later time. /// /// Future access to the module information is lazy and configuration errors are exposed there on a per-value basis. /// /// ### Security Considerations /// /// The information itself should be used with care as it can direct the caller to fetch from remotes. It is, however, /// on the caller to assure the input data can be trusted. pub fn from_bytes( bytes: &[u8], path: impl Into>, config: &gix_config::File<'_>, ) -> Result { let metadata = { let mut meta = gix_config::file::Metadata::from(META_MARKER); meta.path = path.into(); meta }; let modules = gix_config::File::from_parse_events_no_includes( gix_config::parse::Events::from_bytes_owned(bytes, None)?, metadata, ); let mut res = Self { config: modules }; res.append_submodule_overrides(config); Ok(res) } /// Turn ourselves into the underlying parsed configuration file. pub fn into_config(self) -> gix_config::File<'static> { self.config } } }