use crate::sources::git;
use crate::sources::git::fetch::RemoteKind;
use crate::sources::git::resolve_ref;
use crate::sources::registry::MaybeLock;
use crate::sources::registry::download;
use crate::sources::registry::{LoadResponse, RegistryConfig, RegistryData};
use crate::util::cache_lock::CacheLockMode;
use crate::util::errors::CargoResult;
use crate::util::interning::InternedString;
use crate::util::{Filesystem, GlobalContext};
use crate::workspace::global_cache_tracker;
use crate::workspace::{GitReference, PackageId, SourceId};
use anyhow::Context as _;
use cargo_util::paths;
use std::cell::{Cell, Ref, RefCell};
use std::fs::File;
use std::mem;
use std::path::Path;
use std::str;
use tracing::{debug, trace};
pub struct GitRegistry<'gctx> {
name: InternedString,
index_path: Filesystem,
cache_path: Filesystem,
source_id: SourceId,
index_git_ref: GitReference,
gctx: &'gctx GlobalContext,
tree: RefCell<Option<git2::Tree<'static>>>,
repo: RefCell<Option<git2::Repository>>,
head: Cell<Option<git2::Oid>>,
current_sha: Cell<Option<InternedString>>,
needs_update: Cell<bool>,
quiet: bool,
}
impl<'gctx> GitRegistry<'gctx> {
pub fn new(source_id: SourceId, gctx: &'gctx GlobalContext, name: &str) -> GitRegistry<'gctx> {
GitRegistry {
name: name.into(),
index_path: gctx.registry_index_path().join(name),
cache_path: gctx.registry_cache_path().join(name),
source_id,
gctx,
index_git_ref: GitReference::DefaultBranch,
tree: RefCell::new(None),
repo: RefCell::new(None),
head: Cell::new(None),
current_sha: Cell::new(None),
needs_update: Cell::new(false),
quiet: false,
}
}
fn repo(&self) -> CargoResult<Ref<'_, Option<git2::Repository>>> {
if self.repo.borrow().is_none() {
trace!("acquiring registry index lock");
let path = self
.gctx
.assert_package_cache_locked(CacheLockMode::DownloadExclusive, &self.index_path);
self.repo.replace(Some(match git2::Repository::open(&path) {
Ok(repo) => repo,
Err(_) => {
drop(paths::remove_dir_all(&path));
paths::create_dir_all(&path)?;
let mut opts = git2::RepositoryInitOptions::new();
opts.external_template(false);
git2::Repository::init_opts(&path, &opts).with_context(|| {
format!("failed to initialize index git repository (in {:?})", path)
})?
}
}));
}
Ok(self.repo.borrow())
}
fn head(&self) -> CargoResult<git2::Oid> {
if self.head.get().is_none() {
let repo = self.repo()?;
let repo = repo.as_ref().unwrap();
let oid = resolve_ref(&self.index_git_ref, repo)?;
self.head.set(Some(oid));
}
Ok(self.head.get().unwrap())
}
fn tree(&self) -> CargoResult<Ref<'_, git2::Tree<'_>>> {
{
let tree = self.tree.borrow();
if tree.is_some() {
return Ok(Ref::map(tree, |s| s.as_ref().unwrap()));
}
}
let repo = self.repo()?;
let repo = repo.as_ref().unwrap();
let commit = repo.find_commit(self.head()?)?;
let tree = commit.tree()?;
let tree = unsafe { mem::transmute::<git2::Tree<'_>, git2::Tree<'static>>(tree) };
*self.tree.borrow_mut() = Some(tree);
Ok(Ref::map(self.tree.borrow(), |s| s.as_ref().unwrap()))
}
fn current_version(&self) -> Option<InternedString> {
if let Some(sha) = self.current_sha.get() {
return Some(sha);
}
let sha = self.head().ok()?.to_string().into();
self.current_sha.set(Some(sha));
Some(sha)
}
fn is_updated(&self) -> bool {
self.gctx.updated_sources().contains(&self.source_id)
}
fn mark_updated(&self) {
self.gctx.updated_sources().insert(self.source_id);
}
fn update(&self) -> CargoResult<()> {
if !self.needs_update.get() {
return Ok(());
}
self.needs_update.set(false);
if self.is_updated() {
return Ok(());
}
self.mark_updated();
if !self.gctx.network_allowed() {
return Ok(());
}
if self.gctx.cli_unstable().no_index_update {
return Ok(());
}
debug!("updating the index");
self.gctx.http()?;
self.prepare()?;
self.head.set(None);
*self.tree.borrow_mut() = None;
self.current_sha.set(None);
let _path = self
.gctx
.assert_package_cache_locked(CacheLockMode::DownloadExclusive, &self.index_path);
if !self.quiet {
self.gctx
.shell()
.status("Updating", self.source_id.display_index())?;
}
let url = self.source_id.url();
let mut repo = self.repo.borrow_mut();
let repo = repo.as_mut().unwrap();
git::fetch(
repo,
url.as_str(),
&self.index_git_ref,
&self.index_git_ref,
self.gctx,
RemoteKind::Registry,
)
.with_context(|| format!("failed to fetch `{}`", url))?;
Ok(())
}
}
#[async_trait::async_trait(?Send)]
impl<'gctx> RegistryData for GitRegistry<'gctx> {
fn prepare(&self) -> CargoResult<()> {
self.repo()?;
self.gctx
.deferred_global_last_use()?
.mark_registry_index_used(global_cache_tracker::RegistryIndex {
encoded_registry_name: self.name,
});
Ok(())
}
fn index_path(&self) -> &Filesystem {
&self.index_path
}
fn cache_path(&self) -> &Filesystem {
&self.cache_path
}
fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path {
self.gctx
.assert_package_cache_locked(CacheLockMode::DownloadExclusive, path)
}
async fn load(
&self,
_root: &Path,
path: &Path,
index_version: Option<&str>,
) -> CargoResult<LoadResponse> {
if self.needs_update.get() {
self.update()?;
}
let git_commit_hash = self.current_version();
if index_version.is_some() && index_version == git_commit_hash.as_deref() {
return Ok(LoadResponse::CacheValid);
}
fn load_helper(
registry: &GitRegistry<'_>,
path: &Path,
index_version: Option<&str>,
) -> CargoResult<LoadResponse> {
let repo = registry.repo()?;
let repo = repo.as_ref().unwrap();
let tree = registry.tree()?;
let entry = tree.get_path(path);
let entry = entry?;
let git_file_hash = Some(entry.id().to_string());
if index_version.is_some() && index_version == git_file_hash.as_deref() {
return Ok(LoadResponse::CacheValid);
}
let object = entry.to_object(repo)?;
let Some(blob) = object.as_blob() else {
anyhow::bail!("path `{}` is not a blob in the git repo", path.display())
};
Ok(LoadResponse::Data {
raw_data: blob.content().to_vec(),
index_version: git_file_hash,
})
}
loop {
return match load_helper(&self, path, index_version) {
Ok(result) => Ok(result),
Err(_) if !self.is_updated() => {
self.needs_update.set(true);
self.update()?;
continue;
}
Err(e)
if e.downcast_ref::<git2::Error>()
.map(|e| e.code() == git2::ErrorCode::NotFound)
.unwrap_or_default() =>
{
Ok(LoadResponse::NotFound)
}
Err(e) => Err(e),
};
}
}
async fn config(&self) -> CargoResult<Option<RegistryConfig>> {
debug!("loading config");
self.prepare()?;
self.gctx
.assert_package_cache_locked(CacheLockMode::DownloadExclusive, &self.index_path);
match self
.load(Path::new(""), Path::new(RegistryConfig::NAME), None)
.await?
{
LoadResponse::Data { raw_data, .. } => {
trace!("config loaded");
let cfg: RegistryConfig = serde_json::from_slice(&raw_data)?;
Ok(Some(cfg))
}
_ => Ok(None),
}
}
fn invalidate_cache(&self) {
self.needs_update.set(true);
}
fn set_quiet(&mut self, quiet: bool) {
self.quiet = quiet;
}
fn is_updated(&self) -> bool {
self.is_updated()
}
async fn download(&self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> {
let registry_config = self.config().await?.unwrap();
download::download(
&self.cache_path,
&self.gctx,
self.name,
pkg,
checksum,
registry_config,
)
}
async fn finish_download(
&self,
pkg: PackageId,
checksum: &str,
data: &[u8],
) -> CargoResult<File> {
download::finish_download(
&self.cache_path,
&self.gctx,
self.name.clone(),
pkg,
checksum,
data,
)
}
fn is_crate_downloaded(&self, pkg: PackageId) -> bool {
download::is_crate_downloaded(&self.cache_path, &self.gctx, pkg)
}
}
impl<'gctx> Drop for GitRegistry<'gctx> {
fn drop(&mut self) {
self.tree.borrow_mut().take();
}
}