### Example: Get HEAD Tree Source: https://docs.rs/gix/latest/src/gix/repository/reference.rs.html?search=std%3A%3Avec Demonstrates retrieving the HEAD tree and asserting the existence and filename of an entry within it. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let tree = repo.head_tree()?; assert_eq!(tree.find_entry("this").expect("present").filename(), "this"); # Ok(()) } ``` -------------------------------- ### Get Git Installation Config Prefix Source: https://docs.rs/gix/latest/gix/path/env/fn.installation_config_prefix.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the location of git installation specific configuration files. This function invokes the git binary, which can be slow on Windows. ```rust pub fn installation_config_prefix() -> Option<&'static Path> ``` -------------------------------- ### Get Installation Config Path Source: https://docs.rs/gix/latest/gix/path/env/fn.installation_config.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the location of installation-specific git configuration. This function invokes the git binary, which may be slow on Windows. ```rust pub fn installation_config() -> Option<&'static Path> ``` -------------------------------- ### Entry Search Examples Source: https://docs.rs/gix/latest/gix/worktree/object/tree/struct.Entry.html?search= Examples of how to structure search queries for Entry objects. ```APIDOC ## Search Examples ### Example 1: Searching for a specific type ``` std::vec ``` ### Example 2: Searching for a type conversion ``` u32 -> bool ``` ### Example 3: Searching for generic type transformations ``` Option, (T -> U) -> Option ``` ``` -------------------------------- ### UnsignedInteger Search Examples Source: https://docs.rs/gix/latest/gix/config/tree/keys/type.UnsignedInteger.html?search= Examples of how to search for unsigned integers. These demonstrate common patterns and types of searches. ```APIDOC ## UnsignedInteger Search ### Description Provides examples of how to search for unsigned integers. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Example of Opening a Repository Source: https://docs.rs/gix/latest/src/gix/lib.rs.html?search= Demonstrates how to open a repository and assert its head name and commit message. This example requires a pre-existing repository. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo_dir = doctest::basic_repo_dir()?; let repo = doctest::open_repo(repo_dir)?; assert_eq!(repo.head_name()?.expect("born").shorten(), "main"); assert_eq!(repo.head_commit()?.decode()?.message, "c2\n"); # Ok(()) # } ``` -------------------------------- ### Example of len Source: https://docs.rs/gix/latest/gix/config/parse/section/struct.Name.html?search= A simple example showing how to get the length of an array. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Example: Create section and add values Source: https://docs.rs/gix/latest/gix/config/struct.File.html?search= Shows how to create a new section, add values to it, and then add another section. ```rust let mut git_config = gix_config::File::default(); let mut section = git_config.new_section("hello", Some(Cow::Borrowed("world".into())))?; section.push(section::ValueName::try_from("a")?, Some("b".into())); let nl = section.newline().to_owned(); assert_eq!(git_config.to_string(), format!("[hello \"world\"]{nl}\ta = b{nl}")); let _section = git_config.new_section("core", None); assert_eq!(git_config.to_string(), format!("[hello \"world\"]{nl}\ta = b{nl}[core]{nl}")); ``` -------------------------------- ### Get Installation Directory Path Source: https://docs.rs/gix/latest/src/gix/repository/location.rs.html?search=u32+-%3E+bool Returns the directory where the current process binary is installed. This operation can result in an I/O error. ```rust pub fn install_dir(&self) -> std::io::Result { crate::path::install_dir() } ``` -------------------------------- ### Basic Repository Usage Example Source: https://docs.rs/gix/latest/src/gix/lib.rs.html Demonstrates opening a repository, accessing the head commit, and verifying head information. Ensure the repository is set up correctly for doctests. ```rust 1//! This crate provides the [`Repository`] abstraction which serves as a hub into all the functionality of git. 2//! 3//! It's powerful and won't sacrifice performance while still increasing convenience compared to using the sub-crates 4//! individually. Sometimes it may hide complexity under the assumption that the performance difference doesn't matter 5//! for all but the fewest tools out there, which would be using the underlying crates directly or file an issue. 6//! 7//! ## Example 8//! 9//! This is merely an introduction, for more see the respective [`Repository`] methods. 10//! ``` 11//! # fn main() -> Result<(), Box> { 12//! # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } 13//! # let repo_dir = doctest::basic_repo_dir()?; 14//! # let repo = doctest::open_repo(repo_dir)?; 15//! let head = repo.head_commit()?; 16//! 17//! assert_eq!(repo.head_name()?.expect("born").shorten(), "main"); 18//! assert_eq!(head.decode()?.message, "c2\n"); 19//! assert_eq!(repo.head_tree_id()?, head.tree_id()?); 20//! # Ok(()} 21//! ``` ``` -------------------------------- ### Get Installation Directory Source: https://docs.rs/gix/latest/src/gix/repository/location.rs.html Retrieves the directory where the current process's binary is installed. This operation may result in an I/O error. ```rust pub fn install_dir(&self) -> std::io::Result { crate::path::install_dir() } ``` -------------------------------- ### Creating and Using Path Instances Source: https://docs.rs/gix/latest/gix/config/struct.Path.html?search= Demonstrates how to create regular and optional Path instances and check their properties. ```rust use std::borrow::Cow; use gix_config_value::Path; use bstr::ByteSlice; // Regular path - file is expected to exist let path = Path::from(Cow::Borrowed(b"/etc/gitconfig".as_bstr())); assert!(!path.is_optional); // Optional path - it's okay if the file doesn't exist let path = Path::from(Cow::Borrowed(b":(optional)~/.gitignore".as_bstr())); assert!(path.is_optional); assert_eq!(path.value.as_ref(), b"~/.gitignore"); // prefix is stripped ``` -------------------------------- ### Get Installation Directory Source: https://docs.rs/gix/latest/src/gix/path.rs.html Retrieves the installation directory of the current executable. This is useful for locating resources relative to the application's installation path. It handles cases where the executable might not have a parent directory. ```Rust use std::path::PathBuf; pub use gix_path::*; pub(crate) fn install_dir() -> std::io::Result { std::env::current_exe().and_then(|exe| { exe.parent() .map(ToOwned::to_owned) .ok_or_else(|| std::io::Error::other("no parent for current executable")) }) } ``` -------------------------------- ### Example: Writing and Finding a Blob Source: https://docs.rs/gix/latest/src/gix/repository/object.rs.html?search= Demonstrates writing a blob with 'hello world' content and then retrieving it to verify its data. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let dir = doctest::tempdir()?; let repo = gix::init_bare(dir.path())?; let blob_id = repo.write_blob(b"hello world")?; assert_eq!(repo.find_blob(blob_id)?.data, b"hello world"); # Ok(()) # } ``` -------------------------------- ### Example: Get Raw Commit Message Source: https://docs.rs/gix/latest/src/gix/object/commit.rs.html?search= Shows how to retrieve the raw commit message string. This example assumes a repository and a head commit are accessible. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let commit = repo.head_commit()?; assert_eq!(commit.message_raw()?, "c2\n"); # Ok(()) } ``` -------------------------------- ### Example: Get HEAD Object ID Source: https://docs.rs/gix/latest/src/gix/head/mod.rs.html?search= Demonstrates how to retrieve the object ID that the HEAD currently points to. This example assumes the HEAD is 'born' (not unborn). ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let head = repo.head()?; assert_eq!(head.id().expect("born"), repo.head_id()?); # Ok(()) } ``` -------------------------------- ### prepare_clone_bare Source: https://docs.rs/gix/latest/gix/fn.prepare_clone_bare.html?search= Creates a platform for configuring a bare clone from a URL to a local path, using default options amended with git installation configuration to ensure all authentication options are honored. Use `clone::PrepareFetch::new()` for full control over all options. ```APIDOC ## prepare_clone_bare ### Description Create a platform for configuring a bare clone from `url` to the local `path`, using default options for opening it (but amended with using configuration from the git installation to ensure all authentication options are honored). See `clone::PrepareFetch::new()` for a function to take full control over all options. ### Signature ```rust pub fn prepare_clone_bare( url: Url, path: impl AsRef, ) -> Result where Url: TryInto, Error: From, ``` ``` -------------------------------- ### Initialize Repository Options Source: https://docs.rs/gix/latest/src/gix/clone/mod.rs.html?search= Sets options for creating a new repository, ensuring the destination is empty. ```rust create_opts.destination_must_be_empty = Some(true); ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/gix/latest/gix/config/file/init/enum.Error.html?search= Demonstrates example search queries, showing patterns for common Rust types and generic operations. ```text * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Getting Grapheme Indices Source: https://docs.rs/gix/latest/gix/worktree/object/bstr/trait.ByteSlice.html Use `grapheme_indices` to get the starting and ending byte indices of each grapheme cluster. This is helpful for tasks requiring precise byte-level positioning of graphemes. ```rust use bstr::ByteSlice; let bs = "a\u{0300}\u{0316}\u{1F1FA}\u{1F1F8}".as_bytes(); let graphemes: Vec<(usize, usize, &str)> = bs.grapheme_indices().collect(); assert_eq!(vec![(0, 5, "à̖"), (5, 13, "🇺🇸")], graphemes); ``` -------------------------------- ### Initialize File at Path Source: https://docs.rs/gix/latest/gix/index/struct.File.html Opens an index file at the specified path with given options. If skip_hash is true, checksum verification is skipped for performance. ```rust pub fn at( path: impl Into, object_hash: Kind, skip_hash: bool, options: Options, ) -> Result ``` -------------------------------- ### Example: Finding a Commit by Peeling a Reference Source: https://docs.rs/gix/latest/src/gix/reference/mod.rs.html?search=u32+-%3E+bool Demonstrates how to find the ultimate commit an object points to by peeling a reference. This example assumes a repository setup and a 'main' reference. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let mut branch = repo.find_reference("main")?; let commit = branch.peel_to_commit()?; assert_eq!(commit.message_raw()?, "c2\n"); # Ok(()) # } ``` -------------------------------- ### Getting Grapheme Cluster Indices Source: https://docs.rs/gix/latest/gix/diff/object/bstr/trait.ByteSlice.html Use `grapheme_indices` to get the starting and ending byte indices along with the grapheme cluster itself. This method handles invalid UTF-8 by yielding the replacement codepoint. ```rust use bstr::ByteSlice; let bs = "a\u{0300}\u{0316}\u{1F1FA}\u{1F1F8}".as_bytes(); let graphemes: Vec<(usize, usize, &str)> = bs.grapheme_indices().collect(); assert_eq!(vec![(0, 5, "à̖"), (5, 13, "🇺🇸")], graphemes); ``` ```rust use bstr::{ByteSlice, ByteVec}; let mut bytes = vec![]; bytes.push_str("a\u{0300}\u{0316}"); bytes.push(b'\xFF'); bytes.push_str("\u{1F1FA}\u{1F1F8}"); let graphemes: Vec<(usize, usize, &str)> = bytes.grapheme_indices().collect(); assert_eq!( graphemes, vec![(0, 5, "à̖"), (5, 6, "\u{FFFD}"), (6, 14, "🇺🇸")] ); ``` -------------------------------- ### Example: Inspecting Repository HEAD Source: https://docs.rs/gix/latest/src/gix/repository/reference.rs.html?search=std%3A%3Avec Demonstrates how to open a repository and inspect its HEAD reference, checking its referent name, and whether it's detached or unborn. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let head = repo.head()?; assert_eq!(head.referent_name().expect("born").as_bstr(), "refs/heads/main"); assert!(!head.is_detached()); assert!(!head.is_unborn()); # Ok(()) } ``` -------------------------------- ### Initialize Repository with Options Source: https://docs.rs/gix/latest/src/gix/clone/mod.rs.html?search=std%3A%3Avec Initializes a new repository at the specified path with given options. It handles destination emptiness checks and sets up the repository for further operations. The cleanup logic ensures the destination is removed if it was empty and the operation fails. ```rust let mut repo = crate::ThreadSafeRepository::init_opts(path, kind, create_opts, open_opts)?.to_thread_local(); url.canonicalize(repo.options.current_dir_or_empty()) .map_err(|err| Error::CanonicalizeUrl { url: url.clone(), source: err, })?; repo.committer_or_set_generic_fallback()?; Ok(PrepareFetch { url, #[cfg(any(feature = "async-network-client", feature = "blocking-network-client"))] fetch_options: Default::default(), repo: Some(repo), config_overrides: Vec::new(), remote_name: None, configure_remote: None, #[cfg(any(feature = "async-network-client", feature = "blocking-network-client"))] configure_connection: None, shallow: remote::fetch::Shallow::NoChange, ref_name: None, remove_worktree_on_drop, }) ``` -------------------------------- ### Example of first Source: https://docs.rs/gix/latest/gix/config/parse/section/struct.Name.html?search= Shows how to safely get the first element of a slice, returning None if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Example: Basic Repository Operations Source: https://docs.rs/gix/latest/src/gix/lib.rs.html Demonstrates basic operations on an opened Git repository, such as checking the head name and commit message. This example requires a pre-existing repository. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo_dir = doctest::basic_repo_dir()?; # let repo = doctest::open_repo(repo_dir)?; assert_eq!(repo.head_name()?.expect("born").shorten(), "main"); assert_eq!(repo.head_commit()?.decode()?.message, "c2\n"); # Ok(()) # } ``` -------------------------------- ### Take and reset statistics Source: https://docs.rs/gix/latest/gix/worktree/struct.Stack.html?search= Resets the collected statistics after returning them. Use this to get current statistics and start fresh. ```rust pub fn take_statistics(&mut self) -> Statistics ``` -------------------------------- ### Initialize and Prepare Fetch Options Source: https://docs.rs/gix/latest/src/gix/clone/mod.rs.html?search= Initializes a repository and prepares fetch options, including canonicalizing the URL and setting up fallback committer. ```rust let mut repo = crate::ThreadSafeRepository::init_opts(path, kind, create_opts, open_opts)?.to_thread_local(); url.canonicalize(repo.options.current_dir_or_empty()) .map_err(|err| Error::CanonicalizeUrl { url: url.clone(), source: err, })?; repo.committer_or_set_generic_fallback()?; Ok(PrepareFetch { url, #[cfg(any(feature = "async-network-client", feature = "blocking-network-client"))] fetch_options: Default::default(), repo: Some(repo), config_overrides: Vec::new(), remote_name: None, configure_remote: None, #[cfg(any(feature = "async-network-client", feature = "blocking-network-client"))] configure_connection: None, shallow: remote::fetch::Shallow::NoChange, ref_name: None, remove_worktree_on_drop, }) ``` -------------------------------- ### Example Usage of Iterating Ranges Source: https://docs.rs/gix/latest/gix/config/parse/section/struct.Name.html Demonstrates the expected output when iterating over ranges, showing start and end points. ```rust assert_eq!(iter.next(), Some(Range { start: 0, end: 0 })); assert_eq!(iter.next(), Some(Range { start: 1, end: 3 })); assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); ``` -------------------------------- ### Create and Configure Git Repository Source: https://docs.rs/gix/latest/src/gix/create.rs.html Initializes a new Git repository, creates the configuration file, and sets core options based on filesystem capabilities and specified object hash. Handles SHA256 feature for object format. ```rust let (mut config_file, config_path) = { let mut cursor = PathCursor(&mut dot_git); let config_path = cursor.at("config"); (fs::File::create(config_path)?, config_path.to_owned()) }; let mut config = gix_config::File::default(); let caps = { let caps = fs_capabilities.unwrap_or_else(|| gix_fs::Capabilities::probe(&dot_git)); let mut core = config.new_section("core", None).expect("valid section name"); core.push(key("filemode"), Some(bool(caps.executable_bit).into())); core.push(key("bare"), Some(bool(bare).into())); core.push(key("logallrefupdates"), Some(bool(!bare).into())); core.push(key("symlinks"), Some(bool(caps.symlink).into())); core.push(key("ignorecase"), Some(bool(caps.ignore_case).into())); core.push(key("precomposeunicode"), Some(bool(caps.precompose_unicode).into())); match object_hash { #[cfg(feature = "sha256")] Some(gix_hash::Kind::Sha256) => { core.push(key("repositoryformatversion"), Some("1".into())); let mut extensions = config.new_section("extensions", None).expect("valid section name"); extensions.push( key("objectformat"), Some(gix_hash::Kind::Sha256.to_string().as_bytes().into()), ); } _ => { core.push(key("repositoryformatversion"), Some("0".into())); } } caps }; config_file .write_all(&config.to_bstring()) .map_err(|err| Error::IoWrite { source: err, path: config_path, })?; caps }; Ok(gix_discover::repository::Path::from_dot_git_dir( dot_git, if bare { gix_discover::repository::Kind::PossiblyBare } else { gix_discover::repository::Kind::WorkTree { linked_git_dir: None } }, &gix_fs::current_dir(caps.precompose_unicode)?, ) .expect("by now the `dot_git` dir is valid as we have accessed it")) ``` -------------------------------- ### Getting Word Indices Source: https://docs.rs/gix/latest/gix/diff/object/bstr/trait.ByteSlice.html Use `word_indices` to get the starting and ending byte indices of each word. This method identifies words based on UTS #18 Annex C and handles invalid UTF-8 by substituting replacement codepoints. ```rust use bstr::ByteSlice; let bs = b"can't jump 32.3 feet"; let words: Vec<(usize, usize, &str)> = bs.word_indices().collect(); assert_eq!(words, vec![ (0, 5, "can't"), (6, 10, "jump"), (11, 15, "32.3"), (16, 20, "feet"), ]); ``` -------------------------------- ### Initialize Repository with Default Options Source: https://docs.rs/gix/latest/src/gix/init.rs.html Creates a new Git repository in the specified directory using default options. Intermediate directories are created as needed. Fails if the destination is not empty unless specified otherwise in options. ```rust #![allow(clippy::result_large_err)] use std::{borrow::Cow, path::Path}; use gix_ref::{ Category, FullName, Target, store::WriteReflog, transaction::{PreviousValue, RefEdit}, }; use crate::{ ThreadSafeRepository, bstr::{BString, ByteSlice}, config::tree::Init, }; /// The name of the branch to use if non is configured via git configuration. /// /// # Deviation /// /// We use `main` instead of `master`. pub const DEFAULT_BRANCH_NAME: &str = "main"; /// The error returned by [`crate::init()`]. #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("Could not obtain the current directory")] CurrentDir(#[from] std::io::Error), #[error(transparent)] Init(#[from] crate::create::Error), #[error(transparent)] Open(#[from] crate::open::Error), #[error("Invalid default branch name: {name:?}")] InvalidBranchName { name: BString, source: gix_validate::reference::name::Error, }, #[error("Could not edit HEAD reference with new default name")] EditHeadForDefaultBranch(#[from] crate::reference::edit::Error), } impl ThreadSafeRepository { /// Create a repository with work-tree within `directory`, creating intermediate directories as needed. /// /// Fails without action if the destination directory isn't empty unless /// [`create::Options::destination_must_be_empty`][crate::create::Options::destination_must_be_empty] is `None` /// or `Some(false)`. Note that initialization still fails if a `.git` directory already exists in /// the destination. pub fn init( directory: impl AsRef, kind: crate::create::Kind, options: crate::create::Options, ) -> Result { use gix_sec::trust::DefaultForLevel; let open_options = crate::open::Options::default_for_level(gix_sec::Trust::Full); Self::init_opts(directory, kind, options, open_options) } /// Similar to [`init`][Self::init()], but allows to determine how exactly to open the newly created repository. /// /// # Deviation /// /// Instead of naming the default branch `master`, we name it `main` unless configured explicitly using the `init.defaultBranch` /// configuration key. pub fn init_opts( directory: impl AsRef, kind: crate::create::Kind, create_options: crate::create::Options, mut open_options: crate::open::Options, ) -> Result { let path = crate::create::into(directory.as_ref(), kind, create_options)?; let (git_dir, worktree_dir) = path.into_repository_and_work_tree_directories(); open_options.git_dir_trust = Some(gix_sec::Trust::Full); // The repo will use `core.precomposeUnicode` to adjust the value as needed. open_options.current_dir = gix_fs::current_dir(false)?.into(); let repo = ThreadSafeRepository::open_from_paths(git_dir, worktree_dir, open_options)?; let branch_name = repo .config .resolved .string(Init::DEFAULT_BRANCH) .unwrap_or_else(|| Cow::Borrowed(DEFAULT_BRANCH_NAME.into())); if branch_name.as_ref() != DEFAULT_BRANCH_NAME { let configured_branch_name = branch_name.into_owned(); let sym_ref: FullName = Category::LocalBranch .to_full_name(configured_branch_name.as_bstr()) .map_err(|err| Error::InvalidBranchName { name: configured_branch_name.clone(), source: err, })?; gix_validate::reference::branch_name(sym_ref.as_bstr()).map_err(|err| Error::InvalidBranchName { name: configured_branch_name, source: err, })?; let mut repo = repo.to_thread_local(); let prev_write_reflog = repo.refs.write_reflog; repo.refs.write_reflog = WriteReflog::Disable; repo.edit_reference(RefEdit { change: gix_ref::transaction::Change::Update { log: Default::default(), expected: PreviousValue::Any, new: Target::Symbolic(sym_ref), }, name: "HEAD".try_into().expect("valid"), deref: false, })?; repo.refs.write_reflog = prev_write_reflog; } Ok(repo) } } ``` -------------------------------- ### Example: Create a new empty section Source: https://docs.rs/gix/latest/gix/config/struct.File.html?search= Demonstrates creating a new, empty configuration section with a specified name and subsection. ```rust let mut git_config = gix_config::File::default(); let section = git_config.new_section("hello", Some(Cow::Borrowed("world".into())))?; let nl = section.newline().to_owned(); assert_eq!(git_config.to_string(), format!("[hello \"world\"]{nl}")); ``` -------------------------------- ### AsFd for Arc Source: https://docs.rs/gix/latest/gix/progress/prodash/progress/type.StepShared.html?search= Allows implementing traits that require `AsFd` on `Arc`. This example shows a basic setup for a custom trait. ```rust use std::net::UdpSocket; use std::sync::Arc; trait MyTrait: AsFd {} impl MyTrait for Arc {} impl MyTrait for Box {} ``` -------------------------------- ### prepare_clone_bare Source: https://docs.rs/gix/latest/gix/fn.prepare_clone_bare.html?search=std%3A%3Avec Creates a platform for configuring a bare clone from a URL to a local path. It uses default options for opening the repository, but these are amended with configuration from the git installation to ensure all authentication options are honored. For full control over all options, see `clone::PrepareFetch::new()`. ```APIDOC ## Function prepare_clone_bare ### Description Creates a platform for configuring a bare clone from `url` to the local `path`, using default options for opening it (but amended with using configuration from the git installation to ensure all authentication options are honored). See `clone::PrepareFetch::new()` for a function to take full control over all options. ### Signature ```rust pub fn prepare_clone_bare( url: Url, path: impl AsRef, ) -> Result where Url: TryInto, Error: From, ``` ### Parameters * `url`: The URL of the repository to clone. * `path`: The local path where the bare repository will be created. ``` -------------------------------- ### Example of blocking wait on OnceCell Source: https://docs.rs/gix/latest/gix/threading/type.OnceCell.html Demonstrates using `wait` to get a value from a OnceCell, including setting the value in a separate thread. ```rust use once_cell::sync::OnceCell; let mut cell = std::sync::Arc::new(OnceCell::new()); let t = std::thread::spawn({ let cell = std::sync::Arc::clone(&cell); move || cell.set(92).unwrap() }); // Returns immediately, but might return None. let _value_or_none = cell.get(); // Will return 92, but might block until the other thread does `.set`. let value: &u32 = cell.wait(); assert_eq!(*value, 92); t.join().unwrap(); ``` -------------------------------- ### Get Current Stream Position Source: https://docs.rs/gix/latest/gix/diff/object/find/type.Error.html Returns the current seek position from the start of the stream. This method is part of the stream manipulation capabilities. ```rust fn stream_position(&mut self) -> Result ``` -------------------------------- ### Example: Finding and Inspecting a Reference Source: https://docs.rs/gix/latest/src/gix/repository/reference.rs.html?search= Shows how to open a repository, find a specific reference (e.g., 'main'), and then inspect its name and the message of the commit it points to. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let mut reference = repo.find_reference("main")?; assert_eq!(reference.name().as_bstr(), "refs/heads/main"); assert_eq!(reference.peel_to_commit()?.message()?.title, "c2\n"); # Ok(()) } ``` -------------------------------- ### Formatter initialization and configuration Source: https://docs.rs/gix/latest/gix/progress/prodash/unit/human/struct.Formatter.html?search=std%3A%3Avec Demonstrates how to initialize a new Formatter and configure its behavior using methods like `with_decimals`, `with_separator`, `with_scales`, `with_units`, `with_suffix`, and `with_micro_sign`. ```rust let f = Formatter::new(); ``` ```rust let mut fbin = Formatter::new(); fbin.with_scales(Scales::Binary()); ``` ```rust let mut funit = Formatter::new(); funit.with_units("B"); ``` ```rust let mut fb = Formatter::new(); fb.with_scales(Scales::Binary()).with_units("B"); ``` -------------------------------- ### Default Implementation for Time Source: https://docs.rs/gix/latest/gix/config/tree/keys/validate/struct.Time.html Provides a default value for the Time struct. This is useful when a default instance is needed, for example, in configuration setups. ```rust fn default() -> Time ``` -------------------------------- ### Example of mutable access and re-initialization of OnceCell Source: https://docs.rs/gix/latest/gix/threading/type.OnceCell.html Illustrates getting mutable access and then re-initializing a OnceCell, which is generally discouraged due to the single-write invariant. ```rust use once_cell::sync::OnceCell; let mut cell: OnceCell = OnceCell::new(); cell.set(92).unwrap(); cell = OnceCell::new(); ``` -------------------------------- ### Example: Following HEAD to a Branch Source: https://docs.rs/gix/latest/src/gix/reference/mod.rs.html Demonstrates how to find the 'HEAD' reference and follow it to determine the currently checked-out branch. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let head = repo.find_reference("HEAD")?; let branch = head.follow().expect("symbolic")?; assert_eq!(branch.name().as_bstr(), "refs/heads/main"); # Ok(()) # } ``` -------------------------------- ### Initialize a new Git Repository Source: https://docs.rs/gix/latest/gix/fn.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a new Git repository in the specified directory. Use this to create a fresh repository. It returns a Repository object on success. ```rust pub fn init(directory: impl AsRef) -> Result ``` ```rust let repo = gix::init(dir.path())?; assert!(repo.git_dir().is_dir()); assert!(repo.head_name()?.is_some()); assert!(repo.head()?.is_unborn()); ``` -------------------------------- ### Initialize Repository with Options Source: https://docs.rs/gix/latest/gix/struct.ThreadSafeRepository.html?search= Similar to `init`, this function creates a repository and allows specifying options for both creation and opening the newly created repository. It defaults to the 'main' branch name unless configured otherwise. ```rust pub fn init_opts( directory: impl AsRef, kind: Kind, create_options: Options, open_options: Options, ) -> Result ``` -------------------------------- ### Example: Get Referent Name of HEAD Source: https://docs.rs/gix/latest/src/gix/head/mod.rs.html?search= Demonstrates how to obtain the referent name of the HEAD reference in a repository. Assumes a repository with a branch named 'main'. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let head = repo.head()?; assert_eq!(head.referent_name().expect("branch head").as_bstr(), "refs/heads/main"); # Ok(()) } ``` -------------------------------- ### Symbolic HEAD Reference Example Source: https://docs.rs/gix/latest/src/gix/head/mod.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to get the referent name of a symbolic HEAD, which is common for branch heads. Assumes a repository with a 'main' branch. ```rust use gix::Repository; # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let head = repo.head()?; assert_eq!(head.referent_name().expect("branch head").as_bstr(), "refs/heads/main"); # Ok(()) # } ``` -------------------------------- ### Initialize Repository with Options Source: https://docs.rs/gix/latest/src/gix/clone/mod.rs.html Initializes a new repository at the specified path with given options. It checks if the destination directory is empty before initialization and determines if the worktree should be removed on drop. ```rust let mut create_opts = crate::create::Options::default(); create_opts.destination_must_be_empty = Some(true); let remove_worktree_on_drop = match std::fs::read_dir(path) { Ok(mut entries) => entries.next().is_none(), Err(err) if err.kind() == std::io::ErrorKind::NotFound => true, Err(_) => false, }; let mut repo = crate::ThreadSafeRepository::init_opts(path, kind, create_opts, open_opts)?.to_thread_local(); url.canonicalize(repo.options.current_dir_or_empty()) .map_err(|err| Error::CanonicalizeUrl { url: url.clone(), source: err, })?; repo.committer_or_set_generic_fallback()?; Ok(PrepareFetch { url, #[cfg(any(feature = "async-network-client", feature = "blocking-network-client"))] fetch_options: Default::default(), repo: Some(repo), config_overrides: Vec::new(), remote_name: None, configure_remote: None, #[cfg(any(feature = "async-network-client", feature = "blocking-network-client"))] configure_connection: None, shallow: remote::fetch::Shallow::NoChange, ref_name: None, remove_worktree_on_drop, }) ``` -------------------------------- ### Installation Directory Source: https://docs.rs/gix/latest/gix/config/struct.CommitAutoRollback.html Retrieves the directory of the binary path of the current process. ```APIDOC ## pub fn install_dir(&self) -> Result ### Description The directory of the binary path of the current process. ### Returns - `Result`: The installation directory path. ``` -------------------------------- ### Example: Get Short Commit ID Source: https://docs.rs/gix/latest/src/gix/object/commit.rs.html?search= Demonstrates how to obtain a shortened commit ID and compare it with the full ID. Assumes a repository and a head commit are available. ```rust # use std::cmp::Ordering; # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let commit = repo.head_commit()?; let short_id = commit.short_id()?; assert_eq!(short_id.cmp_oid(&commit.id), Ordering::Equal); assert_eq!(short_id.to_string(), "3189cd3"); # Ok(()) } ``` -------------------------------- ### prepare_clone_bare Source: https://docs.rs/gix/latest/gix/fn.prepare_clone_bare.html?search=u32+-%3E+bool Creates a platform for configuring a bare clone from a URL to a local path, using default options amended with git installation configuration to ensure all authentication options are honored. ```APIDOC ## Function prepare_clone_bare ### Description Create a platform for configuring a bare clone from `url` to the local `path`, using default options for opening it (but amended with using configuration from the git installation to ensure all authentication options are honored). See `clone::PrepareFetch::new()` for a function to take full control over all options. ### Signature ```rust pub fn prepare_clone_bare( url: Url, path: impl AsRef, ) -> Result where Url: TryInto, Error: From, ``` ``` -------------------------------- ### Example: Get Reference Target ID Source: https://docs.rs/gix/latest/gix/struct.Reference.html Demonstrates how to find a reference (e.g., 'main' branch) and assert its target ID against the repository's HEAD ID. ```rust let branch = repo.find_reference("main")?; assert_eq!(branch.target().try_id().expect("direct target"), repo.head_id()?.as_ref()); ``` -------------------------------- ### LinesWithTerminator::as_bytes() example Source: https://docs.rs/gix/latest/gix/diff/object/bstr/struct.LinesWithTerminator.html?search= Demonstrates how to use the as_bytes() method to get a slice of the remaining bytes without advancing the iterator. This is useful for inspecting the rest of the data. ```rust use bstr::{B, ByteSlice}; let s = b" foo bar\r baz"; let mut lines = s.lines_with_terminator(); assert_eq!(lines.next(), Some(B("foo\n"))); assert_eq!(lines.as_bytes(), B("bar\r\nbaz")); ``` -------------------------------- ### prepare_clone_with_worktree Source: https://docs.rs/gix/latest/src/gix/lib.rs.html Prepares a platform for configuring a clone with a main working tree from a URL to a local path. It uses default options, amended with git installation configuration to ensure authentication options are honored. For full control, use `clone::PrepareFetch::new()`. ```APIDOC ## prepare_clone_with_worktree ### Description Create a platform for configuring a clone with main working tree from `url` to the local `path`, using default options for opening it (but amended with using configuration from the git installation to ensure all authentication options are honored). See [`clone::PrepareFetch::new()`] for a function to take full control over all options. ### Method ```rust // Signature not fully provided in source, but inferred from context. // pub fn prepare_clone_with_worktree( // url: Url, // path: impl AsRef, // ) -> Result // where // Url: std::convert::TryInto, // gix_url::parse::Error: From, ``` ### Parameters #### Path Parameters - **url** (Url) - Required - The URL of the remote repository to clone. - **path** (impl AsRef) - Required - The local path where the repository will be created with a working tree. ``` -------------------------------- ### Resource Search Examples Source: https://docs.rs/gix/latest/gix/diff/blob/platform/struct.Resource.html?search= Demonstrates various ways to search for resources using different query patterns. These examples showcase how to find specific types, type conversions, and generic type transformations. ```APIDOC ## Example Searches ### Basic Type Search ``` std::vec ``` ### Type Conversion Search ``` u32 -> bool ``` ### Generic Transformation Search ``` Option, (T -> U) -> Option ``` ``` -------------------------------- ### Utf8Chunk::valid() - Get Valid UTF-8 Slice Source: https://docs.rs/gix/latest/gix/diff/object/bstr/struct.Utf8Chunk.html Returns the valid UTF-8 portion of the chunk. This slice may be empty if the chunk starts with invalid UTF-8 bytes. ```rust pub fn valid(&self) -> &'a str ``` -------------------------------- ### Example: Inspecting Repository HEAD Source: https://docs.rs/gix/latest/src/gix/repository/reference.rs.html Demonstrates how to obtain the HEAD reference and check its state (e.g., referent name, detached, unborn). ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let head = repo.head()?; assert_eq!(head.referent_name().expect("born").as_bstr(), "refs/heads/main"); assert!(!head.is_detached()); assert!(!head.is_unborn()); # Ok(()) } ``` -------------------------------- ### Get Mutable Configuration Snapshot Source: https://docs.rs/gix/latest/gix/config/struct.CommitAutoRollback.html?search=u32+-%3E+bool Returns a mutable snapshot of the repository's configuration, starting a transaction. Changes are applied when the snapshot is dropped. Use `reload()` to discard changes. ```rust let mut config_snapshot_mut = repo.config_snapshot_mut(); ``` -------------------------------- ### prepare Source: https://docs.rs/gix/latest/gix/diff/command/fn.prepare.html?search= Prepares a command for spawning by configuring its builder methods. It sets up default IO for typical API usage: stdin is null, stdout is captured, and stderr is inherited. On Windows, terminal windows are suppressed automatically. Be cautious about relying on the current working directory or environment variables; use `Prepare::with_context()` if necessary. ```APIDOC ## prepare ### Description Prepares `cmd` for spawning by configuring it with various builder methods. Note that the default IO is configured for typical API usage, that is: * `stdin` is null to prevent blocking unexpectedly on consumption of stdin * `stdout` is captured for consumption by the caller * `stderr` is inherited to allow the command to provide context to the user On Windows, terminal Windows will be suppressed automatically. ### Warning When using this method, be sure that the invoked program doesn’t rely on the current working dir and/or environment variables to know its context. If so, call instead `Prepare::with_context()` to provide additional information. ### Signature ```rust pub fn prepare(cmd: impl Into) -> Prepare ``` ``` -------------------------------- ### Get Sentence Indices with ByteSlice Source: https://docs.rs/gix/latest/gix/diff/object/bstr/trait.ByteSlice.html Use `sentence_indices` to iterate over sentences along with their start and end byte positions. This allows for precise location tracking of sentences within the byte string. ```rust use bstr::ByteSlice; let bs = b"I want this. Not that. Right now."; let sentences: Vec<(usize, usize, &str)> = bs.sentence_indices().collect(); assert_eq!(sentences, vec![ (0, 13, "I want this. "), (13, 23, "Not that. "), (23, 33, "Right now."), ]); ``` -------------------------------- ### Iterate Over Substring Occurrences Source: https://docs.rs/gix/latest/gix/diff/object/bstr/index.html?search=std%3A%3Avec Use `find_iter` to get the starting indices of all occurrences of a substring within a byte string. This is useful for tasks requiring precise location information of repeated patterns. ```rust use bstr::ByteSlice; let s = b"foo bar foo foo quux foo"; let mut matches = vec![]; for start in s.find_iter("foo") { matches.push(start); } assert_eq!(matches, [0, 8, 12, 21]); ``` -------------------------------- ### Instantiate File from Repository Directory Source: https://docs.rs/gix/latest/gix/config/struct.File.html Provides complete configuration for a repository by including globals, repository-local config, worktree config, and environment variables. Note that 'dir' should be the .git directory. ```rust pub fn from_git_dir(dir: PathBuf) -> Result, Error> ``` -------------------------------- ### Get Mutable Configuration Snapshot Source: https://docs.rs/gix/latest/src/gix/repository/config/mod.rs.html?search=std%3A%3Avec Returns a mutable snapshot of the repository's configuration, starting a transaction. Changes are applied in-memory when the snapshot is dropped. Use `reload()` to discard changes and refresh from disk. ```rust pub fn config_snapshot_mut(&mut self) -> config::SnapshotMut<'_> { let config = self.config.resolved.as_ref().clone(); config::SnapshotMut { repo: Some(self), config, } } ``` -------------------------------- ### Example: Accessing HEAD Commit and Reference Source: https://docs.rs/gix/latest/src/gix/repository/reference.rs.html?search= Demonstrates how to open a repository, retrieve the HEAD commit, and assert its message and tree ID. It also shows how to parse a previous commit and verify it's different from the HEAD commit. ```rust # fn main() -> Result<(), Box> { # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); } # let repo = doctest::open_repo(doctest::basic_repo_dir()?)?; let head = repo.head_commit()?; assert_eq!(head.decode()?.message, "c2\n"); assert_eq!(repo.head_tree_id()?, head.tree_id()?); let previous = repo.rev_parse_single("HEAD^")?; assert_ne!(previous, head.id); # Ok(()) } ``` -------------------------------- ### Getting Grapheme Cluster Indices Source: https://docs.rs/gix/latest/gix/worktree/object/bstr/trait.ByteSlice.html?search=std%3A%3Avec Use `grapheme_indices` to obtain an iterator yielding tuples of (start byte index, end byte index, grapheme cluster string). This is useful for precise positioning of graphemes. ```rust use bstr::ByteSlice; let bs = "a\u{0300}\u{0316}\u{1F1FA}\u{1F1F8}".as_bytes(); let graphemes: Vec<(usize, usize, &str)> = bs.grapheme_indices().collect(); assert_eq!(graphemes, vec![(0, 5, "à̖"), (5, 13, "🇺🇸")]); ``` -------------------------------- ### Open Repository with Options Source: https://docs.rs/gix/latest/src/gix/open/options.rs.html Opens a repository at the specified path using the configured options. This is the final step in the options builder pattern. ```rust pub fn open(self, path: impl Into) -> Result { ThreadSafeRepository::open_opts(path, self) } ``` -------------------------------- ### Get Word and Break Indices with ByteSlice Source: https://docs.rs/gix/latest/gix/diff/object/bstr/trait.ByteSlice.html Use `words_with_break_indices` to obtain an iterator yielding tuples of (start byte, end byte, word slice). This is useful for locating words within the byte string. ```rust use bstr::ByteSlice; let bs = b"can't jump 32.3 feet"; let words: Vec<(usize, usize, &str)> = bs.words_with_break_indices().collect(); assert_eq!(words, vec![ (0, 5, "can't"), (5, 6, " "), (6, 10, "jump"), (10, 11, " "), (11, 15, "32.3"), (15, 16, " "), (16, 20, "feet"), ]); ``` -------------------------------- ### Prepare Bare Clone Source: https://docs.rs/gix/latest/src/gix/lib.rs.html Creates a configuration platform for a bare clone from a URL to a local path. It uses default options but includes git configuration to honor authentication. ```rust pub fn prepare_clone_bare( url: Url, path: impl AsRef, ) -> Result where Url: std::convert::TryInto, gix_url::parse::Error: From, { clone::PrepareFetch::new( url, path, create::Kind::Bare, create::Options::default(), open_opts_with_git_binary_config(), ) } ```