| 5c6e92fd Andy McCall ↶ |
1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
use anyhow::{anyhow, bail, Context, Result}; |
| 10 |
use serde::{Deserialize, Serialize}; |
| 11 |
use std::collections::BTreeMap; |
| 12 |
use std::path::{Path, PathBuf}; |
| 13 |
|
| 14 |
|
| 15 |
#[derive(Debug, Default, Serialize, Deserialize)] |
| 16 |
pub struct Config { |
| 17 |
#[serde(default)] |
| 18 |
pub default_hub: Option<String>, |
| 19 |
#[serde(default)] |
| 20 |
pub hosts: BTreeMap<String, Host>, |
| 21 |
} |
| 22 |
|
| 23 |
#[derive(Clone, Debug, Default, Serialize, Deserialize)] |
| 24 |
pub struct Host { |
| 25 |
pub token: String, |
| 26 |
#[serde(default)] |
| 27 |
pub ca: Option<PathBuf>, |
| 28 |
} |
| 29 |
|
| 30 |
pub fn config_path() -> Result<PathBuf> { |
| 31 |
if let Some(p) = std::env::var_os("OH_CONFIG") { |
| 32 |
return Ok(PathBuf::from(p)); |
| 33 |
} |
| 34 |
let base = match std::env::var_os("XDG_CONFIG_HOME") { |
| 35 |
Some(d) => PathBuf::from(d), |
| bd630386 Andy McCall ↶ |
36 |
|
| 37 |
#[cfg(windows)] |
| 38 |
None => PathBuf::from(std::env::var_os("APPDATA").or_else(|| std::env::var_os("USERPROFILE")).context("APPDATA is not set")?), |
| 39 |
#[cfg(not(windows))] |
| 5c6e92fd Andy McCall ↶ |
40 |
None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".config"), |
| 41 |
}; |
| 42 |
Ok(base.join("oh").join("config.toml")) |
| 43 |
} |
| 44 |
|
| 45 |
impl Config { |
| 46 |
pub fn load() -> Result<Config> { |
| 47 |
let p = config_path()?; |
| 48 |
match std::fs::read_to_string(&p) { |
| 49 |
Ok(t) => toml::from_str(&t).with_context(|| format!("parse {}", p.display())), |
| 50 |
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()), |
| 51 |
Err(e) => Err(e).with_context(|| format!("read {}", p.display())), |
| 52 |
} |
| 53 |
} |
| 54 |
|
| bd630386 Andy McCall ↶ |
55 |
|
| 56 |
|
| 5c6e92fd Andy McCall ↶ |
57 |
pub fn save(&self) -> Result<()> { |
| 58 |
use std::io::Write; |
| 59 |
let p = config_path()?; |
| 60 |
std::fs::create_dir_all(p.parent().unwrap())?; |
| 61 |
let tmp = p.with_extension("toml.tmp"); |
| bd630386 Andy McCall ↶ |
62 |
let mut options = std::fs::OpenOptions::new(); |
| 63 |
options.write(true).create(true).truncate(true); |
| 64 |
#[cfg(unix)] |
| 65 |
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); |
| 66 |
let mut f = options.open(&tmp)?; |
| 5c6e92fd Andy McCall ↶ |
67 |
f.write_all(toml::to_string_pretty(self)?.as_bytes())?; |
| 68 |
f.sync_all()?; |
| 69 |
std::fs::rename(&tmp, &p)?; |
| 70 |
Ok(()) |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
#[derive(Clone, Debug)] |
| 76 |
pub struct Target { |
| 77 |
|
| 78 |
pub hub: String, |
| 79 |
pub token: Option<String>, |
| 80 |
pub ca: Option<PathBuf>, |
| 81 |
pub owner: String, |
| 82 |
pub name: String, |
| 83 |
} |
| 84 |
|
| 85 |
impl Target { |
| 86 |
pub fn repo(&self) -> Result<(&str, &str)> { |
| 87 |
if self.owner.is_empty() { |
| 88 |
bail!("no repository: run inside an Oxygen checkout, or give --repo OWNER/NAME"); |
| 89 |
} |
| 90 |
Ok((&self.owner, &self.name)) |
| 91 |
} |
| 92 |
|
| 93 |
|
| 94 |
pub fn repo_path(&self) -> Result<String> { |
| 95 |
let (o, n) = self.repo()?; |
| 96 |
Ok(format!("/repos/{o}/{n}")) |
| 97 |
} |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
pub fn split_url(url: &str) -> Result<(String, String, String)> { |
| 102 |
let (scheme, rest) = url.split_once("://").ok_or_else(|| anyhow!("{url} is not a hub URL"))?; |
| 103 |
let mut parts = rest.trim_end_matches('/').splitn(2, '/'); |
| 104 |
let host = parts.next().unwrap_or(""); |
| 105 |
let path = parts.next().unwrap_or(""); |
| 106 |
let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); |
| 107 |
match segs.as_slice() { |
| 108 |
[o, n] => Ok((format!("{scheme}://{host}"), o.to_string(), n.trim_end_matches(".oxy").to_string())), |
| 109 |
_ => bail!("{url} does not name a repository as https://hub/OWNER/NAME"), |
| 110 |
} |
| 111 |
} |
| 112 |
|
| cefb0ea2 Andy McCall ↶ |
113 |
|
| 114 |
|
| 115 |
fn checkout_credentials(dir: &Path, hub: &str) -> (Option<String>, Option<PathBuf>) { |
| 116 |
let (mut token, mut ca) = (None, None); |
| 117 |
let mut at = Some(dir.to_path_buf()); |
| 118 |
while let Some(d) = at { |
| 119 |
let Ok(repo) = oxy_core::repo::Repo::open(&d) else { break }; |
| 120 |
for (name, url) in &repo.config.remotes { |
| 121 |
if split_url(url).is_ok_and(|(h, _, _)| h.eq_ignore_ascii_case(hub)) { |
| 122 |
token = token.or_else(|| repo.config.remote_tokens.get(name).cloned()); |
| 123 |
ca = ca.or_else(|| repo.config.remote_cas.get(name).map(PathBuf::from)); |
| 124 |
} |
| 125 |
} |
| 126 |
if token.is_some() && ca.is_some() { |
| 127 |
break; |
| 128 |
} |
| 129 |
at = repo.root().parent().map(Path::to_path_buf); |
| 130 |
} |
| 131 |
(token, ca) |
| 132 |
} |
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
fn checkout_hub(dir: &Path, remote: Option<&str>) -> Option<String> { |
| 137 |
let repo = oxy_core::repo::Repo::open(dir).ok()?; |
| 138 |
let remotes = &repo.config.remotes; |
| 139 |
let url = match remote { |
| 140 |
Some(n) => remotes.get(n)?, |
| 141 |
None => remotes.get("origin").or_else(|| (remotes.len() == 1).then(|| remotes.values().next()).flatten())?, |
| 142 |
}; |
| 143 |
split_url(url).ok().map(|(hub, _, _)| hub) |
| 144 |
} |
| 145 |
|
| 5c6e92fd Andy McCall ↶ |
146 |
pub struct Choice<'a> { |
| 147 |
pub repo: Option<&'a str>, |
| 148 |
pub hub: Option<&'a str>, |
| 149 |
pub remote: Option<&'a str>, |
| 150 |
} |
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
pub fn resolve(choice: &Choice, dir: &Path, cfg: &Config) -> Result<Target> { |
| 155 |
let env_token = std::env::var("OH_TOKEN").ok().or_else(|| std::env::var("OXY_TOKEN").ok()).filter(|t| !t.is_empty()); |
| 156 |
let env_ca = std::env::var_os("OXY_CA").map(PathBuf::from); |
| 157 |
let saved = |hub: &str| cfg.hosts.get(hub).cloned(); |
| 158 |
if let Some(r) = choice.repo { |
| 159 |
let (owner, name) = r.split_once('/').ok_or_else(|| anyhow!("--repo takes OWNER/NAME"))?; |
| cefb0ea2 Andy McCall ↶ |
160 |
|
| 161 |
|
| 5c6e92fd Andy McCall ↶ |
162 |
let hub = choice |
| 163 |
.hub |
| 164 |
.map(String::from) |
| 165 |
.or_else(|| std::env::var("OH_HUB").ok()) |
| cefb0ea2 Andy McCall ↶ |
166 |
.or_else(|| checkout_hub(dir, choice.remote)) |
| 5c6e92fd Andy McCall ↶ |
167 |
.or_else(|| cfg.default_hub.clone()) |
| 168 |
.ok_or_else(|| anyhow!("which hub? give --hub URL, set OH_HUB, or run `oh auth login`"))?; |
| 169 |
let hub = hub.trim_end_matches('/').to_string(); |
| 170 |
let host = saved(&hub).unwrap_or_default(); |
| cefb0ea2 Andy McCall ↶ |
171 |
let (co_token, co_ca) = checkout_credentials(dir, &hub); |
| 5c6e92fd Andy McCall ↶ |
172 |
return Ok(Target { |
| cefb0ea2 Andy McCall ↶ |
173 |
token: env_token.or(co_token).or(Some(host.token).filter(|t| !t.is_empty())), |
| 174 |
ca: env_ca.or(co_ca).or(host.ca), |
| 5c6e92fd Andy McCall ↶ |
175 |
hub, |
| 176 |
owner: owner.into(), |
| 177 |
name: name.into(), |
| 178 |
}); |
| 179 |
} |
| 180 |
|
| 181 |
if let Ok(repo) = oxy_core::repo::Repo::open(dir) { |
| 182 |
let remotes = &repo.config.remotes; |
| 183 |
let name = match choice.remote { |
| 184 |
Some(n) => n.to_string(), |
| 185 |
None if remotes.contains_key("origin") => "origin".into(), |
| 186 |
None if remotes.len() == 1 => remotes.keys().next().unwrap().clone(), |
| 187 |
None if remotes.is_empty() => bail!("this checkout has no remote; give --repo OWNER/NAME"), |
| 188 |
None => bail!( |
| 189 |
"this checkout has several remotes ({}); choose one with --remote", |
| 190 |
remotes.keys().cloned().collect::<Vec<_>>().join(", ") |
| 191 |
), |
| 192 |
}; |
| 193 |
let url = remotes.get(&name).ok_or_else(|| anyhow!("no remote named {name}"))?; |
| 194 |
let (hub, owner, repo_name) = split_url(url)?; |
| 195 |
let host = saved(&hub).unwrap_or_default(); |
| cefb0ea2 Andy McCall ↶ |
196 |
|
| 197 |
|
| 198 |
let (up_token, up_ca) = repo.root().parent().map(|p| checkout_credentials(p, &hub)).unwrap_or_default(); |
| 199 |
let token = |
| 200 |
env_token.or_else(|| repo.config.remote_tokens.get(&name).cloned()).or(up_token).or(Some(host.token).filter(|t| !t.is_empty())); |
| 201 |
let ca = env_ca.or_else(|| repo.config.remote_cas.get(&name).map(PathBuf::from)).or(up_ca).or(host.ca); |
| 5c6e92fd Andy McCall ↶ |
202 |
return Ok(Target { hub, token, ca, owner, name: repo_name }); |
| 203 |
} |
| 204 |
|
| 205 |
let hub = choice |
| 206 |
.hub |
| 207 |
.map(String::from) |
| 208 |
.or_else(|| std::env::var("OH_HUB").ok()) |
| 209 |
.or_else(|| cfg.default_hub.clone()) |
| 210 |
.ok_or_else(|| anyhow!("not in an Oxygen checkout: give --repo OWNER/NAME and --hub URL, or run `oh auth login`"))?; |
| 211 |
let hub = hub.trim_end_matches('/').to_string(); |
| 212 |
let host = saved(&hub).unwrap_or_default(); |
| 213 |
Ok(Target { |
| 214 |
token: env_token.or(Some(host.token).filter(|t| !t.is_empty())), |
| 215 |
ca: env_ca.or(host.ca), |
| 216 |
hub, |
| 217 |
owner: String::new(), |
| 218 |
name: String::new(), |
| 219 |
}) |
| 220 |
} |
| 221 |
|
| 222 |
#[cfg(test)] |
| 223 |
mod tests { |
| 224 |
use super::*; |
| 225 |
|
| 226 |
#[test] |
| 227 |
fn remote_urls_name_the_hub_and_the_repository() { |
| 228 |
assert_eq!( |
| 229 |
split_url("https://earth.example:7343/andy/oxygen").unwrap(), |
| 230 |
("https://earth.example:7343".into(), "andy".into(), "oxygen".into()) |
| 231 |
); |
| 232 |
assert_eq!(split_url("http://127.0.0.1:9/a/b/").unwrap().2, "b"); |
| 233 |
assert!(split_url("https://hub/only-owner").is_err()); |
| 234 |
assert!(split_url("not a url").is_err()); |
| cefb0ea2 Andy McCall ↶ |
235 |
} |
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
#[test] |
| 241 |
fn checkouts_lend_their_hub_and_token() { |
| 242 |
if std::env::var_os("OH_TOKEN").is_some() || std::env::var_os("OXY_TOKEN").is_some() || std::env::var_os("OH_HUB").is_some() { |
| 243 |
return; |
| 244 |
} |
| 245 |
let dir = tempfile::tempdir().unwrap(); |
| 246 |
let parent = dir.path().join("metalgear"); |
| 247 |
let mut p = oxy_core::repo::Repo::init(&parent).unwrap(); |
| 248 |
p.config.set("remote.origin.url", "https://hub.example/doomsdayone/metalgear").unwrap(); |
| 249 |
p.config.set("remote.origin.token", "parent-token").unwrap(); |
| 250 |
p.save_config().unwrap(); |
| 251 |
let sub = parent.join("rstar-api"); |
| 252 |
let mut s = oxy_core::repo::Repo::init(&sub).unwrap(); |
| 253 |
s.config.set("remote.origin.url", "https://hub.example/doomsdayone/rstar-api").unwrap(); |
| 254 |
s.save_config().unwrap(); |
| 255 |
let cfg = Config::default(); |
| 256 |
let none = Choice { repo: None, hub: None, remote: None }; |
| 257 |
let t = resolve(&none, &sub, &cfg).unwrap(); |
| 258 |
assert_eq!((t.name.as_str(), t.token.as_deref()), ("rstar-api", Some("parent-token"))); |
| 259 |
let other = Choice { repo: Some("doomsdayone/other"), hub: None, remote: None }; |
| 260 |
let t = resolve(&other, &parent, &cfg).unwrap(); |
| 261 |
assert_eq!((t.hub.as_str(), t.token.as_deref()), ("https://hub.example", Some("parent-token"))); |
| 5c6e92fd Andy McCall ↶ |
262 |
} |
| 263 |
} |