Skip to main content

gix/
lib.rs

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<dyn std::error::Error + Send + Sync>> {
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//! ```
22//!
23//! ### The Trust Model
24//!
25//! It is very simple - based on the ownership of the repository compared to the user of the current process [Trust](sec::Trust)
26//! is assigned. This can be [overridden](open::Options::with()) as well. Further, git configuration files track their trust level
27//! per section based on and sensitive values like paths to executables or certain values will be skipped if they are from a source
28//! that isn't [fully](sec::Trust::Full) trusted.
29//!
30//! That way, data can safely be obtained without risking to execute untrusted executables.
31//!
32//! Note that it's possible to let `gix` act like `git` or `git2` by setting the [open::Options::bail_if_untrusted()] option.
33//!
34//! ### The prelude and extensions
35//!
36//! With `use git_repository::prelude::*` you should be ready to go as it pulls in various extension traits to make functionality
37//! available on objects that may use it.
38//!
39//! The method signatures are still complex and may require various arguments for configuration and cache control.
40//!
41//! Most extensions to existing objects provide an `obj_with_extension.attach(&repo).an_easier_version_of_a_method()` for simpler
42//! call signatures.
43//!
44//! ### `ThreadSafe` Mode
45//!
46//! By default, the [`Repository`] isn't `Sync` and thus can't be used in certain contexts which require the `Sync` trait.
47//!
48//! To help with this, convert it with [`Repository::into_sync()`] into a [`ThreadSafeRepository`].
49//!
50//! ### Object-Access Performance
51//!
52//! Accessing objects quickly is the bread-and-butter of working with git, right after accessing references. Hence it's vital
53//! to understand which cache levels exist and how to leverage them.
54//!
55//! When accessing an object, the first cache that's queried is a  memory-capped LRU object cache, mapping their id to data and kind.
56//! It has to be specifically enabled on a [`Repository`].
57//! On miss, the object is looked up and if a pack is hit, there is a small fixed-size cache for delta-base objects.
58//!
59//! In scenarios where the same objects are accessed multiple times, the object cache can be useful and is to be configured specifically
60//! using the [`Repository::object_cache_size()`] method.
61//!
62//! Use the `cache-efficiency-debug` cargo feature to learn how efficient the cache actually is - it's easy to end up with lowered
63//! performance if the cache is not hit in 50% of the time.
64//!
65//! ### Terminology
66//!
67//! #### `WorkingTree` and `WorkTree`
68//!
69//! When reading the documentation of the canonical gix-worktree program one gets the impression work tree and working tree are used
70//! interchangeably. We use the term _work tree_ only and try to do so consistently as its shorter and assumed to be the same.
71//!
72//! ### Plumbing Crates
73//!
74//! To make using  _sub-crates_ and their types easier, these are re-exported into the root of this crate. Here we list how to access nested plumbing
75//! crates which are otherwise harder to discover:
76//!
77//! **`git_repository::`**
78//! * [`odb`]
79//!   * [`pack`][odb::pack]
80//! * [`protocol`]
81//!   * [`transport`][protocol::transport]
82//!     * [`packetline`][protocol::transport::packetline]
83//!
84//! ### `libgit2` API to `gix`
85//!
86//! This doc-aliases are used to help finding methods under a possibly changed name. Just search in the docs.
87//! Entering `git2` into the search field will also surface all methods with such annotations.
88//!
89//! What follows is a list of methods you might be missing, along with workarounds if available.
90//! * [`git2::Repository::open_bare()`](https://docs.rs/git2/*/git2/struct.Repository.html#method.open_bare) ➡ ❌ - use [`open()`] and discard if it is not bare.
91//! * [`git2::build::CheckoutBuilder::disable_filters()`](https://docs.rs/git2/*/git2/build/struct.CheckoutBuilder.html#method.disable_filters) ➡ ❌ *(filters are always applied during checkouts)*
92//! * [`git2::Repository::submodule_status()`](https://docs.rs/git2/*/git2/struct.Repository.html#method.submodule_status) ➡ [`Submodule::state()`] - status provides more information and conveniences though, and an actual worktree status isn't performed.
93//!
94//! #### Integrity checks
95//!
96//! `git2` by default performs integrity checks via [`strict_hash_verification()`](https://docs.rs/git2/latest/git2/opts/fn.strict_hash_verification.html) and
97//! [`strict_object_creation`](https://docs.rs/git2/latest/git2/opts/fn.strict_object_creation.html) which `gitoxide` *currently* **does not have**.
98//!
99//! ### Feature Flags
100#![cfg_attr(
101    all(doc, feature = "document-features"),
102    doc = ::document_features::document_features!()
103)]
104#![cfg_attr(all(doc, feature = "document-features"), feature(doc_cfg))]
105#![deny(missing_docs, unsafe_code)]
106#![allow(clippy::result_large_err)]
107
108// Re-exports to make this a potential one-stop shop crate avoiding people from having to reference various crates themselves.
109// This also means that their major version changes affect our major version, but that's alright as we directly expose their
110// APIs/instances anyway.
111pub use gix_actor as actor;
112#[cfg(feature = "attributes")]
113pub use gix_attributes as attrs;
114#[cfg(feature = "blame")]
115pub use gix_blame as blame;
116#[cfg(feature = "command")]
117pub use gix_command as command;
118pub use gix_commitgraph as commitgraph;
119#[cfg(feature = "credentials")]
120pub use gix_credentials as credentials;
121pub use gix_date as date;
122#[cfg(feature = "dirwalk")]
123pub use gix_dir as dir;
124pub use gix_error as error;
125pub use gix_features as features;
126use gix_features::threading::OwnShared;
127pub use gix_features::{
128    parallel,
129    progress::{Count, DynNestedProgress, NestedProgress, Progress},
130    threading,
131};
132pub use gix_fs as fs;
133pub use gix_glob as glob;
134pub use gix_hash as hash;
135pub use gix_hashtable as hashtable;
136#[cfg(feature = "excludes")]
137pub use gix_ignore as ignore;
138#[doc(inline)]
139#[cfg(feature = "index")]
140pub use gix_index as index;
141pub use gix_lock as lock;
142#[cfg(feature = "credentials")]
143pub use gix_negotiate as negotiate;
144pub use gix_object as objs;
145pub use gix_object::bstr;
146pub use gix_odb as odb;
147#[cfg(feature = "credentials")]
148pub use gix_prompt as prompt;
149pub use gix_protocol as protocol;
150pub use gix_ref as refs;
151pub use gix_refspec as refspec;
152pub use gix_revwalk as revwalk;
153pub use gix_sec as sec;
154pub use gix_tempfile as tempfile;
155pub use gix_trace as trace;
156pub use gix_traverse as traverse;
157pub use gix_url as url;
158#[doc(inline)]
159pub use gix_url::Url;
160pub use gix_utils as utils;
161pub use gix_validate as validate;
162pub use gix_zlib as zlib;
163pub use hash::{ObjectId, oid};
164
165pub use gix_error::{Error, Exn};
166
167pub mod interrupt;
168
169mod ext;
170///
171pub mod prelude;
172
173#[cfg(feature = "excludes")]
174mod attribute_stack;
175
176///
177pub mod path;
178
179/// The standard type for a store to handle git references.
180pub type RefStore = gix_ref::file::Store;
181/// A handle for finding objects in an object database, abstracting away caches for thread-local use.
182pub type OdbHandle = gix_odb::memory::Proxy<gix_odb::Handle>;
183/// A handle for finding objects in an object database, abstracting away caches for moving across threads.
184pub type OdbHandleArc = gix_odb::memory::Proxy<gix_odb::HandleArc>;
185
186/// A way to access git configuration
187pub(crate) type Config = OwnShared<gix_config::File>;
188
189mod types;
190#[cfg(any(feature = "excludes", feature = "attributes"))]
191pub use types::AttributeStack;
192pub use types::{
193    Blob, Commit, Head, Id, Object, ObjectDetached, Reference, Remote, Repository, Tag, ThreadSafeRepository, Tree,
194    Worktree,
195};
196#[cfg(feature = "attributes")]
197pub use types::{Pathspec, PathspecDetached, Submodule};
198
199///
200pub mod clone;
201pub mod commit;
202///
203#[cfg(feature = "dirwalk")]
204pub mod dirwalk;
205pub mod head;
206pub mod id;
207pub mod object;
208#[cfg(feature = "attributes")]
209pub mod pathspec;
210pub mod reference;
211pub mod repository;
212#[cfg(feature = "attributes")]
213pub mod submodule;
214pub mod tag;
215#[cfg(any(feature = "dirwalk", feature = "status"))]
216pub(crate) mod util;
217
218///
219pub mod progress;
220///
221pub mod push;
222
223///
224pub mod diff;
225
226///
227#[cfg(feature = "merge")]
228pub mod merge;
229
230/// Try to open a git repository in `directory` and search upwards through its parents until one is found,
231/// using default trust options which matters in case the found repository isn't owned by the current user.
232///
233/// For details, see [`ThreadSafeRepository::discover()`].
234///
235/// # Note
236///
237/// **The discovered repository might not be suitable for any operation that requires authentication with remotes**
238/// as it doesn't see the relevant git configuration.
239///
240/// To achieve that, one has to [enable `git_binary` configuration](https://github.com/GitoxideLabs/gitoxide/blob/9723e1addf52cc336d59322de039ea0537cdca36/src/plumbing/main.rs#L86)
241/// in the open-options and use [`ThreadSafeRepository::discover_opts()`] instead. Alternatively, it might be well-known
242/// that the tool is going to run in a neatly configured environment without relying on bundled configuration.
243///
244/// # Examples
245///
246/// ```
247/// # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
248/// # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); }
249/// # let repo_dir = doctest::basic_repo_dir()?;
250/// let repo = doctest::discover_repo(repo_dir.join("some/very/deeply/nested/subdir"))?;
251///
252/// assert_eq!(repo.kind(), gix::repository::Kind::Common);
253/// assert_eq!(repo.head_name()?.expect("born").shorten(), "main");
254/// assert!(repo.workdir_path("this").expect("non-bare").is_file());
255/// # Ok(()) }
256/// ```
257#[expect(
258    clippy::result_large_err,
259    reason = "will be removed once `gix-error` is used consistently"
260)]
261pub fn discover(directory: impl AsRef<std::path::Path>) -> Result<Repository, discover::Error> {
262    ThreadSafeRepository::discover(directory).map(Into::into)
263}
264
265/// Try to open a git repository in `directory` and search upwards through its parents until one is found,
266/// using `open_options` regardless of the trust level of the discovered repository.
267/// The detected trust level is retained, so repositories with reduced trust still restrict their behavior accordingly.
268#[expect(
269    clippy::result_large_err,
270    reason = "will be removed once `gix-error` is used consistently"
271)]
272pub fn discover_opts(
273    directory: impl AsRef<std::path::Path>,
274    options: discover::upwards::Options<'_>,
275    open_options: open::Options,
276) -> Result<Repository, discover::Error> {
277    ThreadSafeRepository::discover_opts(
278        directory,
279        options,
280        sec::trust::Mapping {
281            full: open_options.clone(),
282            reduced: open_options,
283        },
284    )
285    .map(Into::into)
286}
287
288/// Try to discover a git repository directly from the environment.
289///
290/// For details, see [`ThreadSafeRepository::discover_with_environment_overrides_opts()`].
291#[expect(
292    clippy::result_large_err,
293    reason = "will be removed once `gix-error` is used consistently"
294)]
295pub fn discover_with_environment_overrides(
296    directory: impl AsRef<std::path::Path>,
297) -> Result<Repository, discover::Error> {
298    ThreadSafeRepository::discover_with_environment_overrides(directory).map(Into::into)
299}
300
301/// Try to open a git repository directly from the environment.
302///
303/// See [`ThreadSafeRepository::open_with_environment_overrides()`].
304#[expect(
305    clippy::result_large_err,
306    reason = "will be removed once `gix-error` is used consistently"
307)]
308pub fn open_with_environment_overrides(directory: impl Into<std::path::PathBuf>) -> Result<Repository, open::Error> {
309    ThreadSafeRepository::open_with_environment_overrides(directory, Default::default()).map(Into::into)
310}
311
312/// See [`ThreadSafeRepository::init()`], but returns a [`Repository`] instead.
313///
314/// # Examples
315///
316/// ```
317/// # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
318/// # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); }
319/// # let dir = doctest::tempdir()?;
320/// let repo = gix::init(dir.path())?;
321///
322/// assert!(repo.git_dir().is_dir());
323/// assert!(repo.head_name()?.is_some());
324/// assert!(repo.head()?.is_unborn());
325/// # Ok(()) }
326/// ```
327#[expect(
328    clippy::result_large_err,
329    reason = "will be removed once `gix-error` is used consistently"
330)]
331pub fn init(directory: impl AsRef<std::path::Path>) -> Result<Repository, init::Error> {
332    ThreadSafeRepository::init(directory, create::Kind::WithWorktree, create::Options::default()).map(Into::into)
333}
334
335/// See [`ThreadSafeRepository::init()`], but returns a [`Repository`] instead.
336#[expect(
337    clippy::result_large_err,
338    reason = "will be removed once `gix-error` is used consistently"
339)]
340pub fn init_bare(directory: impl AsRef<std::path::Path>) -> Result<Repository, init::Error> {
341    ThreadSafeRepository::init(directory, create::Kind::Bare, create::Options::default()).map(Into::into)
342}
343
344/// Create a platform for configuring a bare clone from `url` to the local `path`, using default options for opening it (but
345/// amended with using configuration from the git installation to ensure all authentication options are honored).
346///
347/// See [`clone::PrepareFetch::new()`] for a function to take full control over all options.
348#[expect(
349    clippy::result_large_err,
350    reason = "will be removed once `gix-error` is used consistently"
351)]
352pub fn prepare_clone_bare<Url, E>(
353    url: Url,
354    path: impl AsRef<std::path::Path>,
355) -> Result<clone::PrepareFetch, clone::Error>
356where
357    Url: std::convert::TryInto<gix_url::Url, Error = E>,
358    gix_url::parse::Error: From<E>,
359{
360    clone::PrepareFetch::new(
361        url,
362        path,
363        create::Kind::Bare,
364        create::Options::default(),
365        open_opts_with_git_binary_config(),
366    )
367}
368
369/// Create a platform for configuring a clone with main working tree from `url` to the local `path`, using default options for opening it
370/// (but amended with using configuration from the git installation to ensure all authentication options are honored).
371///
372/// See [`clone::PrepareFetch::new()`] for a function to take full control over all options.
373#[expect(
374    clippy::result_large_err,
375    reason = "will be removed once `gix-error` is used consistently"
376)]
377pub fn prepare_clone<Url, E>(url: Url, path: impl AsRef<std::path::Path>) -> Result<clone::PrepareFetch, clone::Error>
378where
379    Url: std::convert::TryInto<gix_url::Url, Error = E>,
380    gix_url::parse::Error: From<E>,
381{
382    clone::PrepareFetch::new(
383        url,
384        path,
385        create::Kind::WithWorktree,
386        create::Options::default(),
387        open_opts_with_git_binary_config(),
388    )
389}
390
391fn open_opts_with_git_binary_config() -> open::Options {
392    use gix_sec::trust::DefaultForLevel;
393    let mut opts = open::Options::default_for_level(gix_sec::Trust::Full);
394    opts.permissions.config.git_binary = true;
395    opts
396}
397
398/// See [`ThreadSafeRepository::open()`], but returns a [`Repository`] instead.
399///
400/// # Examples
401///
402/// ```
403/// # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
404/// # mod doctest { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doctest.rs")); }
405/// # let repo_dir = doctest::basic_repo_dir()?;
406/// let repo = doctest::open_repo(repo_dir)?;
407///
408/// assert_eq!(repo.head_name()?.expect("born").shorten(), "main");
409/// assert_eq!(repo.head_commit()?.decode()?.message, "c2\n");
410/// # Ok(()) }
411/// ```
412#[expect(
413    clippy::result_large_err,
414    reason = "will be removed once `gix-error` is used consistently"
415)]
416#[doc(alias = "git2")]
417pub fn open(directory: impl Into<std::path::PathBuf>) -> Result<Repository, open::Error> {
418    ThreadSafeRepository::open(directory).map(Into::into)
419}
420
421/// See [`ThreadSafeRepository::open_opts()`], but returns a [`Repository`] instead.
422#[expect(
423    clippy::result_large_err,
424    reason = "will be removed once `gix-error` is used consistently"
425)]
426#[doc(alias = "open_ext", alias = "git2")]
427pub fn open_opts(directory: impl Into<std::path::PathBuf>, options: open::Options) -> Result<Repository, open::Error> {
428    ThreadSafeRepository::open_opts(directory, options).map(Into::into)
429}
430
431///
432pub mod create;
433
434///
435pub mod open;
436
437///
438pub mod config;
439
440///
441#[cfg(feature = "mailmap")]
442pub mod mailmap;
443
444///
445pub mod worktree;
446
447pub mod revision;
448
449#[cfg(feature = "attributes")]
450pub mod filter;
451
452///
453pub mod remote;
454
455///
456pub mod init;
457
458/// Not to be confused with 'status'.
459pub mod state;
460
461///
462#[cfg(feature = "status")]
463pub mod status;
464
465///
466pub mod shallow;
467
468///
469pub mod discover;
470
471pub mod env;
472
473#[cfg(feature = "attributes")]
474fn is_dir_to_mode(is_dir: bool) -> gix_index::entry::Mode {
475    if is_dir {
476        gix_index::entry::Mode::DIR
477    } else {
478        gix_index::entry::Mode::FILE
479    }
480}