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