use std::path::{Path, PathBuf};
pub struct CheckedOutRepo {
pub dir: PathBuf,
pub commit_sha: String,
}
pub async fn fetch_at_tag(
temp_dir: &Path,
plugins_dir: Option<&Path>,
owner: &str,
name: &str,
tag: &str,
) -> Result<CheckedOutRepo, String> {
let dir = temp_dir.join(uuid::Uuid::new_v4().to_string());
tokio::fs::create_dir_all(&dir)
.await
.map_err(|e| format!("create checkout dir: {e}"))?;
let result = {
let dir = dir.clone();
let plugins_dir = plugins_dir.map(Path::to_path_buf);
let refspec = format!("+refs/tags/{tag}:refs/tags/{tag}");
let reference = format!("refs/tags/{tag}");
let owner = owner.to_string();
let name = name.to_string();
let tag = tag.to_string();
tokio::task::spawn_blocking(move || {
let source = resolve_source(plugins_dir.as_deref(), &owner, &name, &tag);
fetch_at_tag_blocking(&dir, &source, &refspec, &reference, &owner, &name, &tag)
})
.await
.map_err(|e| format!("fetch task panicked: {e}"))?
};
match result {
Ok(commit_sha) => Ok(CheckedOutRepo { dir, commit_sha }),
Err(message) => {
remove_checkout(&dir).await;
Err(message)
}
}
}
enum Source {
Local(String),
Remote(String),
}
impl Source {
fn url(&self) -> &str {
match self {
Source::Local(url) | Source::Remote(url) => url,
}
}
}
fn resolve_source(plugins_dir: Option<&Path>, owner: &str, name: &str, tag: &str) -> Source {
if let Some(plugins_dir) = plugins_dir
&& let Some(local) = local_plugin_dir(plugins_dir, owner, name)
&& local_has_tag(&local, tag)
{
let local = local.to_string_lossy();
return Source::Local(if cfg!(windows) {
local.replace('\\', "/")
} else {
local.into_owned()
});
}
Source::Remote(format!("https://github.com/{owner}/{name}.git"))
}
fn local_plugin_dir(plugins_dir: &Path, owner: &str, name: &str) -> Option<PathBuf> {
let owner_dir = resolve_segment_ci(plugins_dir, owner)?;
resolve_segment_ci(&owner_dir, name)
}
fn resolve_segment_ci(parent: &Path, target: &str) -> Option<PathBuf> {
let entries: Vec<PathBuf> = std::fs::read_dir(parent)
.ok()?
.flatten()
.map(|entry| entry.path())
.collect();
let matches_target = |path: &&PathBuf, exact: bool| {
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
if exact {
n == target
} else {
n.eq_ignore_ascii_case(target)
}
})
};
entries
.iter()
.find(|path| matches_target(path, true))
.or_else(|| entries.iter().find(|path| matches_target(path, false)))
.cloned()
}
fn local_has_tag(dir: &Path, tag: &str) -> bool {
git2::Repository::open(dir)
.and_then(|repo| repo.refname_to_id(&format!("refs/tags/{tag}")))
.is_ok()
}
fn fetch_at_tag_blocking(
dir: &Path,
source: &Source,
refspec: &str,
reference: &str,
owner: &str,
name: &str,
tag: &str,
) -> Result<String, String> {
let url = source.url();
let repo = git2::Repository::init(dir).map_err(|e| format!("git init: {e}"))?;
let mut remote = repo
.remote_anonymous(url)
.map_err(|e| format!("git remote: {e}"))?;
let mut options = git2::FetchOptions::new();
if matches!(source, Source::Remote(_)) {
options.depth(1);
}
options.download_tags(git2::AutotagOption::None);
remote
.fetch(&[refspec], Some(&mut options), None)
.map_err(|e| {
let message = e.message().to_ascii_lowercase();
if message.contains("couldn't find remote ref")
|| message.contains("could not find remote ref")
|| message.contains(&format!("refs/tags/{tag}").to_ascii_lowercase())
{
format!("plugin tag '{tag}' not found in {owner}/{name}")
} else if matches!(
e.class(),
git2::ErrorClass::Net | git2::ErrorClass::Http
) {
format!("fetch {url}: {e}")
} else {
format!("git fetch {url}: {e}")
}
})?;
let commit = repo
.find_reference(reference)
.map_err(|_| format!("plugin tag '{tag}' not found in {owner}/{name}"))?
.peel_to_commit()
.map_err(|e| format!("peel tag '{tag}': {e}"))?;
let commit_sha = commit.id().to_string();
repo.set_head_detached(commit.id())
.map_err(|e| format!("detach head at '{tag}': {e}"))?;
let mut checkout = git2::build::CheckoutBuilder::new();
checkout.force();
repo.checkout_head(Some(&mut checkout))
.map_err(|e| format!("checkout '{tag}': {e}"))?;
Ok(commit_sha)
}
pub async fn remove_checkout(dir: &Path) {
let dir = dir.to_path_buf();
let result = tokio::task::spawn_blocking(move || {
clear_readonly(&dir);
std::fs::remove_dir_all(&dir)
})
.await;
match result {
Ok(Ok(())) => {}
Ok(Err(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
Ok(Err(e)) => eprintln!("remove checkout: {e}"),
Err(e) => eprintln!("remove checkout task panicked: {e}"),
}
}
fn clear_readonly(path: &Path) {
if let Ok(metadata) = std::fs::symlink_metadata(path) {
let mut permissions = metadata.permissions();
if permissions.readonly() {
#[allow(clippy::permissions_set_readonly_false)]
permissions.set_readonly(false);
let _ = std::fs::set_permissions(path, permissions);
}
if metadata.is_dir()
&& let Ok(entries) = std::fs::read_dir(path)
{
for entry in entries.flatten() {
clear_readonly(&entry.path());
}
}
}
}
pub async fn sweep_temp(temp_dir: &Path) {
let Ok(mut entries) = tokio::fs::read_dir(temp_dir).await else {
return;
};
while let Ok(Some(entry)) = entries.next_entry().await {
remove_checkout(&entry.path()).await;
}
}