forked from rust-lang/crates.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.rs
64 lines (55 loc) · 2.08 KB
/
github.rs
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
//! This module implements functionality for interacting with GitHub.
use oauth2::AccessToken;
use reqwest::{self, header};
use serde::de::DeserializeOwned;
use std::str;
use crate::app::App;
use crate::util::errors::{cargo_err, internal, not_found, AppError, AppResult};
/// Does all the nonsense for sending a GET to Github. Doesn't handle parsing
/// because custom error-code handling may be desirable. Use
/// `parse_github_response` to handle the "common" processing of responses.
pub fn github_api<T>(app: &App, url: &str, auth: &AccessToken) -> AppResult<T>
where
T: DeserializeOwned,
{
let url = format!("{}://api.github.com{}", app.config.api_protocol, url);
info!("GITHUB HTTP: {}", url);
app.http_client()
.get(&url)
.header(header::ACCEPT, "application/vnd.github.v3+json")
.header(header::AUTHORIZATION, format!("token {}", auth.secret()))
.header(header::USER_AGENT, "crates.io (https://crates.io)")
.send()?
.error_for_status()
.map_err(|e| handle_error_response(app, &e))?
.json()
.map_err(Into::into)
}
fn handle_error_response(app: &App, error: &reqwest::Error) -> Box<dyn AppError> {
use reqwest::StatusCode as Status;
match error.status() {
Some(Status::UNAUTHORIZED) | Some(Status::FORBIDDEN) => cargo_err(&format!(
"It looks like you don't have permission \
to query a necessary property from Github \
to complete this request. \
You may need to re-authenticate on \
crates.io to grant permission to read \
github org memberships. Just go to \
https://{}/login",
app.config.domain_name,
)),
Some(Status::NOT_FOUND) => not_found(),
_ => internal(&format_args!(
"didn't get a 200 result from github: {}",
error
)),
}
}
pub fn team_url(login: &str) -> String {
let mut login_pieces = login.split(':');
login_pieces.next();
format!(
"https://github.com/{}",
login_pieces.next().expect("org failed"),
)
}