OXYGENHUB
# cc1cd197df1d oxygenhub / crates / oh / src / target.rs
7.2 KiB · Rust · last changed oh: OxygenHub from the command line 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
pub struct Choice<'a> {
106
    pub repo: Option<&'a str>,
107
    pub hub: Option<&'a str>,
108
    pub remote: Option<&'a str>,
109
}
110
111
/// Resolve what to talk to from the flags, the checkout at `dir`, the
112
/// environment and the saved configuration.
113
pub fn resolve(choice: &Choice, dir: &Path, cfg: &Config) -> Result<Target> {
114
    let env_token = std::env::var("OH_TOKEN").ok().or_else(|| std::env::var("OXY_TOKEN").ok()).filter(|t| !t.is_empty());
115
    let env_ca = std::env::var_os("OXY_CA").map(PathBuf::from);
116
    let saved = |hub: &str| cfg.hosts.get(hub).cloned();
117
    if let Some(r) = choice.repo {
118
        let (owner, name) = r.split_once('/').ok_or_else(|| anyhow!("--repo takes OWNER/NAME"))?;
119
        let hub = choice
120
            .hub
121
            .map(String::from)
122
            .or_else(|| std::env::var("OH_HUB").ok())
123
            .or_else(|| cfg.default_hub.clone())
124
            .ok_or_else(|| anyhow!("which hub? give --hub URL, set OH_HUB, or run `oh auth login`"))?;
125
        let hub = hub.trim_end_matches('/').to_string();
126
        let host = saved(&hub).unwrap_or_default();
127
        return Ok(Target {
128
            token: env_token.or(Some(host.token).filter(|t| !t.is_empty())),
129
            ca: env_ca.or(host.ca),
130
            hub,
131
            owner: owner.into(),
132
            name: name.into(),
133
        });
134
    }
135
    // The checkout's remote.
136
    if let Ok(repo) = oxy_core::repo::Repo::open(dir) {
137
        let remotes = &repo.config.remotes;
138
        let name = match choice.remote {
139
            Some(n) => n.to_string(),
140
            None if remotes.contains_key("origin") => "origin".into(),
141
            None if remotes.len() == 1 => remotes.keys().next().unwrap().clone(),
142
            None if remotes.is_empty() => bail!("this checkout has no remote; give --repo OWNER/NAME"),
143
            None => bail!(
144
                "this checkout has several remotes ({}); choose one with --remote",
145
                remotes.keys().cloned().collect::<Vec<_>>().join(", ")
146
            ),
147
        };
148
        let url = remotes.get(&name).ok_or_else(|| anyhow!("no remote named {name}"))?;
149
        let (hub, owner, repo_name) = split_url(url)?;
150
        let host = saved(&hub).unwrap_or_default();
151
        let token = env_token.or_else(|| repo.config.remote_tokens.get(&name).cloned()).or(Some(host.token).filter(|t| !t.is_empty()));
152
        let ca = env_ca.or_else(|| repo.config.remote_cas.get(&name).map(PathBuf::from)).or(host.ca);
153
        return Ok(Target { hub, token, ca, owner, name: repo_name });
154
    }
155
    // No repository: commands that need only a hub.
156
    let hub = choice
157
        .hub
158
        .map(String::from)
159
        .or_else(|| std::env::var("OH_HUB").ok())
160
        .or_else(|| cfg.default_hub.clone())
161
        .ok_or_else(|| anyhow!("not in an Oxygen checkout: give --repo OWNER/NAME and --hub URL, or run `oh auth login`"))?;
162
    let hub = hub.trim_end_matches('/').to_string();
163
    let host = saved(&hub).unwrap_or_default();
164
    Ok(Target {
165
        token: env_token.or(Some(host.token).filter(|t| !t.is_empty())),
166
        ca: env_ca.or(host.ca),
167
        hub,
168
        owner: String::new(),
169
        name: String::new(),
170
    })
171
}
172
173
#[cfg(test)]
174
mod tests {
175
    use super::*;
176
177
    #[test]
178
    fn remote_urls_name_the_hub_and_the_repository() {
179
        assert_eq!(
180
            split_url("https://earth.example:7343/andy/oxygen").unwrap(),
181
            ("https://earth.example:7343".into(), "andy".into(), "oxygen".into())
182
        );
183
        assert_eq!(split_url("http://127.0.0.1:9/a/b/").unwrap().2, "b");
184
        assert!(split_url("https://hub/only-owner").is_err());
185
        assert!(split_url("not a url").is_err());
186
    }
187
}