use std::collections::BTreeMap;
use crate::config::{Host, builtin_forges};
use crate::error::{Error, Result};
use crate::source::{Protocol, is_local_path};
use super::config_edit::BindRefinement;
use super::{config_edit, load_config, read_config_text, render, target_config_file};
pub(super) struct AddRequest<'a> {
pub(super) url: &'a str,
pub(super) targets: &'a [String],
pub(super) name: Option<String>,
pub(super) branch: Option<String>,
pub(super) tag: Option<String>,
pub(super) root: Option<String>,
pub(super) include: Vec<String>,
pub(super) exclude: Vec<String>,
pub(super) local: bool,
pub(super) symlink: bool,
pub(super) assume_yes: bool,
pub(super) refinement: &'a BindRefinement,
}
pub(super) fn run_add(request: AddRequest<'_>) -> Result<()> {
if request.refinement.r#as.is_some() && request.targets.len() != 1 {
return Err(Error::Config(
"`--as` sets a single binding identity and needs exactly one `--to` target".to_owned(),
));
}
if !request.refinement.is_bare() && !request.refinement.history && request.targets.is_empty() {
return Err(Error::Config(
"refinement flags (`--as`/`--take`) need at least one `--to` target".to_owned(),
));
}
if request.refinement.history && (request.local || request.symlink) {
return Err(Error::Config(
"`--local`/`--symlink` overlays do not support `--history`".to_owned(),
));
}
if (request.local || request.symlink)
&& (!request.targets.is_empty() || !request.refinement.is_bare())
{
return Err(Error::Config(
"`--local`/`--symlink` overlays do not support `--to`/refinement flags".to_owned(),
));
}
if !request.targets.is_empty() {
let AddRequest {
url,
targets,
name,
branch,
tag,
root,
include,
exclude,
local,
symlink,
assume_yes,
refinement,
} = request;
return run_add_to_targets(
url,
targets,
name,
branch,
tag.as_deref(),
root.as_deref(),
include,
exclude,
local,
symlink,
assume_yes,
refinement,
);
}
if request.local || request.symlink {
let AddRequest {
url,
name,
branch,
tag,
root,
include,
exclude,
symlink,
..
} = request;
return add_local(
url,
name,
LocalSourceSpec {
branch: branch.as_deref(),
tag: tag.as_deref(),
root: root.as_deref(),
include,
exclude,
},
symlink,
);
}
run_unbound_add(request)
}
fn run_unbound_add(request: AddRequest<'_>) -> Result<()> {
let AddRequest {
url,
name,
branch,
tag,
root,
include,
exclude,
refinement,
..
} = request;
let mut parsed = resolve_add_source(url)?;
parsed.include = include;
parsed.exclude = exclude;
let name = name.unwrap_or_else(|| parsed.name.clone());
let branch = branch.or_else(|| parsed.branch.clone());
let root = root.or_else(|| parsed.root.clone());
let doc_text =
std::fs::read_to_string("phora.toml").unwrap_or_else(|_| "version = 1\n".to_owned());
let auto_target = super::effective_auto_target();
if refinement.history && !auto_target {
return Err(Error::Config(
"`--history` needs at least one `--to` target".to_owned(),
));
}
let mut updated = if auto_target {
add_to_default_target(
&doc_text,
&name,
&parsed,
branch.as_deref(),
tag.as_deref(),
root.as_deref(),
)?
} else {
config_edit::upsert_source(
&doc_text,
&name,
&parsed,
branch.as_deref(),
tag.as_deref(),
root.as_deref(),
)?
};
if refinement.history {
updated =
config_edit::bind(&updated, "default", std::slice::from_ref(&name), refinement)?.text;
}
super::bind::guard_no_dangling_references(&updated, false)?;
std::fs::write("phora.toml", &updated)?;
let refspec = tag
.or(branch)
.map_or_else(String::new, |r| format!(" ({r})"));
let description = format!("{}{refspec}", describe_source(&parsed));
if auto_target {
render::print_added_to_default(&name, &description);
} else {
render::print_added_declared(&name, &description);
}
if parsed.path.is_none() {
print_add_contribution(&name);
}
Ok(())
}
fn print_add_contribution(name: &str) {
use crate::source::SourceError;
let Some((backend, source_name, remote, refspec)) = add_contribution_target(name) else {
return;
};
match backend.fetch_root_manifest(&source_name, &remote, &refspec) {
Ok(bytes) => print_contribution_from_bytes(name, &bytes),
Err(SourceError::FileAbsent { .. }) => {}
Err(e) => eprintln!("note: could not inspect {name}'s phora.toml: {e}"),
}
}
fn add_contribution_target(
name: &str,
) -> Option<(
crate::source::GitBackend,
crate::source::SourceName,
String,
crate::config::Refspec,
)> {
use crate::source::{GitBackend, Protocol as SourceProtocol};
let config = load_config().ok()?;
let sources = config.parsed_sources().ok()?;
let source = sources.get(name)?;
if source.mode() != crate::config::SourceMode::Git {
return None;
}
let protocol = source
.protocol()
.or(config.protocol)
.unwrap_or(SourceProtocol::Https);
let remote = source.resolved_remote(&config.hosts, protocol).ok()?;
let cwd = std::env::current_dir().ok()?;
let git_dir = crate::paths::cache_root_for(config.paths.cache.as_deref(), &cwd)
.map(|c| c.join("git"))
.ok()?;
let backend = GitBackend::new(git_dir);
let source_name = crate::source::SourceName::trusted(name.to_owned());
Some((backend, source_name, remote, source.refspec()))
}
fn print_contribution_from_bytes(name: &str, bytes: &[u8]) {
use crate::config::transitive::TransitiveManifest;
let text = match std::str::from_utf8(bytes) {
Ok(text) => text,
Err(e) => {
eprintln!("note: could not inspect {name}'s phora.toml: {e}");
return;
}
};
match TransitiveManifest::parse(text) {
Ok(manifest) => print!("{}", render::render_add_contribution(name, &manifest)),
Err(e) => eprintln!("note: could not inspect {name}'s phora.toml: {e}"),
}
}
fn resolve_add_source(url: &str) -> Result<AddTarget> {
if is_local_path(url) {
return local_path_source(url);
}
let hosts = load_config().map(|c| c.hosts).unwrap_or_default();
parse_add_url(url, &hosts)
}
fn local_path_source(url: &str) -> Result<AddTarget> {
let canonical = std::fs::canonicalize(url)
.map_err(|e| Error::Config(format!("local path source `{url}` does not exist: {e}")))?;
let path = canonical.to_string_lossy().into_owned();
let name = canonical.file_name().map_or_else(
|| path.clone(),
|segment| segment.to_string_lossy().into_owned(),
);
Ok(AddTarget {
name,
git: None,
host: None,
repo: None,
path: Some(path),
protocol: None,
branch: None,
root: None,
include: Vec::new(),
exclude: Vec::new(),
})
}
fn resolve_local_source(url: &str, name: Option<String>) -> Result<(String, AddTarget)> {
let canonical = std::fs::canonicalize(url).map_err(|e| {
Error::Config(format!(
"`--local`/`--symlink` require an existing local checkout, but `{url}` is not one: {e}"
))
})?;
if !canonical.is_dir() {
return Err(Error::Config(format!(
"`--local`/`--symlink` require a directory, but `{url}` is not one"
)));
}
let path = canonical.to_string_lossy().into_owned();
let name = name.unwrap_or_else(|| {
canonical
.file_name()
.map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned())
});
let target = AddTarget {
name: name.clone(),
git: None,
host: None,
repo: None,
path: Some(path),
protocol: None,
branch: None,
root: None,
include: Vec::new(),
exclude: Vec::new(),
};
Ok((name, target))
}
fn inject_deploy_link(text: &str, name: &str) -> Result<String> {
let mut doc = text
.parse::<toml_edit::DocumentMut>()
.map_err(|e| Error::Config(format!("parse phora.local.toml: {e}")))?;
doc["sources"][name]["deploy"] = toml_edit::value("link");
Ok(doc.to_string())
}
struct LocalSourceSpec<'a> {
branch: Option<&'a str>,
tag: Option<&'a str>,
root: Option<&'a str>,
include: Vec<String>,
exclude: Vec<String>,
}
fn add_local(
url: &str,
name: Option<String>,
spec: LocalSourceSpec<'_>,
symlink: bool,
) -> Result<()> {
let (name, mut target) = resolve_local_source(url, name)?;
target.include = spec.include;
target.exclude = spec.exclude;
let path = target.path.clone().unwrap_or_default();
let doc_text =
std::fs::read_to_string("phora.local.toml").unwrap_or_else(|_| "version = 1\n".to_owned());
let mut updated =
config_edit::upsert_source(&doc_text, &name, &target, spec.branch, spec.tag, spec.root)?;
if symlink {
updated = inject_deploy_link(&updated, &name)?;
}
super::bind::guard_no_dangling_references(&updated, true)?;
std::fs::write("phora.local.toml", &updated)?;
println!("Added local source '{name}': {path}");
Ok(())
}
#[allow(
clippy::too_many_arguments,
reason = "mirrors the `phora add` argument surface for the bind-on-add sugar"
)]
fn run_add_to_targets(
url: &str,
targets: &[String],
name: Option<String>,
branch: Option<String>,
tag: Option<&str>,
root: Option<&str>,
include: Vec<String>,
exclude: Vec<String>,
local: bool,
symlink: bool,
assume_yes: bool,
refinement: &BindRefinement,
) -> Result<()> {
let overlay = local || symlink;
let (name, mut source, branch) = if overlay {
let (name, source) = resolve_local_source(url, name)?;
(name, source, branch)
} else {
let parsed = resolve_add_source(url)?;
let name = name.unwrap_or_else(|| parsed.name.clone());
let branch = branch.or_else(|| parsed.branch.clone());
(name, parsed, branch)
};
source.include = include;
source.exclude = exclude;
let file = target_config_file(overlay);
let text = read_config_text(file)?;
let source_root = root.map(ToOwned::to_owned).or_else(|| source.root.clone());
let mut updated = add_with_binds(
&text,
&name,
&source,
branch.as_deref(),
tag,
source_root.as_deref(),
targets,
refinement,
&super::TtyMissingTarget { assume_yes },
)?;
if symlink {
updated = inject_deploy_link(&updated, &name)?;
}
super::bind::guard_no_dangling_references(&updated, overlay)?;
std::fs::write(file, &updated)?;
render::print_added_and_bound(&name, &describe_source(&source), targets);
Ok(())
}
#[cfg(test)]
pub(super) fn insert_source_with_ref(
doc_text: &str,
name: &str,
source: &AddTarget,
branch: Option<&str>,
tag: Option<&str>,
root: Option<&str>,
) -> Result<String> {
config_edit::upsert_source(doc_text, name, source, branch, tag, root)
}
fn describe_source(source: &AddTarget) -> String {
match (&source.git, &source.host, &source.repo, &source.path) {
(Some(git), ..) => git.clone(),
(None, Some(host), Some(repo), _) => format!("{host}:{repo}"),
(None, None, None, Some(path)) => path.clone(),
_ => source.name.clone(),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddTarget {
pub name: String,
pub git: Option<String>,
pub host: Option<String>,
pub repo: Option<String>,
pub path: Option<String>,
pub protocol: Option<Protocol>,
pub branch: Option<String>,
pub root: Option<String>,
pub include: Vec<String>,
pub exclude: Vec<String>,
}
pub fn parse_add_url(input: &str, hosts: &BTreeMap<String, Host>) -> Result<AddTarget> {
if is_scp_ssh(input) {
return Ok(parse_scp_ssh(input));
}
if let Some((scheme, rest)) = split_scheme(input) {
return parse_full_url(input, scheme, rest);
}
if let Some((host, path)) = input.split_once(':') {
return parse_colon_alias(input, host, path);
}
parse_shorthand(input, &domain_to_name(hosts))
}
fn parse_colon_alias(input: &str, host: &str, path: &str) -> Result<AddTarget> {
if host.is_empty() {
return Err(Error::Config(format!("empty host in `{input}`")));
}
let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
let [owner, repo, root_segments @ ..] = segments.as_slice() else {
return Err(Error::Config(format!(
"expected <host>:<owner>/<repo> in `{input}`"
)));
};
Ok(symbolic_source(
host.to_owned(),
&format!("{owner}/{repo}"),
join_root(root_segments),
))
}
fn domain_to_name(hosts: &BTreeMap<String, Host>) -> BTreeMap<String, String> {
let builtins = builtin_forges();
builtins
.iter()
.chain(hosts)
.filter_map(|(name, host)| {
let url = host.remote.as_ref()?.https_template()?;
Some((template_domain(url)?.to_owned(), name.clone()))
})
.collect()
}
fn symbolic_source(host: String, repo: &str, root: Option<String>) -> AddTarget {
AddTarget {
name: repo_name(repo),
git: None,
host: Some(host),
repo: Some(repo.to_owned()),
path: None,
protocol: None,
branch: None,
root,
include: Vec::new(),
exclude: Vec::new(),
}
}
fn template_domain(url: &str) -> Option<&str> {
let after_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
let after_user = after_scheme
.split_once('@')
.map_or(after_scheme, |(_, rest)| rest);
let end = after_user.find(['/', ':']).unwrap_or(after_user.len());
let domain = &after_user[..end];
(!domain.is_empty()).then_some(domain)
}
fn is_scp_ssh(input: &str) -> bool {
if input.contains("://") {
return false;
}
match (input.find('@'), input.find(':')) {
(Some(at), Some(colon)) => at < colon,
_ => false,
}
}
fn parse_scp_ssh(input: &str) -> AddTarget {
literal_source(repo_name(input), input.to_owned(), None, None)
}
fn literal_source(
name: String,
git: String,
branch: Option<String>,
root: Option<String>,
) -> AddTarget {
AddTarget {
name,
git: Some(git),
host: None,
repo: None,
path: None,
protocol: None,
branch,
root,
include: Vec::new(),
exclude: Vec::new(),
}
}
fn split_scheme(input: &str) -> Option<(&str, &str)> {
let (scheme, rest) = input.split_once("://")?;
matches!(scheme, "https" | "http" | "ssh").then_some((scheme, rest))
}
fn parse_full_url(input: &str, scheme: &str, rest: &str) -> Result<AddTarget> {
let (host, path) = rest
.split_once('/')
.ok_or_else(|| Error::Config(format!("cannot parse owner/repo from `{input}`")))?;
let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
let [owner, repo, tail @ ..] = segments.as_slice() else {
return Err(Error::Config(format!(
"expected <owner>/<repo> in `{input}`"
)));
};
if let ["tree", git_ref, root_segments @ ..] = tail {
return Ok(literal_source(
strip_git(repo).to_owned(),
with_git_suffix(&format!("{scheme}://{host}/{owner}/{repo}")),
Some((*git_ref).to_owned()),
join_root(root_segments),
));
}
let remote = format!("{scheme}://{host}/{}", segments.join("/"));
Ok(literal_source(
repo_name(&remote),
with_git_suffix(&remote),
None,
None,
))
}
fn parse_shorthand(input: &str, domains: &BTreeMap<String, String>) -> Result<AddTarget> {
let segments: Vec<&str> = input.split('/').filter(|s| !s.is_empty()).collect();
let first = segments
.first()
.ok_or_else(|| Error::Config(format!("empty add target `{input}`")))?;
if let Some(name) = domains.get(*first) {
let [_, owner, repo, root_segments @ ..] = segments.as_slice() else {
return Err(Error::Config(format!(
"expected <host>/<owner>/<repo> in `{input}`"
)));
};
return Ok(symbolic_source(
name.clone(),
&format!("{owner}/{repo}"),
join_root(root_segments),
));
}
let [owner, repo, root_segments @ ..] = segments.as_slice() else {
return Err(Error::Config(format!(
"expected <owner>/<repo> shorthand in `{input}`"
)));
};
Ok(symbolic_source(
"github".to_owned(),
&format!("{owner}/{repo}"),
join_root(root_segments),
))
}
fn join_root(segments: &[&str]) -> Option<String> {
(!segments.is_empty()).then(|| segments.join("/"))
}
fn repo_name(input: &str) -> String {
let last = input.rsplit('/').next().unwrap_or(input);
strip_git(last).to_owned()
}
fn strip_git(segment: &str) -> &str {
segment.strip_suffix(".git").unwrap_or(segment)
}
#[expect(
clippy::case_sensitive_file_extension_comparisons,
reason = "git remote URLs are case-sensitive strings, not filesystem paths"
)]
fn with_git_suffix(url: &str) -> String {
if url.ends_with(".git") {
url.to_owned()
} else {
format!("{url}.git")
}
}
pub fn insert_source(
doc_text: &str,
name: &str,
source: &AddTarget,
root: Option<&str>,
) -> Result<String> {
config_edit::upsert_source(doc_text, name, source, source.branch.as_deref(), None, root)
}
pub(super) enum MissingTarget {
Create,
Reject,
}
pub(super) trait MissingTargetDecider {
fn decide(&self, name: &str, path: &str) -> MissingTarget;
}
pub(super) fn missing_target_decision(
path_exists: bool,
assume_yes: bool,
interactive: bool,
confirm: impl FnOnce() -> bool,
) -> MissingTarget {
if path_exists || assume_yes {
return MissingTarget::Create;
}
if !interactive {
return MissingTarget::Reject;
}
if confirm() {
MissingTarget::Create
} else {
MissingTarget::Reject
}
}
pub(super) fn add_to_default_target(
text: &str,
name: &str,
source: &AddTarget,
branch: Option<&str>,
tag: Option<&str>,
root: Option<&str>,
) -> Result<String> {
let mut current = config_edit::upsert_source(text, name, source, branch, tag, root)?;
if !target_exists(¤t, "default")? {
current = config_edit::upsert_target(¤t, "default", ".", Some("flat"))?;
}
Ok(config_edit::bind(
¤t,
"default",
&[name.to_owned()],
&BindRefinement::default(),
)?
.text)
}
#[allow(
clippy::too_many_arguments,
reason = "single-string desugar carries the source shape plus refspec and bind targets"
)]
pub(super) fn add_with_binds(
text: &str,
name: &str,
source: &AddTarget,
branch: Option<&str>,
tag: Option<&str>,
root: Option<&str>,
targets: &[String],
refinement: &BindRefinement,
decider: &dyn MissingTargetDecider,
) -> Result<String> {
let mut current = config_edit::upsert_source(text, name, source, branch, tag, root)?;
let bind_names = [name.to_owned()];
for target in targets {
if !target_exists(¤t, target)? {
let path = format!("./{target}");
match decider.decide(target, &path) {
MissingTarget::Create => {
current = config_edit::upsert_target(¤t, target, &path, Some("flat"))?;
}
MissingTarget::Reject => {
return Err(Error::Config(super::bind::missing_target_message(
target, false,
)));
}
}
}
current = config_edit::bind(¤t, target, &bind_names, refinement)?.text;
}
Ok(current)
}
fn target_exists(text: &str, target: &str) -> Result<bool> {
let doc = text
.parse::<toml_edit::DocumentMut>()
.map_err(|e| Error::Config(format!("parse toml: {e}")))?;
Ok(doc
.get("targets")
.and_then(toml_edit::Item::as_table_like)
.is_some_and(|targets| targets.contains_key(target)))
}