OXYGENHUB
# dd327d76062d oxygenhub / crates / oh / src / target.rs
7.8 KiB · Rust · last changed Drops: per-user gists, each a small hidden Oxygen repository (#279) 16 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),
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.
56
    pub fn save(&self) -> Result<()> {
57
        use std::io::Write;
58
        use std::os::unix::fs::OpenOptionsExt;
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 f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;
63
        f.write_all(toml::to_string_pretty(self)?.as_bytes())?;
64
        f.sync_all()?;
65
        std::fs::rename(&tmp, &p)?;
66
        Ok(())
67
    }
68
}
69
70
/// A hub, and a repository on it when the command needs one.
71
#[derive(Clone, Debug)]
72
pub struct Target {
73
    /// `https://host:port`, no trailing slash.
74
    pub hub: String,
75
    pub token: Option<String>,
76
    pub ca: Option<PathBuf>,
77
    pub owner: String,
78
    pub name: String,
79
}
80
81
impl Target {
82
    pub fn repo(&self) -> Result<(&str, &str)> {
83
        if self.owner.is_empty() {
84
            bail!("no repository: run inside an Oxygen checkout, or give --repo OWNER/NAME");
85
        }
86
        Ok((&self.owner, &self.name))
87
    }
88
89
    /// `/repos/{owner}/{name}`.
90
    pub fn repo_path(&self) -> Result<String> {
91
        let (o, n) = self.repo()?;
92
        Ok(format!("/repos/{o}/{n}"))
93
    }
94
}
95
96
/// Split `https://host:port/owner/name` into the hub and the repository.
97
pub fn split_url(url: &str) -> Result<(String, String, String)> {
98
    let (scheme, rest) = url.split_once("://").ok_or_else(|| anyhow!("{url} is not a hub URL"))?;
99
    let mut parts = rest.trim_end_matches('/').splitn(2, '/');
100
    let host = parts.next().unwrap_or("");
101
    let path = parts.next().unwrap_or("");
102
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
103
    match segs.as_slice() {
104
        [o, n] => Ok((format!("{scheme}://{host}"), o.to_string(), n.trim_end_matches(".oxy").to_string())),
166f6e9b Andy McCall 105
        // A drop's clone (oxygenhub#279): `https://hub/OWNER/drops/ID`.
106
        [o, "drops", id] => Ok((format!("{scheme}://{host}"), o.to_string(), format!("drops/{id}"))),
5c6e92fd Andy McCall ↶ 107
        _ => bail!("{url} does not name a repository as https://hub/OWNER/NAME"),
108
    }
109
}
110
111
pub struct Choice<'a> {
112
    pub repo: Option<&'a str>,
113
    pub hub: Option<&'a str>,
114
    pub remote: Option<&'a str>,
115
}
116
117
/// Resolve what to talk to from the flags, the checkout at `dir`, the
118
/// environment and the saved configuration.
119
pub fn resolve(choice: &Choice, dir: &Path, cfg: &Config) -> Result<Target> {
120
    let env_token = std::env::var("OH_TOKEN").ok().or_else(|| std::env::var("OXY_TOKEN").ok()).filter(|t| !t.is_empty());
121
    let env_ca = std::env::var_os("OXY_CA").map(PathBuf::from);
2bbe88a8 Andy McCall ↶ 122
    let saved = |hub: &str| Some(stored(hub));
5c6e92fd Andy McCall ↶ 123
    if let Some(r) = choice.repo {
124
        let (owner, name) = r.split_once('/').ok_or_else(|| anyhow!("--repo takes OWNER/NAME"))?;
125
        let hub = choice
126
            .hub
127
            .map(String::from)
128
            .or_else(|| std::env::var("OH_HUB").ok())
129
            .or_else(|| cfg.default_hub.clone())
130
            .ok_or_else(|| anyhow!("which hub? give --hub URL, set OH_HUB, or run `oh auth login`"))?;
131
        let hub = hub.trim_end_matches('/').to_string();
132
        let host = saved(&hub).unwrap_or_default();
133
        return Ok(Target {
134
            token: env_token.or(Some(host.token).filter(|t| !t.is_empty())),
135
            ca: env_ca.or(host.ca),
136
            hub,
137
            owner: owner.into(),
138
            name: name.into(),
139
        });
140
    }
141
    // The checkout's remote.
142
    if let Ok(repo) = oxy_core::repo::Repo::open(dir) {
143
        let remotes = &repo.config.remotes;
144
        let name = match choice.remote {
145
            Some(n) => n.to_string(),
146
            None if remotes.contains_key("origin") => "origin".into(),
147
            None if remotes.len() == 1 => remotes.keys().next().unwrap().clone(),
148
            None if remotes.is_empty() => bail!("this checkout has no remote; give --repo OWNER/NAME"),
149
            None => bail!(
150
                "this checkout has several remotes ({}); choose one with --remote",
151
                remotes.keys().cloned().collect::<Vec<_>>().join(", ")
152
            ),
153
        };
154
        let url = remotes.get(&name).ok_or_else(|| anyhow!("no remote named {name}"))?;
155
        let (hub, owner, repo_name) = split_url(url)?;
156
        let host = saved(&hub).unwrap_or_default();
157
        let token = env_token.or_else(|| repo.config.remote_tokens.get(&name).cloned()).or(Some(host.token).filter(|t| !t.is_empty()));
158
        let ca = env_ca.or_else(|| repo.config.remote_cas.get(&name).map(PathBuf::from)).or(host.ca);
159
        return Ok(Target { hub, token, ca, owner, name: repo_name });
160
    }
161
    // No repository: commands that need only a hub.
162
    let hub = choice
163
        .hub
164
        .map(String::from)
165
        .or_else(|| std::env::var("OH_HUB").ok())
166
        .or_else(|| cfg.default_hub.clone())
167
        .ok_or_else(|| anyhow!("not in an Oxygen checkout: give --repo OWNER/NAME and --hub URL, or run `oh auth login`"))?;
168
    let hub = hub.trim_end_matches('/').to_string();
169
    let host = saved(&hub).unwrap_or_default();
170
    Ok(Target {
171
        token: env_token.or(Some(host.token).filter(|t| !t.is_empty())),
172
        ca: env_ca.or(host.ca),
173
        hub,
174
        owner: String::new(),
175
        name: String::new(),
176
    })
177
}
178
179
#[cfg(test)]
180
mod tests {
181
    use super::*;
182
183
    #[test]
184
    fn remote_urls_name_the_hub_and_the_repository() {
185
        assert_eq!(
186
            split_url("https://earth.example:7343/andy/oxygen").unwrap(),
187
            ("https://earth.example:7343".into(), "andy".into(), "oxygen".into())
188
        );
189
        assert_eq!(split_url("http://127.0.0.1:9/a/b/").unwrap().2, "b");
166f6e9b Andy McCall 190
        // A drop's clone names its hub, so `oh drop` works inside it.
191
        assert_eq!(
192
            split_url("https://hub/andy/drops/0123456789abcdef01234567").unwrap(),
193
            ("https://hub".into(), "andy".into(), "drops/0123456789abcdef01234567".into())
194
        );
195
        assert!(split_url("https://hub/a/b/c").is_err());
5c6e92fd Andy McCall ↶ 196
        assert!(split_url("https://hub/only-owner").is_err());
197
        assert!(split_url("not a url").is_err());
198
    }
199
}