OXYGENHUB
◆ v0.9.23 oxygenhub / crates / oh / src / target.rs
11.7 KiB · Rust · last changed Drops: per-user gists, each a small hidden Oxygen repository (#279) 15 days ago source blame history raw
5c6e92fd Andy McCall ↶ 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::path::{Path, PathBuf};
12
2bbe88a8 Andy McCall ↶ 13
/// `~/.config/oh/config.toml`: the default hub. Tokens are oxy's: one
14
/// sign-in (`oh auth login` or `oxy auth login`) serves both, kept in
15
/// oxy's credential store (oxygen#47).
5c6e92fd Andy McCall ↶ 16
#[derive(Debug, Default, Serialize, Deserialize)]
17
pub struct Config {
18
    #[serde(default)]
19
    pub default_hub: Option<String>,
20
}
21
2bbe88a8 Andy McCall ↶ 22
/// What oxy's credential store holds for a hub.
23
#[derive(Clone, Debug, Default)]
5c6e92fd Andy McCall ↶ 24
pub struct Host {
25
    pub token: String,
26
    pub ca: Option<PathBuf>,
2bbe88a8 Andy McCall ↶ 27
}
28
29
fn stored(hub: &str) -> Host {
30
    let (token, ca) = oxy_core::credentials::Credentials::user().lookup(hub);
31
    Host { token: token.unwrap_or_default(), ca }
5c6e92fd Andy McCall ↶ 32
}
33
34
pub fn config_path() -> Result<PathBuf> {
35
    if let Some(p) = std::env::var_os("OH_CONFIG") {
36
        return Ok(PathBuf::from(p));
37
    }
38
    let base = match std::env::var_os("XDG_CONFIG_HOME") {
39
        Some(d) => PathBuf::from(d),
bd630386 Andy McCall ↶ 40
        // Windows has no HOME as a rule: the roaming profile's application data.
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))]
5c6e92fd Andy McCall ↶ 44
        None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".config"),
45
    };
46
    Ok(base.join("oh").join("config.toml"))
47
}
48
49
impl Config {
50
    pub fn load() -> Result<Config> {
51
        let p = config_path()?;
52
        match std::fs::read_to_string(&p) {
53
            Ok(t) => toml::from_str(&t).with_context(|| format!("parse {}", p.display())),
54
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
55
            Err(e) => Err(e).with_context(|| format!("read {}", p.display())),
56
        }
57
    }
58
bd630386 Andy McCall ↶ 59
    /// Written owner-only: it holds tokens. (On Windows the file sits in the
60
    /// user's own profile, which only they and administrators can read.)
5c6e92fd Andy McCall ↶ 61
    pub fn save(&self) -> Result<()> {
62
        use std::io::Write;
63
        let p = config_path()?;
64
        std::fs::create_dir_all(p.parent().unwrap())?;
65
        let tmp = p.with_extension("toml.tmp");
bd630386 Andy McCall ↶ 66
        let mut options = std::fs::OpenOptions::new();
67
        options.write(true).create(true).truncate(true);
68
        #[cfg(unix)]
69
        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
70
        let mut f = options.open(&tmp)?;
5c6e92fd Andy McCall ↶ 71
        f.write_all(toml::to_string_pretty(self)?.as_bytes())?;
72
        f.sync_all()?;
73
        std::fs::rename(&tmp, &p)?;
74
        Ok(())
75
    }
76
}
77
78
/// A hub, and a repository on it when the command needs one.
79
#[derive(Clone, Debug)]
80
pub struct Target {
81
    /// `https://host:port`, no trailing slash.
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
    pub fn repo(&self) -> Result<(&str, &str)> {
91
        if self.owner.is_empty() {
92
            bail!("no repository: run inside an Oxygen checkout, or give --repo OWNER/NAME");
93
        }
94
        Ok((&self.owner, &self.name))
95
    }
96
97
    /// `/repos/{owner}/{name}`.
98
    pub fn repo_path(&self) -> Result<String> {
99
        let (o, n) = self.repo()?;
100
        Ok(format!("/repos/{o}/{n}"))
101
    }
102
}
103
104
/// Split `https://host:port/owner/name` into the hub and the repository.
105
pub fn split_url(url: &str) -> Result<(String, String, String)> {
106
    let (scheme, rest) = url.split_once("://").ok_or_else(|| anyhow!("{url} is not a hub URL"))?;
107
    let mut parts = rest.trim_end_matches('/').splitn(2, '/');
108
    let host = parts.next().unwrap_or("");
109
    let path = parts.next().unwrap_or("");
110
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
111
    match segs.as_slice() {
112
        [o, n] => Ok((format!("{scheme}://{host}"), o.to_string(), n.trim_end_matches(".oxy").to_string())),
166f6e9b Andy McCall 113
        // A drop's clone (oxygenhub#279): `https://hub/OWNER/drops/ID`.
114
        [o, "drops", id] => Ok((format!("{scheme}://{host}"), o.to_string(), format!("drops/{id}"))),
5c6e92fd Andy McCall ↶ 115
        _ => bail!("{url} does not name a repository as https://hub/OWNER/NAME"),
116
    }
117
}
118
cefb0ea2 Andy McCall ↶ 119
/// A token and CA for `hub` from the checkout at `dir` or one enclosing
120
/// it (a subrepo's parent): the first remote on that hub that has each.
121
fn checkout_credentials(dir: &Path, hub: &str) -> (Option<String>, Option<PathBuf>) {
122
    let (mut token, mut ca) = (None, None);
123
    let mut at = Some(dir.to_path_buf());
124
    while let Some(d) = at {
125
        let Ok(repo) = oxy_core::repo::Repo::open(&d) else { break };
126
        for (name, url) in &repo.config.remotes {
127
            if split_url(url).is_ok_and(|(h, _, _)| h.eq_ignore_ascii_case(hub)) {
128
                token = token.or_else(|| repo.config.remote_tokens.get(name).cloned());
129
                ca = ca.or_else(|| repo.config.remote_cas.get(name).map(PathBuf::from));
130
            }
131
        }
132
        if token.is_some() && ca.is_some() {
133
            break;
134
        }
135
        at = repo.root().parent().map(Path::to_path_buf);
136
    }
137
    (token, ca)
138
}
139
140
/// The hub of the checkout's remote (the one chosen, `origin`, or the only
141
/// one), for `--repo` without `--hub`.
142
fn checkout_hub(dir: &Path, remote: Option<&str>) -> Option<String> {
143
    let repo = oxy_core::repo::Repo::open(dir).ok()?;
144
    let remotes = &repo.config.remotes;
145
    let url = match remote {
146
        Some(n) => remotes.get(n)?,
147
        None => remotes.get("origin").or_else(|| (remotes.len() == 1).then(|| remotes.values().next()).flatten())?,
148
    };
149
    split_url(url).ok().map(|(hub, _, _)| hub)
150
}
151
5c6e92fd Andy McCall ↶ 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
/// Resolve what to talk to from the flags, the checkout at `dir`, the
159
/// environment and the saved configuration.
160
pub fn resolve(choice: &Choice, dir: &Path, cfg: &Config) -> Result<Target> {
161
    let env_token = std::env::var("OH_TOKEN").ok().or_else(|| std::env::var("OXY_TOKEN").ok()).filter(|t| !t.is_empty());
162
    let env_ca = std::env::var_os("OXY_CA").map(PathBuf::from);
2bbe88a8 Andy McCall ↶ 163
    let saved = |hub: &str| Some(stored(hub));
5c6e92fd Andy McCall ↶ 164
    if let Some(r) = choice.repo {
165
        let (owner, name) = r.split_once('/').ok_or_else(|| anyhow!("--repo takes OWNER/NAME"))?;
cefb0ea2 Andy McCall ↶ 166
        // Inside a checkout, its remote's hub, token and CA serve for
167
        // another repository on the same hub.
5c6e92fd Andy McCall ↶ 168
        let hub = choice
169
            .hub
170
            .map(String::from)
171
            .or_else(|| std::env::var("OH_HUB").ok())
cefb0ea2 Andy McCall ↶ 172
            .or_else(|| checkout_hub(dir, choice.remote))
5c6e92fd Andy McCall ↶ 173
            .or_else(|| cfg.default_hub.clone())
174
            .ok_or_else(|| anyhow!("which hub? give --hub URL, set OH_HUB, or run `oh auth login`"))?;
175
        let hub = hub.trim_end_matches('/').to_string();
176
        let host = saved(&hub).unwrap_or_default();
cefb0ea2 Andy McCall ↶ 177
        let (co_token, co_ca) = checkout_credentials(dir, &hub);
5c6e92fd Andy McCall ↶ 178
        return Ok(Target {
cefb0ea2 Andy McCall ↶ 179
            token: env_token.or(co_token).or(Some(host.token).filter(|t| !t.is_empty())),
180
            ca: env_ca.or(co_ca).or(host.ca),
5c6e92fd Andy McCall ↶ 181
            hub,
182
            owner: owner.into(),
183
            name: name.into(),
184
        });
185
    }
186
    // The checkout's remote.
187
    if let Ok(repo) = oxy_core::repo::Repo::open(dir) {
188
        let remotes = &repo.config.remotes;
189
        let name = match choice.remote {
190
            Some(n) => n.to_string(),
191
            None if remotes.contains_key("origin") => "origin".into(),
192
            None if remotes.len() == 1 => remotes.keys().next().unwrap().clone(),
193
            None if remotes.is_empty() => bail!("this checkout has no remote; give --repo OWNER/NAME"),
194
            None => bail!(
195
                "this checkout has several remotes ({}); choose one with --remote",
196
                remotes.keys().cloned().collect::<Vec<_>>().join(", ")
197
            ),
198
        };
199
        let url = remotes.get(&name).ok_or_else(|| anyhow!("no remote named {name}"))?;
200
        let (hub, owner, repo_name) = split_url(url)?;
201
        let host = saved(&hub).unwrap_or_default();
cefb0ea2 Andy McCall ↶ 202
        // The remote's own, then a parent checkout's for the same hub (a
203
        // subrepo cloned before it recorded them), then the saved ones.
204
        let (up_token, up_ca) = repo.root().parent().map(|p| checkout_credentials(p, &hub)).unwrap_or_default();
205
        let token =
206
            env_token.or_else(|| repo.config.remote_tokens.get(&name).cloned()).or(up_token).or(Some(host.token).filter(|t| !t.is_empty()));
207
        let ca = env_ca.or_else(|| repo.config.remote_cas.get(&name).map(PathBuf::from)).or(up_ca).or(host.ca);
5c6e92fd Andy McCall ↶ 208
        return Ok(Target { hub, token, ca, owner, name: repo_name });
209
    }
210
    // No repository: commands that need only a hub.
211
    let hub = choice
212
        .hub
213
        .map(String::from)
214
        .or_else(|| std::env::var("OH_HUB").ok())
215
        .or_else(|| cfg.default_hub.clone())
216
        .ok_or_else(|| anyhow!("not in an Oxygen checkout: give --repo OWNER/NAME and --hub URL, or run `oh auth login`"))?;
217
    let hub = hub.trim_end_matches('/').to_string();
218
    let host = saved(&hub).unwrap_or_default();
219
    Ok(Target {
220
        token: env_token.or(Some(host.token).filter(|t| !t.is_empty())),
221
        ca: env_ca.or(host.ca),
222
        hub,
223
        owner: String::new(),
224
        name: String::new(),
225
    })
226
}
227
228
#[cfg(test)]
229
mod tests {
230
    use super::*;
231
232
    #[test]
233
    fn remote_urls_name_the_hub_and_the_repository() {
234
        assert_eq!(
235
            split_url("https://earth.example:7343/andy/oxygen").unwrap(),
236
            ("https://earth.example:7343".into(), "andy".into(), "oxygen".into())
237
        );
238
        assert_eq!(split_url("http://127.0.0.1:9/a/b/").unwrap().2, "b");
166f6e9b Andy McCall 239
        // A drop's clone names its hub, so `oh drop` works inside it.
240
        assert_eq!(
241
            split_url("https://hub/andy/drops/0123456789abcdef01234567").unwrap(),
242
            ("https://hub".into(), "andy".into(), "drops/0123456789abcdef01234567".into())
243
        );
244
        assert!(split_url("https://hub/a/b/c").is_err());
5c6e92fd Andy McCall ↶ 245
        assert!(split_url("https://hub/only-owner").is_err());
246
        assert!(split_url("not a url").is_err());
cefb0ea2 Andy McCall ↶ 247
    }
248
249
    /// oxygenhub#50, #51: a subrepo checkout whose remote has no token
250
    /// borrows its parent's for the same hub, and --repo inside a checkout
251
    /// takes the checkout's hub and token.
252
    #[test]
253
    fn checkouts_lend_their_hub_and_token() {
254
        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
            return;
256
        }
257
        let dir = tempfile::tempdir().unwrap();
258
        let parent = dir.path().join("metalgear");
259
        let mut p = oxy_core::repo::Repo::init(&parent).unwrap();
260
        p.config.set("remote.origin.url", "https://hub.example/doomsdayone/metalgear").unwrap();
261
        p.config.set("remote.origin.token", "parent-token").unwrap();
262
        p.save_config().unwrap();
263
        let sub = parent.join("rstar-api");
264
        let mut s = oxy_core::repo::Repo::init(&sub).unwrap();
265
        s.config.set("remote.origin.url", "https://hub.example/doomsdayone/rstar-api").unwrap();
266
        s.save_config().unwrap();
267
        let cfg = Config::default();
268
        let none = Choice { repo: None, hub: None, remote: None };
269
        let t = resolve(&none, &sub, &cfg).unwrap();
270
        assert_eq!((t.name.as_str(), t.token.as_deref()), ("rstar-api", Some("parent-token")));
271
        let other = Choice { repo: Some("doomsdayone/other"), hub: None, remote: None };
272
        let t = resolve(&other, &parent, &cfg).unwrap();
273
        assert_eq!((t.hub.as_str(), t.token.as_deref()), ("https://hub.example", Some("parent-token")));
5c6e92fd Andy McCall ↶ 274
    }
275
}