use super::shell_quote;
use crate::routines::model::Repository;
pub(crate) fn repo_dir_name(url: &str) -> String {
let trimmed = url.trim_end_matches('/');
let last = trimmed.rsplit(['/', ':']).next().unwrap_or(trimmed);
let stem = last.strip_suffix(".git").unwrap_or(last);
let sanitized: String = stem
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_') {
ch
} else {
'_'
}
})
.collect();
if sanitized.is_empty() {
"repo".to_string()
} else {
sanitized
}
}
pub(crate) fn clone_repository_stmts(repositories: &[Repository]) -> Vec<String> {
repositories
.iter()
.map(|repo| {
let url = shell_quote(&repo.repository);
let cache = shell_quote(&crate::paths::repo_cache_dir(&repo.repository).to_string_lossy());
let dir_name = repo_dir_name(&repo.repository);
let branch_arg = match &repo.branch {
Some(branch) => format!(" -b {}", shell_quote(branch)),
None => String::new(),
};
let branch_desc = match &repo.branch {
Some(branch) => format!(" (branch {branch})"),
None => String::new(),
};
format!(
r#"mkdir -p {cache_parent} && {{ if [ -d {cache} ]; then git -C {cache} fetch --prune --quiet origin; else git clone --mirror --quiet {url} {cache}; fi; }} || {{ echo "moadim: failed to sync cached repository {url}; aborting launch" | tee -a "$WB/agent.log" >&2; exit 1; }}; git clone --local --quiet{branch_arg} {cache} "$WB/{dir_name}" || {{ echo "moadim: failed to materialize repository {url}{branch_desc}; aborting launch" | tee -a "$WB/agent.log" >&2; exit 1; }}"#,
cache_parent =
shell_quote(&crate::paths::config_dir().join("cache").to_string_lossy()),
)
})
.collect()
}