use std::collections::HashSet;
use std::path::{Path, PathBuf};
use anyhow::Context;
use async_trait::async_trait;
use tokio::fs;
use crate::config;
use crate::github::http::{FileFetch, GhHttp};
use crate::store::TaskStore;
use crate::store::cluster::registry;
use crate::sys::home;
const CONFIG_FILE: &str = ".orch.yml";
const ETAG_FILE: &str = ".orch.yml.etag";
#[async_trait]
pub(crate) trait Contents: Send + Sync {
async fn orch_yml(&self, repo: &str, etag: Option<&str>) -> anyhow::Result<FileFetch>;
}
#[async_trait]
impl Contents for GhHttp {
async fn orch_yml(&self, repo: &str, etag: Option<&str>) -> anyhow::Result<FileFetch> {
self.get_file_if_changed(repo, CONFIG_FILE, etag).await
}
}
pub(crate) async fn remote_projects(store: &TaskStore, hosted: &HashSet<String>) -> Vec<String> {
if store.node().is_none() {
return Vec::new();
}
match registry::read(store).await {
Ok(entries) => registry::hosts_by_project(&entries)
.into_keys()
.filter(|repo| !hosted.contains(repo))
.collect(),
Err(e) => {
tracing::warn!(err = %e, "cannot read the node registry for the cluster's projects");
Vec::new()
}
}
}
fn valid_slug(repo: &str) -> bool {
let mut parts = repo.split('/');
let ok = |p: Option<&str>| {
p.is_some_and(|p| {
!p.is_empty()
&& p != "."
&& p != ".."
&& p.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
})
};
ok(parts.next()) && ok(parts.next()) && parts.next().is_none()
}
pub(crate) fn config_dir(repo: &str) -> anyhow::Result<PathBuf> {
anyhow::ensure!(valid_slug(repo), "not an owner/name repo slug: {repo}");
Ok(home::state_dir()?
.join("cluster")
.join("projects")
.join(repo))
}
pub(crate) async fn refresh(source: &dyn Contents, dir: &Path, repo: &str) -> anyhow::Result<bool> {
let file = dir.join(CONFIG_FILE);
let etag_file = dir.join(ETAG_FILE);
let etag = if fs::try_exists(&file).await.unwrap_or(false) {
fs::read_to_string(&etag_file)
.await
.ok()
.map(|e| e.trim().to_string())
.filter(|e| !e.is_empty())
} else {
None
};
let (content, etag) = match source.orch_yml(repo, etag.as_deref()).await? {
FileFetch::NotModified => return Ok(false),
FileFetch::Found { content, etag } => {
if let Err(e) = serde_norway::from_str::<serde_norway::Value>(&content) {
tracing::warn!(repo, err = %e, "the default branch has an invalid .orch.yml, keeping the last good one");
return Ok(false);
}
(content, etag)
}
FileFetch::Missing => ("{}\n".to_string(), None),
};
fs::create_dir_all(dir)
.await
.with_context(|| format!("creating {}", dir.display()))?;
fs::write(&file, &content)
.await
.with_context(|| format!("writing {}", file.display()))?;
match etag {
Some(etag) => fs::write(&etag_file, etag).await?,
None => {
let _ = fs::remove_file(&etag_file).await;
}
}
tracing::info!(repo, "read .orch.yml from the default branch");
config::reloaded(&file);
Ok(true)
}
pub(crate) async fn refresh_all(source: &dyn Contents, projects: &[(String, PathBuf)]) {
for (repo, dir) in projects {
if let Err(e) = refresh(source, dir, repo).await {
tracing::warn!(repo = %repo, err = %e, "cannot read .orch.yml from the default branch");
}
}
}
#[cfg(test)]
#[path = "cluster_projects_tests.rs"]
mod tests;