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