OXYGENHUB
# cefb0ea24511 oxygenhub / crates / oh / src / target.rs
10.6 KiB · Rust · last changed oh takes a hub and token from the checkout, and from a subrepo's parent 1 month ago source blame history raw
1
//! Which hub and repository a command talks to, and with which token.
2
//!
3
//! Inside an Oxygen checkout, `oh` uses the checkout's remote (`origin`, or
4
//! the only one, or `--remote NAME`): its URL names the hub and the
5
//! repository, and its token and CA are the ones `oxy` pushes with.
6
//! Elsewhere, `--repo OWNER/NAME` with the hub from `--hub`, `OH_HUB` or
7
//! the one `oh auth login` saved.
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
/// `~/.config/oh/config.toml`: tokens and CAs by hub, and the default hub.
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),
36
        None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".config"),
37
    };
38
    Ok(base.join("oh").join("config.toml"))
39
}
40
41
impl Config {
42
    pub fn load() -> Result<Config> {
43
        let p = config_path()?;
44
        match std::fs::read_to_string(&p) {
45
            Ok(t) => toml::from_str(&t).with_context(|| format!("parse {}", p.display())),
46
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
47
            Err(e) => Err(e).with_context(|| format!("read {}", p.display())),
48
        }
49
    }
50
51
    /// Written owner-only: it holds tokens.
52
    pub fn save(&self) -> Result<()> {
53
        use std::io::Write;
54
        use std::os::unix::fs::OpenOptionsExt;
55
        let p = config_path()?;
56
        std::fs::create_dir_all(p.parent().unwrap())?;
57
        let tmp = p.with_extension("toml.tmp");
58
        let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;
59
        f.write_all(toml::to_string_pretty(self)?.as_bytes())?;
60
        f.sync_all()?;
61
        std::fs::rename(&tmp, &p)?;
62
        Ok(())
63
    }
64
}
65
66
/// A hub, and a repository on it when the command needs one.
67
#[derive(Clone, Debug)]
68
pub struct Target {
69
    /// `https://host:port`, no trailing slash.
70
    pub hub: String,
71
    pub token: Option<String>,
72
    pub ca: Option<PathBuf>,
73
    pub owner: String,
74
    pub name: String,
75
}
76
77
impl Target {
78
    pub fn repo(&self) -> Result<(&str, &str)> {
79
        if self.owner.is_empty() {
80
            bail!("no repository: run inside an Oxygen checkout, or give --repo OWNER/NAME");
81
        }
82
        Ok((&self.owner, &self.name))
83
    }
84
85
    /// `/repos/{owner}/{name}`.
86
    pub fn repo_path(&self) -> Result<String> {
87
        let (o, n) = self.repo()?;
88
        Ok(format!("/repos/{o}/{n}"))
89
    }
90
}
91
92
/// Split `https://host:port/owner/name` into the hub and the repository.
93
pub fn split_url(url: &str) -> Result<(String, String, String)> {
94
    let (scheme, rest) = url.split_once("://").ok_or_else(|| anyhow!("{url} is not a hub URL"))?;
95
    let mut parts = rest.trim_end_matches('/').splitn(2, '/');
96
    let host = parts.next().unwrap_or("");
97
    let path = parts.next().unwrap_or("");
98
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
99
    match segs.as_slice() {
100
        [o, n] => Ok((format!("{scheme}://{host}"), o.to_string(), n.trim_end_matches(".oxy").to_string())),
101
        _ => bail!("{url} does not name a repository as https://hub/OWNER/NAME"),
102
    }
103
}
104
105
/// A token and CA for `hub` from the checkout at `dir` or one enclosing
106
/// it (a subrepo's parent): the first remote on that hub that has each.
107
fn checkout_credentials(dir: &Path, hub: &str) -> (Option<String>, Option<PathBuf>) {
108
    let (mut token, mut ca) = (None, None);
109
    let mut at = Some(dir.to_path_buf());
110
    while let Some(d) = at {
111
        let Ok(repo) = oxy_core::repo::Repo::open(&d) else { break };
112
        for (name, url) in &repo.config.remotes {
113
            if split_url(url).is_ok_and(|(h, _, _)| h.eq_ignore_ascii_case(hub)) {
114
                token = token.or_else(|| repo.config.remote_tokens.get(name).cloned());
115
                ca = ca.or_else(|| repo.config.remote_cas.get(name).map(PathBuf::from));
116
            }
117
        }
118
        if token.is_some() && ca.is_some() {
119
            break;
120
        }
121
        at = repo.root().parent().map(Path::to_path_buf);
122
    }
123
    (token, ca)
124
}
125
126
/// The hub of the checkout's remote (the one chosen, `origin`, or the only
127
/// one), for `--repo` without `--hub`.
128
fn checkout_hub(dir: &Path, remote: Option<&str>) -> Option<String> {
129
    let repo = oxy_core::repo::Repo::open(dir).ok()?;
130
    let remotes = &repo.config.remotes;
131
    let url = match remote {
132
        Some(n) => remotes.get(n)?,
133
        None => remotes.get("origin").or_else(|| (remotes.len() == 1).then(|| remotes.values().next()).flatten())?,
134
    };
135
    split_url(url).ok().map(|(hub, _, _)| hub)
136
}
137
138
pub struct Choice<'a> {
139
    pub repo: Option<&'a str>,
140
    pub hub: Option<&'a str>,
141
    pub remote: Option<&'a str>,
142
}
143
144
/// Resolve what to talk to from the flags, the checkout at `dir`, the
145
/// environment and the saved configuration.
146
pub fn resolve(choice: &Choice, dir: &Path, cfg: &Config) -> Result<Target> {
147
    let env_token = std::env::var("OH_TOKEN").ok().or_else(|| std::env::var("OXY_TOKEN").ok()).filter(|t| !t.is_empty());
148
    let env_ca = std::env::var_os("OXY_CA").map(PathBuf::from);
149
    let saved = |hub: &str| cfg.hosts.get(hub).cloned();
150
    if let Some(r) = choice.repo {
151
        let (owner, name) = r.split_once('/').ok_or_else(|| anyhow!("--repo takes OWNER/NAME"))?;
152
        // Inside a checkout, its remote's hub, token and CA serve for
153
        // another repository on the same hub.
154
        let hub = choice
155
            .hub
156
            .map(String::from)
157
            .or_else(|| std::env::var("OH_HUB").ok())
158
            .or_else(|| checkout_hub(dir, choice.remote))
159
            .or_else(|| cfg.default_hub.clone())
160
            .ok_or_else(|| anyhow!("which hub? give --hub URL, set OH_HUB, or run `oh auth login`"))?;
161
        let hub = hub.trim_end_matches('/').to_string();
162
        let host = saved(&hub).unwrap_or_default();
163
        let (co_token, co_ca) = checkout_credentials(dir, &hub);
164
        return Ok(Target {
165
            token: env_token.or(co_token).or(Some(host.token).filter(|t| !t.is_empty())),
166
            ca: env_ca.or(co_ca).or(host.ca),
167
            hub,
168
            owner: owner.into(),
169
            name: name.into(),
170
        });
171
    }
172
    // The checkout's remote.
173
    if let Ok(repo) = oxy_core::repo::Repo::open(dir) {
174
        let remotes = &repo.config.remotes;
175
        let name = match choice.remote {
176
            Some(n) => n.to_string(),
177
            None if remotes.contains_key("origin") => "origin".into(),
178
            None if remotes.len() == 1 => remotes.keys().next().unwrap().clone(),
179
            None if remotes.is_empty() => bail!("this checkout has no remote; give --repo OWNER/NAME"),
180
            None => bail!(
181
                "this checkout has several remotes ({}); choose one with --remote",
182
                remotes.keys().cloned().collect::<Vec<_>>().join(", ")
183
            ),
184
        };
185
        let url = remotes.get(&name).ok_or_else(|| anyhow!("no remote named {name}"))?;
186
        let (hub, owner, repo_name) = split_url(url)?;
187
        let host = saved(&hub).unwrap_or_default();
188
        // The remote's own, then a parent checkout's for the same hub (a
189
        // subrepo cloned before it recorded them), then the saved ones.
190
        let (up_token, up_ca) = repo.root().parent().map(|p| checkout_credentials(p, &hub)).unwrap_or_default();
191
        let token =
192
            env_token.or_else(|| repo.config.remote_tokens.get(&name).cloned()).or(up_token).or(Some(host.token).filter(|t| !t.is_empty()));
193
        let ca = env_ca.or_else(|| repo.config.remote_cas.get(&name).map(PathBuf::from)).or(up_ca).or(host.ca);
194
        return Ok(Target { hub, token, ca, owner, name: repo_name });
195
    }
196
    // No repository: commands that need only a hub.
197
    let hub = choice
198
        .hub
199
        .map(String::from)
200
        .or_else(|| std::env::var("OH_HUB").ok())
201
        .or_else(|| cfg.default_hub.clone())
202
        .ok_or_else(|| anyhow!("not in an Oxygen checkout: give --repo OWNER/NAME and --hub URL, or run `oh auth login`"))?;
203
    let hub = hub.trim_end_matches('/').to_string();
204
    let host = saved(&hub).unwrap_or_default();
205
    Ok(Target {
206
        token: env_token.or(Some(host.token).filter(|t| !t.is_empty())),
207
        ca: env_ca.or(host.ca),
208
        hub,
209
        owner: String::new(),
210
        name: String::new(),
211
    })
212
}
213
214
#[cfg(test)]
215
mod tests {
216
    use super::*;
217
218
    #[test]
219
    fn remote_urls_name_the_hub_and_the_repository() {
220
        assert_eq!(
221
            split_url("https://earth.example:7343/andy/oxygen").unwrap(),
222
            ("https://earth.example:7343".into(), "andy".into(), "oxygen".into())
223
        );
224
        assert_eq!(split_url("http://127.0.0.1:9/a/b/").unwrap().2, "b");
225
        assert!(split_url("https://hub/only-owner").is_err());
226
        assert!(split_url("not a url").is_err());
227
    }
228
229
    /// oxygenhub#50, #51: a subrepo checkout whose remote has no token
230
    /// borrows its parent's for the same hub, and --repo inside a checkout
231
    /// takes the checkout's hub and token.
232
    #[test]
233
    fn checkouts_lend_their_hub_and_token() {
234
        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() {
235
            return;
236
        }
237
        let dir = tempfile::tempdir().unwrap();
238
        let parent = dir.path().join("metalgear");
239
        let mut p = oxy_core::repo::Repo::init(&parent).unwrap();
240
        p.config.set("remote.origin.url", "https://hub.example/doomsdayone/metalgear").unwrap();
241
        p.config.set("remote.origin.token", "parent-token").unwrap();
242
        p.save_config().unwrap();
243
        let sub = parent.join("rstar-api");
244
        let mut s = oxy_core::repo::Repo::init(&sub).unwrap();
245
        s.config.set("remote.origin.url", "https://hub.example/doomsdayone/rstar-api").unwrap();
246
        s.save_config().unwrap();
247
        let cfg = Config::default();
248
        let none = Choice { repo: None, hub: None, remote: None };
249
        let t = resolve(&none, &sub, &cfg).unwrap();
250
        assert_eq!((t.name.as_str(), t.token.as_deref()), ("rstar-api", Some("parent-token")));
251
        let other = Choice { repo: Some("doomsdayone/other"), hub: None, remote: None };
252
        let t = resolve(&other, &parent, &cfg).unwrap();
253
        assert_eq!((t.hub.as_str(), t.token.as_deref()), ("https://hub.example", Some("parent-token")));
254
    }
255
}