Skip to content

Commit

Permalink
issue-45: improve logs (#46)
Browse files Browse the repository at this point in the history
* issue-45: improve logs

* issue-45: refactor client
  • Loading branch information
lowitea authored Jan 18, 2023
1 parent 07e4964 commit 8b18638
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 62 deletions.
13 changes: 5 additions & 8 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,16 @@ async fn git<S: AsRef<OsStr>>(args: Vec<S>) -> Result<String> {

let cmd = Command::new("git").args(args).output().await?;

let errmsg = if !cmd.stderr.is_empty() {
let err = from_utf8(&cmd.stderr)?;
warn!(err);
err
} else {
""
};

let errmsg = from_utf8(&cmd.stderr).unwrap_or_default();
if !cmd.status.success() {
warn!("git exit status not success");
bail!("git error: {}", errmsg);
}

if !errmsg.is_empty() {
info!("{}", errmsg);
}

Ok(from_utf8(&cmd.stdout)?.to_string())
}

Expand Down
126 changes: 72 additions & 54 deletions src/gitlab/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use anyhow::Result;
use chrono::Utc;
use reqwest::{Method, RequestBuilder, Response};
use serde::Serialize;
use tracing::info;
use url::Url;

const API_VERSION: &str = "v4";
Expand All @@ -11,6 +12,8 @@ pub struct Client {
url: Url,
http: reqwest::Client,
disable_sync_date: bool,
token: String,
limit: u32,
}

impl Client {
Expand All @@ -21,35 +24,65 @@ impl Client {
disable_sync_date: bool,
) -> Result<Self> {
let http = reqwest::Client::new();
let opp = if let Some(opp) = opp { opp } else { 1000 };
let limit = if let Some(opp) = opp { opp } else { 1000 };
let token = token.to_string();

let query = format!("access_token={}&per_page={}", token, opp);
url.set_path(&format!("api/{}", API_VERSION));
url.set_query(Some(&query));

Ok(Client {
url,
http,
disable_sync_date,
token,
limit,
})
}

fn build_request<S: Into<String>>(&self, m: Method, path: S) -> RequestBuilder {
fn build_request<S: Into<String>, J: Serialize>(
&self,
m: Method,
path: S,
query: Option<String>,
json: Option<J>,
) -> RequestBuilder {
let mut url = self.url.clone();
url.set_path(&format!("{}/{}", url.path(), path.into()));
// TODO: add url to verbose logs with info level
self.http

if let Some(query) = query {
url.set_query(Some(&query));
}

info!("{}", url);

let mut req = self
.http
.request(m, url)
.header("Content-Type", "application/json")
.header("PRIVATE-TOKEN", &self.token);

if let Some(json) = json {
req = req.json(&json)
}

req
}

async fn request<S: Into<String>>(&self, m: Method, path: S) -> reqwest::Result<Response> {
self.build_request(m, path).send().await?.error_for_status()
async fn request<S: Into<String>, J: Serialize>(
&self,
m: Method,
path: S,
query: Option<String>,
json: Option<J>,
) -> reqwest::Result<Response> {
self.build_request(m, path, query, json)
.send()
.await?
.error_for_status()
}

pub async fn get_project(&self, path: String) -> reqwest::Result<types::Project> {
let path = urlencoding::encode(&path);
self.request(Method::GET, format!("projects/{}", path))
self.request(Method::GET, format!("projects/{}", path), None, None::<()>)
.await?
.json::<types::Project>()
.await
Expand Down Expand Up @@ -82,27 +115,16 @@ impl Client {
let mut next_page = 1;

loop {
let mut url = self.url.clone();
url.set_path(&format!("{}/{}", url.path(), "projects"));

let mut query = url.query().expect("query is empty").to_string();
query += format!("&page={}", next_page).as_str();
let mut query = format!("per_page={}&page={}", &self.limit, next_page);
if only_owned {
query += "&owned=true"
}
if only_membership {
query += "&only_membership=true"
}
url.set_query(Some(&query));

let resp = self
.http
.request(Method::GET, url)
.header("Content-Type", "application/json")
.send()
.await?
.error_for_status()?;

.request(Method::GET, "projects", Some(query), None::<()>)
.await?;
let headers = resp.headers().clone();

projects.append(&mut resp.json::<Vec<types::Project>>().await?);
Expand Down Expand Up @@ -150,16 +172,14 @@ impl Client {
let namespace_id = group_id;
let description = self.make_project_description(info.description.clone());

self.build_request(Method::POST, "projects")
.json(&MakeProjectRequest {
name,
description,
path,
namespace_id,
})
.send()
let data = &MakeProjectRequest {
name,
description,
path,
namespace_id,
};
self.request(Method::POST, "projects", None, Some(data))
.await?
.error_for_status()?
.json::<types::Project>()
.await
}
Expand All @@ -175,19 +195,22 @@ impl Client {
}

let description = self.make_project_description(info.description.clone());

self.build_request(Method::PUT, format!("projects/{}", project.id))
.json(&UpdateProjectRequest { description })
.send()
.await?
.error_for_status()?
.json::<types::Project>()
.await
let data = &UpdateProjectRequest { description };

self.request(
Method::PUT,
format!("projects/{}", project.id),
None,
Some(data),
)
.await?
.json::<types::Project>()
.await
}

pub async fn get_group(&self, path: String) -> reqwest::Result<types::Group> {
let path = urlencoding::encode(&path);
self.request(Method::GET, format!("groups/{}", path))
self.request(Method::GET, format!("groups/{}", path), None, None::<()>)
.await?
.json::<types::Group>()
.await
Expand All @@ -210,16 +233,14 @@ impl Client {
}

let path = name.clone();
let data = &MakeGroupRequest {
name,
path,
parent_id,
};

self.build_request(Method::POST, "groups")
.json(&MakeGroupRequest {
name,
path,
parent_id,
})
.send()
self.request(Method::POST, "groups", None, Some(data))
.await?
.error_for_status()?
.json::<types::Group>()
.await
}
Expand All @@ -231,10 +252,7 @@ impl Client {
project_info: &types::Project,
) -> reqwest::Result<types::Project> {
let mut parent_id = root_group.as_ref().map(|gr| gr.id);

// TODO: remove unwrap
let project_name = path.pop().unwrap();

let project_name = path.pop().expect("invalid project path");
let mut current_namespace = root_group
.as_ref()
.map(|gr| gr.full_path.clone())
Expand Down Expand Up @@ -277,7 +295,7 @@ impl Client {
}

pub async fn get_current_user(&self) -> reqwest::Result<types::User> {
self.request(Method::GET, "user")
self.request(Method::GET, "user", None, None::<()>)
.await?
.json::<types::User>()
.await
Expand Down

0 comments on commit 8b18638

Please sign in to comment.