//! Which hub and repository a command talks to, and with which token. //! //! Inside an Oxygen checkout, `oh` uses the checkout's remote (`origin`, or //! the only one, or `--remote NAME`): its URL names the hub and the //! repository, and its token and CA are the ones `oxy` pushes with. //! Elsewhere, `--repo OWNER/NAME` with the hub from `--hub`, `OH_HUB` or //! the one `oh auth login` saved. use anyhow::{anyhow, bail, Context, Result}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; /// `~/.config/oh/config.toml`: tokens and CAs by hub, and the default hub. #[derive(Debug, Default, Serialize, Deserialize)] pub struct Config { #[serde(default)] pub default_hub: Option, #[serde(default)] pub hosts: BTreeMap, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct Host { pub token: String, #[serde(default)] pub ca: Option, } pub fn config_path() -> Result { if let Some(p) = std::env::var_os("OH_CONFIG") { return Ok(PathBuf::from(p)); } let base = match std::env::var_os("XDG_CONFIG_HOME") { Some(d) => PathBuf::from(d), None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".config"), }; Ok(base.join("oh").join("config.toml")) } impl Config { pub fn load() -> Result { let p = config_path()?; match std::fs::read_to_string(&p) { Ok(t) => toml::from_str(&t).with_context(|| format!("parse {}", p.display())), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()), Err(e) => Err(e).with_context(|| format!("read {}", p.display())), } } /// Written owner-only: it holds tokens. pub fn save(&self) -> Result<()> { use std::io::Write; use std::os::unix::fs::OpenOptionsExt; let p = config_path()?; std::fs::create_dir_all(p.parent().unwrap())?; let tmp = p.with_extension("toml.tmp"); let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?; f.write_all(toml::to_string_pretty(self)?.as_bytes())?; f.sync_all()?; std::fs::rename(&tmp, &p)?; Ok(()) } } /// A hub, and a repository on it when the command needs one. #[derive(Clone, Debug)] pub struct Target { /// `https://host:port`, no trailing slash. pub hub: String, pub token: Option, pub ca: Option, pub owner: String, pub name: String, } impl Target { pub fn repo(&self) -> Result<(&str, &str)> { if self.owner.is_empty() { bail!("no repository: run inside an Oxygen checkout, or give --repo OWNER/NAME"); } Ok((&self.owner, &self.name)) } /// `/repos/{owner}/{name}`. pub fn repo_path(&self) -> Result { let (o, n) = self.repo()?; Ok(format!("/repos/{o}/{n}")) } } /// Split `https://host:port/owner/name` into the hub and the repository. pub fn split_url(url: &str) -> Result<(String, String, String)> { let (scheme, rest) = url.split_once("://").ok_or_else(|| anyhow!("{url} is not a hub URL"))?; let mut parts = rest.trim_end_matches('/').splitn(2, '/'); let host = parts.next().unwrap_or(""); let path = parts.next().unwrap_or(""); let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); match segs.as_slice() { [o, n] => Ok((format!("{scheme}://{host}"), o.to_string(), n.trim_end_matches(".oxy").to_string())), _ => bail!("{url} does not name a repository as https://hub/OWNER/NAME"), } } pub struct Choice<'a> { pub repo: Option<&'a str>, pub hub: Option<&'a str>, pub remote: Option<&'a str>, } /// Resolve what to talk to from the flags, the checkout at `dir`, the /// environment and the saved configuration. pub fn resolve(choice: &Choice, dir: &Path, cfg: &Config) -> Result { let env_token = std::env::var("OH_TOKEN").ok().or_else(|| std::env::var("OXY_TOKEN").ok()).filter(|t| !t.is_empty()); let env_ca = std::env::var_os("OXY_CA").map(PathBuf::from); let saved = |hub: &str| cfg.hosts.get(hub).cloned(); if let Some(r) = choice.repo { let (owner, name) = r.split_once('/').ok_or_else(|| anyhow!("--repo takes OWNER/NAME"))?; let hub = choice .hub .map(String::from) .or_else(|| std::env::var("OH_HUB").ok()) .or_else(|| cfg.default_hub.clone()) .ok_or_else(|| anyhow!("which hub? give --hub URL, set OH_HUB, or run `oh auth login`"))?; let hub = hub.trim_end_matches('/').to_string(); let host = saved(&hub).unwrap_or_default(); return Ok(Target { token: env_token.or(Some(host.token).filter(|t| !t.is_empty())), ca: env_ca.or(host.ca), hub, owner: owner.into(), name: name.into(), }); } // The checkout's remote. if let Ok(repo) = oxy_core::repo::Repo::open(dir) { let remotes = &repo.config.remotes; let name = match choice.remote { Some(n) => n.to_string(), None if remotes.contains_key("origin") => "origin".into(), None if remotes.len() == 1 => remotes.keys().next().unwrap().clone(), None if remotes.is_empty() => bail!("this checkout has no remote; give --repo OWNER/NAME"), None => bail!( "this checkout has several remotes ({}); choose one with --remote", remotes.keys().cloned().collect::>().join(", ") ), }; let url = remotes.get(&name).ok_or_else(|| anyhow!("no remote named {name}"))?; let (hub, owner, repo_name) = split_url(url)?; let host = saved(&hub).unwrap_or_default(); let token = env_token.or_else(|| repo.config.remote_tokens.get(&name).cloned()).or(Some(host.token).filter(|t| !t.is_empty())); let ca = env_ca.or_else(|| repo.config.remote_cas.get(&name).map(PathBuf::from)).or(host.ca); return Ok(Target { hub, token, ca, owner, name: repo_name }); } // No repository: commands that need only a hub. let hub = choice .hub .map(String::from) .or_else(|| std::env::var("OH_HUB").ok()) .or_else(|| cfg.default_hub.clone()) .ok_or_else(|| anyhow!("not in an Oxygen checkout: give --repo OWNER/NAME and --hub URL, or run `oh auth login`"))?; let hub = hub.trim_end_matches('/').to_string(); let host = saved(&hub).unwrap_or_default(); Ok(Target { token: env_token.or(Some(host.token).filter(|t| !t.is_empty())), ca: env_ca.or(host.ca), hub, owner: String::new(), name: String::new(), }) } #[cfg(test)] mod tests { use super::*; #[test] fn remote_urls_name_the_hub_and_the_repository() { assert_eq!( split_url("https://earth.example:7343/andy/oxygen").unwrap(), ("https://earth.example:7343".into(), "andy".into(), "oxygen".into()) ); assert_eq!(split_url("http://127.0.0.1:9/a/b/").unwrap().2, "b"); assert!(split_url("https://hub/only-owner").is_err()); assert!(split_url("not a url").is_err()); } }