tlrepo/lib.rs
1//! `tlrepo` provides `ThreadLocalRepo`, a convenient way to share a `git2::Repository` object
2//! between threads.
3//!
4//! A standard `git2::Repository` object does not support sharing among threads without some form
5//! of synchronization. `tlrepo::ThreadLocalRepo` provides a convenient way to reopen the same
6//! repository on each thread, caching the opened repository thread-locally for reuse.
7//!
8//! You can create a `ThreadLocalRepo` by calling `ThreadLocalRepo::new`, or by using the extension
9//! trait `tlrepo::RepositoryExt` to call `.thread_local()` on an existing `git2::Repository`.
10#![deny(missing_docs)]
11use std::path::PathBuf;
12
13use git2::Repository;
14use thread_local::ThreadLocal;
15
16/// An object providing a thread-local copy of a `git2::Repository` for each thread.
17pub struct ThreadLocalRepo {
18 tl: ThreadLocal<Repository>,
19 path: PathBuf,
20}
21
22impl ThreadLocalRepo {
23 /// Create a `ThreadLocalRepo` that opens the repository at the specified path on each thread.
24 pub fn new(path: PathBuf) -> Self {
25 Self {
26 path,
27 tl: ThreadLocal::new(),
28 }
29 }
30
31 /// Get the `git2::Repository` for this thread. Returns an error if the open fails.
32 ///
33 /// Note that the cache of thread-local objects never gets pruned. If you're running on a
34 /// long-running thread or a thread pool, call this method. If you're running on a short-lived
35 /// thread, call `get_uncached` instead.
36 pub fn get(&self) -> Result<&Repository, git2::Error> {
37 self.tl.get_or_try(|| Repository::open(&self.path))
38 }
39
40 /// Get a new `git2::Repository`, and don't save it in the thread-local cache. Returns an error
41 /// if the open fails.
42 ///
43 /// The cache of thread-local objects never gets pruned. If, over the lifetime of your process,
44 /// you run an unbounded number of threads that call `get` and subsequently exit, the
45 /// thread-local cache will grow without bound. In such threads, use `get_uncached` to open a
46 /// repository that won't get cached.
47 pub fn get_uncached(&self) -> Result<Repository, git2::Error> {
48 Repository::open(&self.path)
49 }
50}
51
52/// Extension trait for `git2::Repository`, to create a `ThreadLocalRepo` with the path to the
53/// repository.
54pub trait RepositoryExt {
55 /// Get a `ThreadLocalRepo` that reopens the path to this `git2::Repository` on each thread.
56 fn thread_local(&self) -> ThreadLocalRepo;
57}
58
59impl RepositoryExt for Repository {
60 fn thread_local(&self) -> ThreadLocalRepo {
61 ThreadLocalRepo::new(self.path().to_path_buf())
62 }
63}