Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Github specific code into own backend #38

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ serde_json = "1.0"
tokio = { version = "1.17", default-features = false, features = ["macros", "rt-multi-thread"] }
toml = "0.5"
xdg = "2.4"
async-trait = "0.1.74"

[dev-dependencies]
tempfile = "3.8.1"
122 changes: 122 additions & 0 deletions src/backend/github.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
use crate::backend::{Backend, ReviewInfo};
use crate::parser::FileComment;
use crate::prr::Config;
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use octocrab::Octocrab;
use reqwest::StatusCode;
use serde_json::{json, Value};

pub struct Github {
crab: Octocrab,
}

impl Github {
pub fn new(config: &Config) -> Result<Self> {
let crab = Octocrab::builder()
.personal_token(config.prr.token.clone())
.base_url(config.url())
.context("Failed to parse github base URL")?
.build()
.context("Failed to create GH client")?;

Ok(Github { crab })
}
}

#[async_trait]
impl Backend for Github {
async fn get_pr_info(&self, owner: &str, repo: &str, pr_num: u64) -> Result<ReviewInfo> {
let pr_handler = self.crab.pulls(owner, repo);

let diff = pr_handler
.get_diff(pr_num)
.await
.context("Failed to fetch diff")?;

let commit = pr_handler
.get(pr_num)
.await
.context("Failed to fetch commit ID")?
.head
.sha;

Ok(ReviewInfo { diff, commit })
}

async fn submit_review(
&self,
owner: &str,
repo: &str,
pr_num: u64,
body: &Value,
) -> Result<()> {
let path = format!("repos/{}/{}/pulls/{}/reviews", owner, repo, pr_num);
match self
.crab
._post(self.crab.absolute_url(path)?, Some(body))
.await
{
Ok(resp) => {
let status = resp.status();
if status != StatusCode::OK {
let text = resp
.text()
.await
.context("Failed to decode failed response")?;
bail!("Error during POST: Status code: {}, Body: {}", status, text);
}

Ok(())
}
// GH is known to send unescaped control characters in JSON responses which
// serde will fail to parse (not that it should succeed)
Err(octocrab::Error::Json {
source: _,
backtrace: _,
}) => bail!("Warning: GH response had invalid JSON"),
Err(e) => bail!("Error during POST: {}", e),
}
}

async fn submit_file_comment(
&self,
owner: &str,
repo: &str,
pr_num: u64,
commit_id: &str,
fc: &FileComment,
) -> Result<()> {
let body = json!({
"body": fc.comment,
"commit_id": commit_id,
"path": fc.file,
"subject_type": "file",
});
let path = format!("repos/{}/{}/pulls/{}/comments", owner, repo, pr_num);
match self
.crab
._post(self.crab.absolute_url(path)?, Some(&body))
.await
{
Ok(resp) => {
let status = resp.status();
if status != StatusCode::CREATED {
let text = resp
.text()
.await
.context("Failed to decode failed response")?;
bail!("Error during POST: Status code: {}, Body: {}", status, text);
}
Ok(())
}
// GH is known to send unescaped control characters in JSON responses which
// serde will fail to parse (not that it should succeed)
Err(octocrab::Error::Json {
source: _,
backtrace: _,
}) => bail!("Warning: GH response had invalid JSON"),
Err(e) => bail!("Error during POST: {}", e),
}
}
}
33 changes: 33 additions & 0 deletions src/backend/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use crate::parser::FileComment;
use crate::prr::Config;
use anyhow::Result;
use async_trait::async_trait;
use github::Github;
use serde_json::Value;

mod github;

pub struct ReviewInfo {
pub diff: String,
pub commit: String,
}

#[async_trait]
pub trait Backend {
async fn get_pr_info(&self, owner: &str, repo: &str, pr_num: u64) -> Result<ReviewInfo>;
async fn submit_review(&self, owner: &str, repo: &str, pr_num: u64, body: &Value)
-> Result<()>;

async fn submit_file_comment(
&self,
owner: &str,
repo: &str,
pr_num: u64,
commit_id: &str,
fc: &FileComment,
) -> Result<()>;
}

pub fn new_backend(config: &Config) -> Result<Box<dyn Backend>> {
Ok(Box::new(Github::new(config)?))
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::path::PathBuf;
use anyhow::Result;
use clap::{Parser, Subcommand};

mod backend;
mod parser;
mod prr;
mod review;
Expand Down
Loading