forked from sourcegraph/sg.nvim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.rs
More file actions
95 lines (79 loc) · 2.29 KB
/
Copy pathauth.rs
File metadata and controls
95 lines (79 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use {
anyhow::{Context, Result},
once_cell::sync::Lazy,
serde::{Deserialize, Serialize},
std::sync::Mutex,
};
#[derive(Serialize, Deserialize, Default)]
pub struct CodyCredentials {
pub endpoint: Option<String>,
pub token: Option<String>,
}
static ACCESS_TOKEN: Lazy<Mutex<Option<String>>> = Lazy::new(|| {
fn get_token() -> Option<String> {
if let Ok(token) = std::env::var("SRC_ACCESS_TOKEN") {
if !token.is_empty() {
return Some(token);
}
}
if let Some(CodyCredentials {
token: Some(token), ..
}) = get_credentials()
{
return Some(token);
};
None
}
Mutex::new(get_token())
});
static ENDPOINT: Lazy<Mutex<Option<String>>> = Lazy::new(|| {
fn get_token() -> Option<String> {
if let Ok(token) = std::env::var("SRC_ENDPOINT") {
if !token.is_empty() {
return Some(token);
}
}
if let Some(CodyCredentials {
endpoint: Some(token),
..
}) = get_credentials()
{
return Some(token);
};
None
}
Mutex::new(get_token())
});
pub fn get_access_token() -> Option<String> {
ACCESS_TOKEN.lock().expect("to unlock access token").clone()
}
pub fn get_endpoint() -> String {
ENDPOINT
.lock()
.expect("to unlock endpoint")
.clone()
.unwrap_or_else(|| "https://sourcegraph.com/".to_string())
.trim_end_matches('/')
.to_string()
}
fn get_entry() -> Result<keyring::Entry> {
let username = whoami::username();
keyring::Entry::new("cody-access-token", &username).context("getting keyring entry")
}
fn get_credentials() -> Option<CodyCredentials> {
let entry = get_entry().ok()?;
let token = entry.get_password().ok()?;
serde_json::from_str(&token).ok()
}
pub fn set_credentials(credentials: CodyCredentials) -> Result<()> {
if let Some(token) = &credentials.token {
std::env::set_var("SRC_ACCESS_TOKEN", token);
}
if let Some(endpoint) = &credentials.endpoint {
std::env::set_var("SRC_ENDPOINT", endpoint);
}
let entry = get_entry()?;
entry
.set_password(&serde_json::to_string(&credentials)?)
.context("set_credentials")
}