From 1fe0c5372905fe940f0aa927d5ecd04079f07be5 Mon Sep 17 00:00:00 2001 From: Diptesh Date: Fri, 13 Jan 2023 18:34:22 +0530 Subject: [PATCH 1/8] build: add http dep --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index dbc77491..4c75bce5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ futures-util = { version = "0.3.15", optional = true } secrecy = "0.8.0" cfg-if = "1.0.0" either = "1.8.0" +http = "0.2.8" [dev-dependencies] tokio = { version = "1.17.0", default-features = false, features = [ From 5b1913e4ff17c6061a6425f0031d983851ce5ac8 Mon Sep 17 00:00:00 2001 From: Diptesh Date: Fri, 13 Jan 2023 18:34:51 +0530 Subject: [PATCH 2/8] refactor(example): use http in examples --- examples/device_flow.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/device_flow.rs b/examples/device_flow.rs index 0267f77e..42cefa16 100644 --- a/examples/device_flow.rs +++ b/examples/device_flow.rs @@ -1,5 +1,5 @@ use either::Either; -use reqwest::header::ACCEPT; +use http::header::ACCEPT; use std::time::Duration; #[tokio::main] From ee15954bc4c5b8ef217a2d0563342826a66ab2fd Mon Sep 17 00:00:00 2001 From: Diptesh Date: Fri, 13 Jan 2023 18:46:30 +0530 Subject: [PATCH 3/8] refactor: simple reqwest instances with http --- src/api/actions.rs | 48 +++++++++++++++----------- src/api/gitignore.rs | 2 +- src/api/markdown.rs | 2 +- src/api/pulls.rs | 20 +++++------ src/api/repos.rs | 6 ++-- src/api/repos/events.rs | 2 +- src/api/repos/generate.rs | 16 +++++---- src/api/repos/releases.rs | 4 +-- src/api/repos/stargazers.rs | 69 +++++++++++++++++++------------------ src/api/teams/team_repos.rs | 2 +- src/auth.rs | 2 +- src/lib.rs | 37 ++++++++++++-------- 12 files changed, 116 insertions(+), 94 deletions(-) diff --git a/src/api/actions.rs b/src/api/actions.rs index 6946c759..fd8426c8 100644 --- a/src/api/actions.rs +++ b/src/api/actions.rs @@ -3,13 +3,11 @@ use snafu::ResultExt; use crate::etag::{EntityTag, Etagged}; use crate::models::{ - workflows::WorkflowListArtifact, - ArtifactId, RepositoryId, RunId, - workflows::WorkflowDispatch + workflows::WorkflowDispatch, workflows::WorkflowListArtifact, ArtifactId, RepositoryId, RunId, }; use crate::{params, FromResponse, Octocrab, Page}; +use http::{header::HeaderMap, Method, StatusCode}; use hyperx::header::{ETag, IfNoneMatch, TypedHeaders}; -use reqwest::{header::HeaderMap, Method, StatusCode}; pub struct ListWorkflowRunArtifacts<'octo> { crab: &'octo Octocrab, @@ -93,8 +91,20 @@ pub struct WorkflowDispatchBuilder<'octo> { } impl<'octo> WorkflowDispatchBuilder<'octo> { - pub(crate) fn new(crab: &'octo Octocrab, owner: String, repo: String, workflow_id: String, r#ref: String) -> Self { - let mut this = Self { crab, owner, repo, workflow_id, data: Default::default() }; + pub(crate) fn new( + crab: &'octo Octocrab, + owner: String, + repo: String, + workflow_id: String, + r#ref: String, + ) -> Self { + let mut this = Self { + crab, + owner, + repo, + workflow_id, + data: Default::default(), + }; this.data.r#ref = r#ref; this } @@ -119,11 +129,9 @@ impl<'octo> WorkflowDispatchBuilder<'octo> { ); // this entry point doesn't actually return anything sensible - self.crab._post( - self.crab.absolute_url(route)?, - Some(&self.data), - ) - .await?; + self.crab + ._post(self.crab.absolute_url(route)?, Some(&self.data)) + .await?; Ok(()) } @@ -242,14 +250,13 @@ impl<'octo> ActionsHandler<'octo> { &self, response: reqwest::Response, ) -> crate::Result { - let data_response = - if let Some(redirect) = response.headers().get(reqwest::header::LOCATION) { - let location = redirect.to_str().expect("Location URL not valid str"); + let data_response = if let Some(redirect) = response.headers().get(http::header::LOCATION) { + let location = redirect.to_str().expect("Location URL not valid str"); - self.crab._get(location, None::<&()>).await? - } else { - response - }; + self.crab._get(location, None::<&()>).await? + } else { + response + }; data_response.bytes().await.context(crate::error::HttpSnafu) } @@ -411,11 +418,12 @@ impl<'octo> ActionsHandler<'octo> { workflow_id: impl Into, r#ref: impl Into, ) -> WorkflowDispatchBuilder<'_> { - WorkflowDispatchBuilder::new(self.crab, + WorkflowDispatchBuilder::new( + self.crab, owner.into(), repo.into(), workflow_id.into(), - r#ref.into() + r#ref.into(), ) } } diff --git a/src/api/gitignore.rs b/src/api/gitignore.rs index d3431970..b7699299 100644 --- a/src/api/gitignore.rs +++ b/src/api/gitignore.rs @@ -41,7 +41,7 @@ impl<'octo> GitignoreHandler<'octo> { .crab .client .get(self.crab.absolute_url(route)?) - .header(reqwest::header::ACCEPT, crate::format_media_type("raw")); + .header(http::header::ACCEPT, crate::format_media_type("raw")); self.crab .execute(request) diff --git a/src/api/markdown.rs b/src/api/markdown.rs index 508a177a..7de19a67 100644 --- a/src/api/markdown.rs +++ b/src/api/markdown.rs @@ -54,7 +54,7 @@ impl<'octo> MarkdownHandler<'octo> { .crab .client .post(self.crab.absolute_url("markdown/raw")?) - .header(reqwest::header::CONTENT_TYPE, "text/x-markdown") + .header(http::header::CONTENT_TYPE, "text/x-markdown") .body(text.into()); self.crab diff --git a/src/api/pulls.rs b/src/api/pulls.rs index 66559765..4178591f 100644 --- a/src/api/pulls.rs +++ b/src/api/pulls.rs @@ -2,15 +2,18 @@ mod comment; mod create; -mod update; mod list; mod merge; +mod update; use snafu::ResultExt; use crate::{Octocrab, Page}; -pub use self::{create::CreatePullRequestBuilder, update::UpdatePullRequestBuilder, list::ListPullRequestsBuilder}; +pub use self::{ + create::CreatePullRequestBuilder, list::ListPullRequestsBuilder, + update::UpdatePullRequestBuilder, +}; /// A client to GitHub's pull request API. /// @@ -132,7 +135,7 @@ impl<'octo> PullRequestHandler<'octo> { .crab .client .get(self.crab.absolute_url(route)?) - .header(reqwest::header::ACCEPT, crate::format_media_type("diff")); + .header(http::header::ACCEPT, crate::format_media_type("diff")); let response = crate::map_github_error(self.crab.execute(request).await?).await?; @@ -158,7 +161,7 @@ impl<'octo> PullRequestHandler<'octo> { .crab .client .get(self.crab.absolute_url(route)?) - .header(reqwest::header::ACCEPT, crate::format_media_type("patch")); + .header(http::header::ACCEPT, crate::format_media_type("patch")); let response = crate::map_github_error(self.crab.execute(request).await?).await?; @@ -211,10 +214,7 @@ impl<'octo> PullRequestHandler<'octo> { /// # Ok(()) /// # } /// ``` - pub fn update( - &self, - pull_number: u64, - ) -> update::UpdatePullRequestBuilder<'octo, '_> { + pub fn update(&self, pull_number: u64) -> update::UpdatePullRequestBuilder<'octo, '_> { update::UpdatePullRequestBuilder::new(self, pull_number) } @@ -378,7 +378,7 @@ impl<'octo> PullRequestHandler<'octo> { if let Some(media_type) = self.media_type { request = request.header( - reqwest::header::ACCEPT, + http::header::ACCEPT, crate::format_media_type(&media_type.to_string()), ); } @@ -439,7 +439,7 @@ impl<'octo> PullRequestHandler<'octo> { if let Some(media_type) = self.media_type { request = request.header( - reqwest::header::ACCEPT, + http::header::ACCEPT, crate::format_media_type(&media_type.to_string()), ); } diff --git a/src/api/repos.rs b/src/api/repos.rs index 6d0fe4e3..274a1b90 100644 --- a/src/api/repos.rs +++ b/src/api/repos.rs @@ -1,6 +1,6 @@ //! The repositories API. -use reqwest::header::ACCEPT; +use http::header::ACCEPT; mod branches; mod commits; @@ -15,15 +15,15 @@ mod status; mod tags; use crate::{models, params, Octocrab, Result}; +pub use branches::ListBranchesBuilder; pub use commits::ListCommitsBuilder; -pub use file::{GetContentBuilder, UpdateFileBuilder, DeleteFileBuilder}; +pub use file::{DeleteFileBuilder, GetContentBuilder, UpdateFileBuilder}; pub use generate::GenerateRepositoryBuilder; pub use pulls::ListPullsBuilder; pub use releases::ReleasesHandler; pub use stargazers::ListStarGazersBuilder; pub use status::{CreateStatusBuilder, ListStatusesBuilder}; pub use tags::ListTagsBuilder; -pub use branches::ListBranchesBuilder; /// Handler for GitHub's repository API. /// diff --git a/src/api/repos/events.rs b/src/api/repos/events.rs index 20ce501e..c344d4b8 100644 --- a/src/api/repos/events.rs +++ b/src/api/repos/events.rs @@ -5,8 +5,8 @@ use crate::{ repos::RepoHandler, FromResponse, Page, }; +use http::{header::HeaderMap, Method, StatusCode}; use hyperx::header::{ETag, IfNoneMatch, TypedHeaders}; -use reqwest::{header::HeaderMap, Method, StatusCode}; pub struct ListRepoEventsBuilder<'octo, 'handler> { handler: &'handler RepoHandler<'octo>, diff --git a/src/api/repos/generate.rs b/src/api/repos/generate.rs index f4c49645..14fb08d8 100644 --- a/src/api/repos/generate.rs +++ b/src/api/repos/generate.rs @@ -1,4 +1,4 @@ -use crate::{Error, repos::RepoHandler}; +use crate::{repos::RepoHandler, Error}; #[derive(serde::Serialize)] pub struct GenerateRepositoryBuilder<'octo, 'r> { @@ -58,16 +58,18 @@ impl<'octo, 'r> GenerateRepositoryBuilder<'octo, 'r> { owner = self.handler.owner, repo = self.handler.repo ); - let request = self.handler + let request = self + .handler .crab .client .post(self.handler.crab.absolute_url(url)?) .body(serde_json::to_string(&self).unwrap()) - .header(reqwest::header::ACCEPT, "application/vnd.github.baptiste-preview+json"); + .header( + http::header::ACCEPT, + "application/vnd.github.baptiste-preview+json", + ); let response = self.handler.crab.execute(request).await?; - crate::map_github_error(response) - .await - .map(drop) + crate::map_github_error(response).await.map(drop) } -} \ No newline at end of file +} diff --git a/src/api/repos/releases.rs b/src/api/repos/releases.rs index 20ba07b9..71145129 100644 --- a/src/api/repos/releases.rs +++ b/src/api/repos/releases.rs @@ -189,8 +189,8 @@ impl<'octo, 'r> ReleasesHandler<'octo, 'r> { .execute( self.parent .crab - .request_builder(&url, reqwest::Method::GET) - .header(reqwest::header::ACCEPT, "application/octet-stream"), + .request_builder(&url, http::Method::GET) + .header(http::header::ACCEPT, "application/octet-stream"), ) .await? .bytes_stream() diff --git a/src/api/repos/stargazers.rs b/src/api/repos/stargazers.rs index 36c4041e..772f3eeb 100644 --- a/src/api/repos/stargazers.rs +++ b/src/api/repos/stargazers.rs @@ -2,46 +2,49 @@ use super::*; #[derive(serde::Serialize)] pub struct ListStarGazersBuilder<'octo, 'r> { - #[serde(skip)] - handler: &'r RepoHandler<'octo>, - #[serde(skip_serializing_if = "Option::is_none")] - per_page: Option, - #[serde(skip_serializing_if = "Option::is_none")] - page: Option, + #[serde(skip)] + handler: &'r RepoHandler<'octo>, + #[serde(skip_serializing_if = "Option::is_none")] + per_page: Option, + #[serde(skip_serializing_if = "Option::is_none")] + page: Option, } impl<'octo, 'r> ListStarGazersBuilder<'octo, 'r> { - pub fn new(handler: &'r RepoHandler<'octo>) -> Self { - Self { - handler, - per_page: None, - page: None, + pub fn new(handler: &'r RepoHandler<'octo>) -> Self { + Self { + handler, + per_page: None, + page: None, + } } - } - /// Results per page (max 100). - pub fn per_page(mut self, per_page: impl Into) -> Self { - self.per_page = Some(per_page.into()); - self - } + /// Results per page (max 100). + pub fn per_page(mut self, per_page: impl Into) -> Self { + self.per_page = Some(per_page.into()); + self + } - /// Page number of the results to fetch. - pub fn page(mut self, page: impl Into) -> Self { - self.page = Some(page.into()); - self - } + /// Page number of the results to fetch. + pub fn page(mut self, page: impl Into) -> Self { + self.page = Some(page.into()); + self + } - /// Sends the actual request. - pub async fn send(self) -> crate::Result> { - let url = format!( - "repos/{owner}/{repo}/stargazers", - owner = self.handler.owner, - repo = self.handler.repo - ); + /// Sends the actual request. + pub async fn send(self) -> crate::Result> { + let url = format!( + "repos/{owner}/{repo}/stargazers", + owner = self.handler.owner, + repo = self.handler.repo + ); - let mut headers = reqwest::header::HeaderMap::new(); - headers.insert(ACCEPT, "application/vnd.github.star+json".parse().unwrap()); + let mut headers = http::header::HeaderMap::new(); + headers.insert(ACCEPT, "application/vnd.github.star+json".parse().unwrap()); - self.handler.crab.get_with_headers(url, Some(&self), Some(headers)).await - } + self.handler + .crab + .get_with_headers(url, Some(&self), Some(headers)) + .await + } } diff --git a/src/api/teams/team_repos.rs b/src/api/teams/team_repos.rs index 433ff8f5..37b81ad5 100644 --- a/src/api/teams/team_repos.rs +++ b/src/api/teams/team_repos.rs @@ -1,6 +1,6 @@ use crate::params; use crate::{models, FromResponse, Octocrab, Result}; -use reqwest::header::ACCEPT; +use http::header::ACCEPT; use reqwest::StatusCode; #[derive(Debug, serde::Serialize)] diff --git a/src/auth.rs b/src/auth.rs index f147f9ff..7e9694b7 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -128,7 +128,7 @@ impl crate::Octocrab { /// "ACCEPT: application/json". For example: /// ```no_run /// # async fn run() -> octocrab::Result<()> { - /// # use reqwest::header::ACCEPT; + /// # use http::header::ACCEPT; /// let crab = octocrab::Octocrab::builder() /// .base_url("https://github.com")? /// .add_header(ACCEPT, "application/json".to_string()) diff --git a/src/lib.rs b/src/lib.rs index f32f6343..8d591d7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -172,7 +172,7 @@ use models::{AppId, InstallationId, InstallationToken}; pub use self::{ api::{ actions, activity, apps, current, events, gists, gitignore, issues, licenses, markdown, - orgs, pulls, repos, search, teams, workflows, ratelimit, + orgs, pulls, ratelimit, repos, search, teams, workflows, }, error::{Error, GitHubError}, from_response::FromResponse, @@ -320,21 +320,21 @@ impl OctocrabBuilder { /// Create the `Octocrab` client. pub fn build(self) -> Result { - let mut hmap = reqwest::header::HeaderMap::new(); + let mut hmap = http::header::HeaderMap::new(); for preview in &self.previews { hmap.append( - reqwest::header::ACCEPT, + http::header::ACCEPT, crate::format_preview(&preview).parse().unwrap(), ); } let auth_state = match self.auth { Auth::None => AuthState::None, - Auth::Basic{ username, password } => AuthState::BasicAuth { username, password }, + Auth::Basic { username, password } => AuthState::BasicAuth { username, password }, Auth::PersonalToken(token) => { hmap.append( - reqwest::header::AUTHORIZATION, + http::header::AUTHORIZATION, (String::from("Bearer ") + token.expose_secret()) .parse() .unwrap(), @@ -344,7 +344,7 @@ impl OctocrabBuilder { Auth::App(app_auth) => AuthState::App(app_auth), Auth::OAuth(device) => { hmap.append( - reqwest::header::AUTHORIZATION, + http::header::AUTHORIZATION, (device.token_type + " " + &device.access_token.expose_secret()) .parse() .unwrap(), @@ -709,16 +709,23 @@ impl Octocrab { ) -> Result { self._get_with_headers(url, parameters, None).await } - + /// Send a `GET` request to `route` with optional query parameters and headers, returning /// the body of the response. - pub async fn get_with_headers(&self, route: A, parameters: Option<&P>, headers: Option) -> Result + pub async fn get_with_headers( + &self, + route: A, + parameters: Option<&P>, + headers: Option, + ) -> Result where A: AsRef, P: Serialize + ?Sized, R: FromResponse, { - let response = self._get_with_headers(self.absolute_url(route)?, parameters, headers).await?; + let response = self + ._get_with_headers(self.absolute_url(route)?, parameters, headers) + .await?; R::from_response(crate::map_github_error(response).await?).await } @@ -727,14 +734,14 @@ impl Octocrab { &self, url: impl reqwest::IntoUrl, parameters: Option<&P>, - headers: Option + headers: Option, ) -> Result { let mut request = self.client.get(url); if let Some(parameters) = parameters { request = request.query(parameters); } - + if let Some(headers) = headers { request = request.headers(headers) } @@ -742,7 +749,6 @@ impl Octocrab { self.execute(request).await } - /// Send a `PATCH` request to `route` with optional query parameters, /// returning the body of the response. pub async fn patch(&self, route: A, body: Option<&B>) -> Result @@ -897,7 +903,10 @@ impl Octocrab { retry_request = Some(request.try_clone().unwrap()); request = request.bearer_auth(app.generate_bearer_token()?); } - AuthState::BasicAuth { ref username, ref password } => { + AuthState::BasicAuth { + ref username, + ref password, + } => { retry_request = Some(request.try_clone().unwrap()); request = request.basic_auth(username, Some(password)); } @@ -1023,7 +1032,7 @@ mod tests { #[tokio::test] async fn extra_headers() { - use reqwest::header::HeaderName; + use http::header::HeaderName; use wiremock::{matchers, Mock, MockServer, ResponseTemplate}; let response = ResponseTemplate::new(304).append_header("etag", "\"abcd\""); let mock_server = MockServer::start().await; From 7e42011f452309d79f30092cbaa8153ed45bfbd0 Mon Sep 17 00:00:00 2001 From: Diptesh Date: Fri, 13 Jan 2023 19:02:46 +0530 Subject: [PATCH 4/8] refactor: replace `reqwest::Url` with `url::Url` --- src/models.rs | 38 ++++++++++++++--------------- src/models/events.rs | 4 +-- src/models/events/payload.rs | 2 +- src/models/events/payload/gollum.rs | 2 +- src/models/events/payload/push.rs | 2 +- 5 files changed, 23 insertions(+), 25 deletions(-) diff --git a/src/models.rs b/src/models.rs index 51d3d6a2..2b73667f 100644 --- a/src/models.rs +++ b/src/models.rs @@ -5,8 +5,8 @@ use std::fmt; use std::ops::{Deref, DerefMut}; use chrono::{DateTime, Utc}; -use reqwest::Url; use serde::{de, Deserialize, Deserializer, Serialize}; +use url::Url; pub mod activity; pub mod apps; @@ -544,21 +544,20 @@ pub struct Repository { #[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)] pub struct RepositoryFile { - pub name : Option, + pub name: Option, pub key: Option, - pub url : Option, - pub html_url : Option, + pub url: Option, + pub html_url: Option, } - #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct RepositoryMetrics { - pub health_percentage : u64, + pub health_percentage: u64, pub description: Option, - pub documentation : Option, + pub documentation: Option, pub files: HashMap>, pub updated_at: Option>, - pub content_reports_enabled: Option + pub content_reports_enabled: Option, } #[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)] @@ -770,29 +769,28 @@ pub struct PublicKey { pub key: String, } - #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct RateLimit { pub resources: Resources, - pub rate: Rate, + pub rate: Rate, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Resources { - pub core: Rate, - pub search: Rate, - pub graphql: Option, - pub integration_manifest: Option, - pub scim: Option, - pub source_import: Option, - pub code_scanning_upload: Option, + pub core: Rate, + pub search: Rate, + pub graphql: Option, + pub integration_manifest: Option, + pub scim: Option, + pub source_import: Option, + pub code_scanning_upload: Option, pub actions_runner_registration: Option, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Rate { - pub limit: usize, - pub used: usize, + pub limit: usize, + pub used: usize, pub remaining: usize, - pub reset: usize, + pub reset: usize, } diff --git a/src/models/events.rs b/src/models/events.rs index d092422a..ae97cd45 100644 --- a/src/models/events.rs +++ b/src/models/events.rs @@ -9,8 +9,8 @@ use self::payload::{ use super::{ActorId, OrgId, RepositoryId}; use chrono::{DateTime, Utc}; use payload::MemberEventPayload; -use reqwest::Url; use serde::{de::Error, Deserialize, Serialize}; +use url::Url; /// A GitHub event. #[derive(Debug, Clone, PartialEq, Serialize)] @@ -157,7 +157,7 @@ impl<'de> Deserialize<'de> for Event { #[cfg(test)] mod test { use super::{Event, EventPayload, EventType}; - use reqwest::Url; + use url::Url; #[test] fn should_deserialize_push_event() { diff --git a/src/models/events/payload.rs b/src/models/events/payload.rs index be322b4a..4f64e1e5 100644 --- a/src/models/events/payload.rs +++ b/src/models/events/payload.rs @@ -27,8 +27,8 @@ pub use pull_request_review_comment::*; pub use push::*; pub use workflow_run::*; -use reqwest::Url; use serde::{Deserialize, Serialize}; +use url::Url; /// The payload in an event type. /// diff --git a/src/models/events/payload/gollum.rs b/src/models/events/payload/gollum.rs index 5649cc20..800fd0ff 100644 --- a/src/models/events/payload/gollum.rs +++ b/src/models/events/payload/gollum.rs @@ -1,5 +1,5 @@ -use reqwest::Url; use serde::{Deserialize, Serialize}; +use url::Url; /// The payload in a [`super::EventPayload::GollumEvent`] type. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] diff --git a/src/models/events/payload/push.rs b/src/models/events/payload/push.rs index 1179547f..a1a3eaf5 100644 --- a/src/models/events/payload/push.rs +++ b/src/models/events/payload/push.rs @@ -22,7 +22,7 @@ mod test { events::{payload::EventPayload, Event}, repos::GitUser, }; - use reqwest::Url; + use url::Url; #[test] fn should_deserialize_push_event_with_correct_payload() { From abe701ba43d8fce8f0fe477327f900b7f3c9efc2 Mon Sep 17 00:00:00 2001 From: Diptesh Date: Fri, 13 Jan 2023 19:22:46 +0530 Subject: [PATCH 5/8] chore: replace remaining simples --- src/api/events.rs | 2 +- src/api/repos.rs | 2 +- src/api/teams/team_repos.rs | 3 +-- src/lib.rs | 3 ++- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/api/events.rs b/src/api/events.rs index 78de3253..d816b9c9 100644 --- a/src/api/events.rs +++ b/src/api/events.rs @@ -4,8 +4,8 @@ use crate::{ models::events, FromResponse, Octocrab, Page, }; +use http::{header::HeaderMap, Method, StatusCode}; use hyperx::header::{ETag, IfNoneMatch, TypedHeaders}; -use reqwest::{header::HeaderMap, Method, StatusCode}; pub struct EventsBuilder<'octo> { crab: &'octo Octocrab, diff --git a/src/api/repos.rs b/src/api/repos.rs index 274a1b90..de7f3975 100644 --- a/src/api/repos.rs +++ b/src/api/repos.rs @@ -485,7 +485,7 @@ impl<'octo> RepoHandler<'octo> { repo = self.repo, path = path.as_ref(), ))?; - let mut request = self.crab.request_builder(url, reqwest::Method::GET); + let mut request = self.crab.request_builder(url, http::Method::GET); request = request.query(&[("ref", &reference.into().0)]); request = request.header(ACCEPT, "application/vnd.github.v3.raw"); self.crab.execute(request).await diff --git a/src/api/teams/team_repos.rs b/src/api/teams/team_repos.rs index 37b81ad5..d385a864 100644 --- a/src/api/teams/team_repos.rs +++ b/src/api/teams/team_repos.rs @@ -1,7 +1,6 @@ use crate::params; use crate::{models, FromResponse, Octocrab, Result}; -use http::header::ACCEPT; -use reqwest::StatusCode; +use http::{header::ACCEPT, StatusCode}; #[derive(Debug, serde::Serialize)] struct PermissionUpdateBody { diff --git a/src/lib.rs b/src/lib.rs index 8d591d7d..a8f6ba20 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -160,11 +160,12 @@ pub mod params; use std::fmt; use std::sync::{Arc, RwLock}; +use http::{header::HeaderName, StatusCode}; use once_cell::sync::Lazy; -use reqwest::{header::HeaderName, StatusCode, Url}; use secrecy::{ExposeSecret, SecretString}; use serde::Serialize; use snafu::*; +use url::Url; use auth::{AppAuth, Auth}; use models::{AppId, InstallationId, InstallationToken}; From 11b3513b45aa56ba18446ae710b79abaf1eafdb0 Mon Sep 17 00:00:00 2001 From: Diptesh Date: Fri, 13 Jan 2023 22:25:30 +0530 Subject: [PATCH 6/8] refactor: replace all `reqwest::Url` with `url::Url` --- Cargo.toml | 1 + src/api/actions.rs | 9 ++++++++- src/api/issues.rs | 14 +++++++------- src/api/issues/create.rs | 2 +- src/api/orgs.rs | 4 ++-- src/api/pulls.rs | 2 +- src/api/repos.rs | 4 ++-- src/api/repos/forks.rs | 2 +- src/api/repos/releases.rs | 2 +- src/api/repos/status.rs | 2 +- src/api/teams/create.rs | 4 ++-- src/lib.rs | 31 +++++++++++++++---------------- 12 files changed, 42 insertions(+), 35 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4c75bce5..f12cdc08 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ secrecy = "0.8.0" cfg-if = "1.0.0" either = "1.8.0" http = "0.2.8" +hyper = "0.14.23" [dev-dependencies] tokio = { version = "1.17.0", default-features = false, features = [ diff --git a/src/api/actions.rs b/src/api/actions.rs index fd8426c8..ffa6a538 100644 --- a/src/api/actions.rs +++ b/src/api/actions.rs @@ -1,5 +1,7 @@ //! GitHub Actions use snafu::ResultExt; +use std::str::FromStr; +use url::Url; use crate::etag::{EntityTag, Etagged}; use crate::models::{ @@ -253,7 +255,12 @@ impl<'octo> ActionsHandler<'octo> { let data_response = if let Some(redirect) = response.headers().get(http::header::LOCATION) { let location = redirect.to_str().expect("Location URL not valid str"); - self.crab._get(location, None::<&()>).await? + self.crab + ._get( + Url::from_str(location).context(crate::error::UrlSnafu)?, + None::<&()>, + ) + .await? } else { response }; diff --git a/src/api/issues.rs b/src/api/issues.rs index 172c7ed2..6b8a4a49 100644 --- a/src/api/issues.rs +++ b/src/api/issues.rs @@ -218,7 +218,7 @@ impl<'octo> IssueHandler<'octo> { ); self.crab - .post(route, Some(&serde_json::json!({ "assignees": assignees }))) + .post(&route, Some(&serde_json::json!({ "assignees": assignees }))) .await } @@ -336,7 +336,7 @@ impl<'octo> IssueHandler<'octo> { ); self.crab - .post(route, Some(&serde_json::json!({ "labels": labels }))) + .post(&route, Some(&serde_json::json!({ "labels": labels }))) .await } @@ -417,7 +417,7 @@ impl<'octo> IssueHandler<'octo> { self.crab .post( - route, + &route, Some(&serde_json::json!({ "name": name.as_ref(), "color": color.as_ref(), @@ -531,7 +531,7 @@ impl<'octo> IssueHandler<'octo> { ); self.crab - .post(route, Some(&serde_json::json!({ "body": body.as_ref() }))) + .post(&route, Some(&serde_json::json!({ "body": body.as_ref() }))) .await } @@ -579,7 +579,7 @@ impl<'octo> IssueHandler<'octo> { ); self.crab - .post(route, Some(&serde_json::json!({ "body": body.as_ref() }))) + .post(&route, Some(&serde_json::json!({ "body": body.as_ref() }))) .await } @@ -926,7 +926,7 @@ impl<'octo> IssueHandler<'octo> { ); self.crab - .post(route, Some(&serde_json::json!({ "content": content }))) + .post(&route, Some(&serde_json::json!({ "content": content }))) .await } @@ -953,7 +953,7 @@ impl<'octo> IssueHandler<'octo> { ); self.crab - .post(route, Some(&serde_json::json!({ "content": content }))) + .post(&route, Some(&serde_json::json!({ "content": content }))) .await } } diff --git a/src/api/issues/create.rs b/src/api/issues/create.rs index b551d87c..ef83b3e5 100644 --- a/src/api/issues/create.rs +++ b/src/api/issues/create.rs @@ -35,7 +35,7 @@ impl<'octo, 'r> CreateIssueBuilder<'octo, 'r> { repo = self.handler.repo, ); - self.handler.crab.post(route, Some(&self)).await + self.handler.crab.post(&route, Some(&self)).await } /// The contents of the issue. diff --git a/src/api/orgs.rs b/src/api/orgs.rs index b11681f4..7ca7535f 100644 --- a/src/api/orgs.rs +++ b/src/api/orgs.rs @@ -55,7 +55,7 @@ impl<'octo> OrgHandler<'octo> { let body = role.map(|role| serde_json::json!({ "role": role })); - self.crab.post(url, body.as_ref()).await + self.crab.post(&url, body.as_ref()).await } /// Check if a user is, publicly or privately, a member of the organization. @@ -164,7 +164,7 @@ impl<'octo> OrgHandler<'octo> { let route = format!("orgs/{org}/hooks", org = self.owner); let res = self .crab - .post(self.crab.absolute_url(route)?, Some(&hook)) + .post(self.crab.absolute_url(route)?.as_str(), Some(&hook)) .await?; Ok(res) diff --git a/src/api/pulls.rs b/src/api/pulls.rs index 4178591f..50149595 100644 --- a/src/api/pulls.rs +++ b/src/api/pulls.rs @@ -288,7 +288,7 @@ impl<'octo> PullRequestHandler<'octo> { map.insert("reviewers".to_string(), reviewers.into().into()); map.insert("team_reviewers".to_string(), team_reviewers.into().into()); - self.crab.post(url, Some(&map)).await + self.crab.post(&url, Some(&map)).await } /// List all `FileDiff`s associated with the pull request. diff --git a/src/api/repos.rs b/src/api/repos.rs index de7f3975..42f4b4f9 100644 --- a/src/api/repos.rs +++ b/src/api/repos.rs @@ -180,7 +180,7 @@ impl<'octo> RepoHandler<'octo> { ); self.crab .post( - url, + &url, Some(&serde_json::json!({ "ref": reference.full_ref_url(), "sha": sha.into(), @@ -485,7 +485,7 @@ impl<'octo> RepoHandler<'octo> { repo = self.repo, path = path.as_ref(), ))?; - let mut request = self.crab.request_builder(url, http::Method::GET); + let mut request = self.crab.request_builder(url.as_str(), http::Method::GET); request = request.query(&[("ref", &reference.into().0)]); request = request.header(ACCEPT, "application/vnd.github.v3.raw"); self.crab.execute(request).await diff --git a/src/api/repos/forks.rs b/src/api/repos/forks.rs index cdd1d50a..a00a6d38 100644 --- a/src/api/repos/forks.rs +++ b/src/api/repos/forks.rs @@ -79,7 +79,7 @@ impl<'octo, 'r> CreateForkBuilder<'octo, 'r> { owner = self.handler.owner, repo = self.handler.repo ); - self.handler.crab.post(url, Some(&self)).await + self.handler.crab.post(&url, Some(&self)).await } } diff --git a/src/api/repos/releases.rs b/src/api/repos/releases.rs index 71145129..1ec4b041 100644 --- a/src/api/repos/releases.rs +++ b/src/api/repos/releases.rs @@ -360,7 +360,7 @@ impl<'octo, 'repos, 'handler, 'tag_name, 'target_commitish, 'name, 'body> owner = self.handler.parent.owner, repo = self.handler.parent.repo ); - self.handler.parent.crab.post(url, Some(&self)).await + self.handler.parent.crab.post(&url, Some(&self)).await } } diff --git a/src/api/repos/status.rs b/src/api/repos/status.rs index c16d532d..c91768b2 100644 --- a/src/api/repos/status.rs +++ b/src/api/repos/status.rs @@ -68,7 +68,7 @@ impl<'octo, 'r> CreateStatusBuilder<'octo, 'r> { repo = self.handler.repo, sha = self.sha ); - self.handler.crab.post(url, Some(&self)).await + self.handler.crab.post(&url, Some(&self)).await } } diff --git a/src/api/teams/create.rs b/src/api/teams/create.rs index 67f1eee0..2c466595 100644 --- a/src/api/teams/create.rs +++ b/src/api/teams/create.rs @@ -1,6 +1,6 @@ use super::*; -use crate::params; use crate::models::TeamId; +use crate::params; #[derive(serde::Serialize)] pub struct CreateTeamBuilder<'octo, 'h, 'a, 'b> { @@ -72,6 +72,6 @@ impl<'octo, 'h, 'a, 'b> CreateTeamBuilder<'octo, 'h, 'a, 'b> { /// Sends the actual request. pub async fn send(self) -> Result { let url = format!("orgs/{org}/teams", org = self.handler.owner,); - self.handler.crab.post(url, Some(&self)).await + self.handler.crab.post(&url, Some(&self)).await } } diff --git a/src/lib.rs b/src/lib.rs index a8f6ba20..8ceafdd9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -93,10 +93,12 @@ //! the request. //! //! ```no_run +//! # use std::str::FromStr; +//! # use url::Url; //! # async fn run() -> octocrab::Result<()> { //! let octocrab = octocrab::instance(); //! let response = octocrab -//! ._get("https://api.github.com/organizations", None::<&()>) +//! ._get(Url::from_str("https://api.github.com/organizations").unwrap(), None::<&()>) //! .await?; //! //! // You can also use `Octocrab::absolute_url` if you want to still to go to @@ -158,6 +160,7 @@ pub mod models; pub mod params; use std::fmt; +use std::str::FromStr; use std::sync::{Arc, RwLock}; use http::{header::HeaderName, StatusCode}; @@ -314,8 +317,8 @@ impl OctocrabBuilder { } /// Set the base url for `Octocrab`. - pub fn base_url(mut self, base_url: impl reqwest::IntoUrl) -> Result { - self.base_url = Some(base_url.into_url().context(crate::error::HttpSnafu)?); + pub fn base_url(mut self, base_url: &str) -> Result { + self.base_url = Some(Url::from_str(base_url).context(crate::error::UrlSnafu)?); Ok(self) } @@ -669,7 +672,7 @@ impl Octocrab { /// of the response. pub async fn post( &self, - route: impl AsRef, + route: &str, body: Option<&P>, ) -> Result { let response = self._post(self.absolute_url(route)?, body).await?; @@ -679,7 +682,7 @@ impl Octocrab { /// Send a `POST` request with no additional pre/post-processing. pub async fn _post( &self, - url: impl reqwest::IntoUrl, + url: Url, body: Option<&P>, ) -> Result { let mut request = self.client.post(url); @@ -705,7 +708,7 @@ impl Octocrab { /// Send a `GET` request with no additional post-processing. pub async fn _get( &self, - url: impl reqwest::IntoUrl, + url: Url, parameters: Option<&P>, ) -> Result { self._get_with_headers(url, parameters, None).await @@ -733,7 +736,7 @@ impl Octocrab { /// Send a `GET` request including option to set headers, with no additional post-processing. pub async fn _get_with_headers( &self, - url: impl reqwest::IntoUrl, + url: Url, parameters: Option<&P>, headers: Option, ) -> Result { @@ -765,7 +768,7 @@ impl Octocrab { /// Send a `PATCH` request with no additional post-processing. pub async fn _patch( &self, - url: impl reqwest::IntoUrl, + url: Url, parameters: Option<&B>, ) -> Result { let mut request = self.client.patch(url); @@ -792,7 +795,7 @@ impl Octocrab { /// Send a `PATCH` request with no additional post-processing. pub async fn _put( &self, - url: impl reqwest::IntoUrl, + url: Url, body: Option<&B>, ) -> Result { let mut request = self.client.put(url); @@ -819,7 +822,7 @@ impl Octocrab { /// Send a `DELETE` request with no additional post-processing. pub async fn _delete( &self, - url: impl reqwest::IntoUrl, + url: Url, parameters: Option<&P>, ) -> Result { let mut request = self.client.delete(url); @@ -844,11 +847,7 @@ impl Octocrab { /// # Ok(()) /// # } /// ``` - pub fn request_builder( - &self, - url: impl reqwest::IntoUrl, - method: reqwest::Method, - ) -> reqwest::RequestBuilder { + pub fn request_builder(&self, url: &str, method: reqwest::Method) -> reqwest::RequestBuilder { self.client.request(method, url) } @@ -1046,7 +1045,7 @@ mod tests { .mount(&mock_server) .await; crate::OctocrabBuilder::new() - .base_url(mock_server.uri()) + .base_url(mock_server.uri().as_str()) .unwrap() .add_header(HeaderName::from_static("x-test1"), "hello".to_string()) .add_header(HeaderName::from_static("x-test2"), "goodbye".to_string()) From 7f3556cf5922716518867a560a9a7657c1a33579 Mon Sep 17 00:00:00 2001 From: Diptesh Date: Fri, 13 Jan 2023 22:57:59 +0530 Subject: [PATCH 7/8] fix: replace `&str` with `impl AsRef` --- src/lib.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 8ceafdd9..eb53cbb5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -317,8 +317,8 @@ impl OctocrabBuilder { } /// Set the base url for `Octocrab`. - pub fn base_url(mut self, base_url: &str) -> Result { - self.base_url = Some(Url::from_str(base_url).context(crate::error::UrlSnafu)?); + pub fn base_url(mut self, base_url: impl AsRef) -> Result { + self.base_url = Some(Url::from_str(base_url.as_ref()).context(crate::error::UrlSnafu)?); Ok(self) } @@ -329,7 +329,7 @@ impl OctocrabBuilder { for preview in &self.previews { hmap.append( http::header::ACCEPT, - crate::format_preview(&preview).parse().unwrap(), + crate::format_preview(preview).parse().unwrap(), ); } @@ -672,7 +672,7 @@ impl Octocrab { /// of the response. pub async fn post( &self, - route: &str, + route: impl AsRef, body: Option<&P>, ) -> Result { let response = self._post(self.absolute_url(route)?, body).await?; @@ -847,7 +847,11 @@ impl Octocrab { /// # Ok(()) /// # } /// ``` - pub fn request_builder(&self, url: &str, method: reqwest::Method) -> reqwest::RequestBuilder { + pub fn request_builder( + &self, + url: impl AsRef, + method: reqwest::Method, + ) -> reqwest::RequestBuilder { self.client.request(method, url) } From 353edc82311eaacd314513006b8745d3f0997403 Mon Sep 17 00:00:00 2001 From: Diptesh Date: Sat, 14 Jan 2023 07:39:30 +0530 Subject: [PATCH 8/8] try: use `TryInto` instead of `AsRef` --- src/lib.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index eb53cbb5..b698b7c6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -159,8 +159,8 @@ pub mod etag; pub mod models; pub mod params; +use std::convert::TryInto; use std::fmt; -use std::str::FromStr; use std::sync::{Arc, RwLock}; use http::{header::HeaderName, StatusCode}; @@ -317,8 +317,9 @@ impl OctocrabBuilder { } /// Set the base url for `Octocrab`. - pub fn base_url(mut self, base_url: impl AsRef) -> Result { - self.base_url = Some(Url::from_str(base_url.as_ref()).context(crate::error::UrlSnafu)?); + pub fn base_url(mut self, base_url: impl TryInto) -> Result { + let url: Url = base_url.try_into().context(crate::error::UrlSnafu)?; + self.base_url = Some(url); Ok(self) }