OXYGENHUB
◆ v0.1.0 oxygenhub / crates / oh / src / target.rs
11.0 KiB · Rust · last changed oh builds for Windows 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
        // Windows has no HOME as a rule: the roaming profile's application data.
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))]
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
55
    /// Written owner-only: it holds tokens. (On Windows the file sits in the
56
    /// user's own profile, which only they and administrators can read.)
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");
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)?;
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
/// A hub, and a repository on it when the command needs one.
75
#[derive(Clone, Debug)]
76
pub struct Target {
77
    /// `https://host:port`, no trailing slash.
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
    /// `/repos/{owner}/{name}`.
94
    pub fn repo_path(&self) -> Result<String> {
95
        let (o, n) = self.repo()?;
96
        Ok(format!("/repos/{o}/{n}"))
97
    }
98
}
99
100
/// Split `https://host:port/owner/name` into the hub and the repository.
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
113
/// A token and CA for `hub` from the checkout at `dir` or one enclosing
114
/// it (a subrepo's parent): the first remote on that hub that has each.
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
/// The hub of the checkout's remote (the one chosen, `origin`, or the only
135
/// one), for `--repo` without `--hub`.
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
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
/// Resolve what to talk to from the flags, the checkout at `dir`, the
153
/// environment and the saved configuration.
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"))?;
160
        // Inside a checkout, its remote's hub, token and CA serve for
161
        // another repository on the same hub.
162
        let hub = choice
163
            .hub
164
            .map(String::from)
165
            .or_else(|| std::env::var("OH_HUB").ok())
166
            .or_else(|| checkout_hub(dir, choice.remote))
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();
171
        let (co_token, co_ca) = checkout_credentials(dir, &hub);
172
        return Ok(Target {
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),
175
            hub,
176
            owner: owner.into(),
177
            name: name.into(),
178
        });
179
    }
180
    // The checkout's remote.
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();
196
        // The remote's own, then a parent checkout's for the same hub (a
197
        // subrepo cloned before it recorded them), then the saved ones.
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);
202
        return Ok(Target { hub, token, ca, owner, name: repo_name });
203
    }
204
    // No repository: commands that need only a hub.
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());
235
    }
236
237
    /// oxygenhub#50, #51: a subrepo checkout whose remote has no token
238
    /// borrows its parent's for the same hub, and --repo inside a checkout
239
    /// takes the checkout's hub and token.
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")));
262
    }
263
}