1#![feature(async_closure)]
2use reqwest::{header::*, Client, ClientBuilder};
3
4static mut TOKEN: Option<String> = None;
5
6pub fn gh_client(token: Option<&str>) -> ClientBuilder {
7 let mut default_headers = HeaderMap::new();
8
9 if let Some(token) = token.or(get_token()) {
10 default_headers.insert(
11 AUTHORIZATION,
12 HeaderValue::from_str(&format!("Bearer {}", token)).unwrap(),
13 );
14 }
15
16 default_headers.insert(
17 "Accept",
18 HeaderValue::from_static("application/vnd.github.v3+json"),
19 );
20 default_headers.insert(USER_AGENT, HeaderValue::from_str("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36").unwrap());
21
22 Client::builder().default_headers(default_headers)
23}
24
25pub fn get_token() -> Option<&'static str> {
26 unsafe { TOKEN.as_ref().map(|token| &token[..]) }
27}
28
29pub fn set_token<T: ToString>(token: Option<T>) {
30 unsafe { TOKEN = token.map(|token| token.to_string()) };
31}
32
33#[macro_export]
34macro_rules! gh_api_get {
35 ($fmt:literal$(, $($arg:tt)*)?) => {
36 $crate::gh_api_get!($crate::gh_client(None).build().unwrap(), $fmt$(, $($arg)*)?)
37 };
38
39 ($client:expr, $fmt:literal$(, $($arg:tt)*)?) => {
40 $crate::gh_get!($client, "https://api.github.com/{}", format!($fmt$(, $($arg)*)?))
41 };
42}
43
44#[macro_export]
45macro_rules! gh_get {
46 ($fmt:literal$(, $($arg:tt)*)?) => {
47 $crate::gh_get!($crate::gh_client(None).build().unwrap(), $fmt$(, $($arg)*)?)
48 };
49
50 ($client:expr, $fmt:literal$(, $($arg:tt)*)?) => {
51 $client.get(&format!($fmt$(, $($arg)*)?))
52 };
53}