Integrate OpenRouter for AI-powered code review
Add openrouter-rs dependency, review prompt, and markdown formatting. Update comment API to accept dynamic body. Adjust devcontainer for podman compatibility.
This commit is contained in:
+135
-6
@@ -1,22 +1,81 @@
|
||||
use std::time::Duration;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{
|
||||
consts::{BOT_PROCESS_MSG, REVIEW_PROMPT},
|
||||
env::EnvConfig,
|
||||
errors::AppError,
|
||||
gitea::{GiteaAPI, ReviewPayload, WebhookType},
|
||||
open_router::OpenRouterClient,
|
||||
};
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct ReviewResult {
|
||||
reviews: Vec<ReviewItem>,
|
||||
comment: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct ReviewItem {
|
||||
filename: String,
|
||||
line: Option<u64>,
|
||||
code: String,
|
||||
message: String,
|
||||
}
|
||||
|
||||
/// Map a filename to a markdown language identifier for syntax highlighting.
|
||||
fn lang_from_filename(filename: &str) -> &str {
|
||||
match std::path::Path::new(filename)
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or("")
|
||||
{
|
||||
"rs" => "rust",
|
||||
"py" => "python",
|
||||
"js" | "mjs" => "javascript",
|
||||
"ts" => "typescript",
|
||||
"jsx" => "jsx",
|
||||
"tsx" => "tsx",
|
||||
"go" => "go",
|
||||
"java" => "java",
|
||||
"kt" | "kts" => "kotlin",
|
||||
"scala" => "scala",
|
||||
"c" | "h" => "c",
|
||||
"cpp" | "cc" | "cxx" | "hpp" | "hxx" => "cpp",
|
||||
"rb" => "ruby",
|
||||
"php" => "php",
|
||||
"swift" => "swift",
|
||||
"sh" | "bash" | "zsh" => "bash",
|
||||
"sql" => "sql",
|
||||
"html" | "htm" => "html",
|
||||
"css" => "css",
|
||||
"scss" | "sass" => "scss",
|
||||
"json" => "json",
|
||||
"yaml" | "yml" => "yaml",
|
||||
"xml" => "xml",
|
||||
"toml" => "toml",
|
||||
"md" | "mdx" => "markdown",
|
||||
"dockerfile" | "Dockerfile" => "dockerfile",
|
||||
"Makefile" => "makefile",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Bot {
|
||||
config: EnvConfig,
|
||||
gitea_api: GiteaAPI,
|
||||
open_router_client: OpenRouterClient,
|
||||
}
|
||||
|
||||
impl Bot {
|
||||
pub fn new(config: EnvConfig) -> Self {
|
||||
Self {
|
||||
pub fn new(config: EnvConfig) -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
gitea_api: GiteaAPI::new(&config.gitea_url, &config.gitea_token),
|
||||
open_router_client: OpenRouterClient::new(
|
||||
&config.open_router_api_key,
|
||||
&config.open_router_model,
|
||||
)?,
|
||||
config,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn start(
|
||||
@@ -46,17 +105,87 @@ impl Bot {
|
||||
let new_comment = self
|
||||
.gitea_api
|
||||
.comment(
|
||||
&BOT_PROCESS_MSG.replace("{model}", &self.config.open_router_model),
|
||||
&review_payload.repository.full_name,
|
||||
review_payload.pull_request.number,
|
||||
)
|
||||
.await?;
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
let bot_result: Result<String, anyhow::Error> = async {
|
||||
let git_diff = self
|
||||
.download_git_diff(&review_payload.pull_request.diff_url)
|
||||
.await?;
|
||||
|
||||
let bot_request = &&REVIEW_PROMPT
|
||||
.replace("{subject}", &review_payload.pull_request.title)
|
||||
.replace("{comment}", &review_payload.comment.body)
|
||||
.replace("{diff}", &git_diff);
|
||||
|
||||
self.open_router_client.chat(&bot_request).await
|
||||
}
|
||||
.await;
|
||||
|
||||
let edit_msg = match bot_result {
|
||||
Ok(bot_result) => self.review_result_to_markdown(&bot_result),
|
||||
Err(e) => format!("Error while reviewing: {}", e),
|
||||
};
|
||||
|
||||
self.gitea_api
|
||||
.edit_comment(&review_payload.repository.full_name, new_comment.id)
|
||||
.edit_comment(
|
||||
&edit_msg,
|
||||
&review_payload.repository.full_name,
|
||||
new_comment.id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn review_result_to_markdown(&self, result: &str) -> String {
|
||||
let review_result: ReviewResult = match serde_json::from_str(result) {
|
||||
Ok(review_result) => review_result,
|
||||
Err(_) => {
|
||||
return format!(
|
||||
"Failed to parse review result. Raw output:\n\n```json\n{}\n```",
|
||||
result
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if review_result.reviews.is_empty() {
|
||||
return String::from("No issues found. ✅");
|
||||
}
|
||||
|
||||
let mut md = String::from("## Review Feedback\n\n");
|
||||
for (i, item) in review_result.reviews.iter().enumerate() {
|
||||
if i > 0 {
|
||||
md.push_str("\n---\n\n");
|
||||
}
|
||||
md.push_str(&format!("### `{}`\n\n", item.filename));
|
||||
if let Some(line) = item.line {
|
||||
md.push_str(&format!("> **Line {}**\n\n", line));
|
||||
}
|
||||
if !item.code.is_empty() {
|
||||
let lang = lang_from_filename(&item.filename);
|
||||
md.push_str(&format!("```{}\n{}\n```\n\n", lang, item.code));
|
||||
}
|
||||
md.push_str(&item.message);
|
||||
md.push('\n');
|
||||
}
|
||||
|
||||
if !review_result.comment.is_empty() {
|
||||
md.push_str("\n---\n\n");
|
||||
md.push_str("### Summary\n\n");
|
||||
md.push_str(&review_result.comment);
|
||||
md.push('\n');
|
||||
}
|
||||
|
||||
md
|
||||
}
|
||||
|
||||
async fn download_git_diff(&self, url: &str) -> anyhow::Result<String> {
|
||||
let response = reqwest::get(url).await?;
|
||||
let body = response.text().await?;
|
||||
Ok(body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,36 @@
|
||||
pub const GITEA_SIG_HEADER_NAME: &str = "x-gitea-signature";
|
||||
pub const GITEA_EVENT_TYPE_HEADER_NAME: &str = "x-gitea-event-type";
|
||||
pub const MAX_WEBHOOK_BODY_SIZE: usize = 1024 * 1024; // 1 MiB
|
||||
|
||||
pub const BOT_PROCESS_MSG: &str = "
|
||||
Review in progress with the model \"{model}\"...
|
||||
";
|
||||
|
||||
pub const REVIEW_PROMPT: &str = "
|
||||
You are a senior software engineer reviewing code changes.
|
||||
|
||||
Check good practices and code quality.
|
||||
|
||||
This is the pull request subject: \"{subject}\"
|
||||
|
||||
This is the user comment: \"{comment}\"
|
||||
|
||||
This is the git diff of the code changes:
|
||||
|
||||
\"{diff}\"
|
||||
|
||||
Please review the code changes and provide feedback.
|
||||
Return your feedback with only this json format, reviews must contain each review (filename field must contain the full path with extension) and comment msut contain a final summary:
|
||||
|
||||
{
|
||||
\"reviews\": [
|
||||
{
|
||||
\"filename\": \"\",
|
||||
\"line\": ,
|
||||
\"code\": \"\",
|
||||
\"message\": \"\"
|
||||
}
|
||||
],
|
||||
\"comment\": \"\"
|
||||
}
|
||||
";
|
||||
|
||||
@@ -6,6 +6,7 @@ pub struct EnvConfig {
|
||||
pub http_port: u16,
|
||||
pub webhook_secret: String,
|
||||
pub open_router_api_key: String,
|
||||
pub open_router_model: String,
|
||||
pub bot_name: String,
|
||||
pub gitea_url: String,
|
||||
pub gitea_token: String,
|
||||
@@ -18,6 +19,7 @@ pub fn load_config() -> anyhow::Result<EnvConfig> {
|
||||
let bot_name = try_get_env("BOT_NAME")?;
|
||||
let webhook_secret = try_get_env("WEBHOOK_SIG_HEADER_SECRET")?;
|
||||
let open_router_api_key = try_get_env("OPEN_ROUTER_API_KEY")?;
|
||||
let open_router_model = try_get_env("OPEN_ROUTER_MODEL")?;
|
||||
let gitea_url = try_get_env("GITEA_URL")?;
|
||||
let gitea_token = try_get_env("GITEA_TOKEN")?;
|
||||
|
||||
@@ -26,6 +28,7 @@ pub fn load_config() -> anyhow::Result<EnvConfig> {
|
||||
webhook_secret,
|
||||
bot_name,
|
||||
open_router_api_key,
|
||||
open_router_model,
|
||||
gitea_url,
|
||||
gitea_token,
|
||||
})
|
||||
|
||||
+15
-8
@@ -16,7 +16,12 @@ impl GiteaAPI {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn comment(&self, full_name: &str, index: u64) -> anyhow::Result<Comment> {
|
||||
pub async fn comment(
|
||||
&self,
|
||||
body: &str,
|
||||
full_name: &str,
|
||||
index: u64,
|
||||
) -> anyhow::Result<Comment> {
|
||||
let url = format!(
|
||||
"{}/api/v1/repos/{}/issues/{}/comments?access_token={}",
|
||||
self.base_url, full_name, index, self.token
|
||||
@@ -26,17 +31,20 @@ impl GiteaAPI {
|
||||
let res = client
|
||||
.post(url)
|
||||
.json(&json!({
|
||||
"body": "Hello world :)"
|
||||
"body": body
|
||||
}))
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
println!("{}", res.status());
|
||||
|
||||
res.json::<Comment>().await.map_err(anyhow::Error::from)
|
||||
}
|
||||
|
||||
pub async fn edit_comment(&self, full_name: &str, comment_id: u64) -> anyhow::Result<()> {
|
||||
pub async fn edit_comment(
|
||||
&self,
|
||||
body: &str,
|
||||
full_name: &str,
|
||||
comment_id: u64,
|
||||
) -> anyhow::Result<()> {
|
||||
let url = format!(
|
||||
"{}/api/v1/repos/{}/issues/comments/{}?access_token={}",
|
||||
self.base_url, full_name, comment_id, self.token
|
||||
@@ -46,13 +54,11 @@ impl GiteaAPI {
|
||||
let res = client
|
||||
.patch(url)
|
||||
.json(&json!({
|
||||
"body": "Updated Hello world :)"
|
||||
"body": body
|
||||
}))
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
println!("{}", res.status());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -75,6 +81,7 @@ pub struct PullRequest {
|
||||
pub id: u64,
|
||||
pub diff_url: String,
|
||||
pub number: u64,
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
|
||||
+4
-6
@@ -6,21 +6,19 @@ mod consts;
|
||||
mod env;
|
||||
mod errors;
|
||||
mod gitea;
|
||||
mod open_router;
|
||||
mod state;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let config = env::load_config()?;
|
||||
let bot = Bot::new(config.clone());
|
||||
let bot = Bot::new(config.clone())?;
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::channel::<WebhookType>(1);
|
||||
|
||||
let app_state = AppState {
|
||||
bot_tx: tx,
|
||||
config,
|
||||
};
|
||||
let app_state = AppState { bot_tx: tx, config };
|
||||
|
||||
tokio::try_join!(bot.start(rx), api::start(app_state))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
use openrouter_rs::{Message, api::chat::ChatCompletionRequest};
|
||||
|
||||
pub struct OpenRouterClient {
|
||||
client: openrouter_rs::OpenRouterClient,
|
||||
model: String,
|
||||
}
|
||||
|
||||
impl OpenRouterClient {
|
||||
pub fn new(token: &str, model: &str) -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
client: openrouter_rs::OpenRouterClient::builder()
|
||||
.api_key(token)
|
||||
.build()?,
|
||||
model: String::from(model),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn chat(&self, msg: &str) -> anyhow::Result<String> {
|
||||
let request = ChatCompletionRequest::builder()
|
||||
.model(&self.model)
|
||||
.messages(vec![Message::new(
|
||||
openrouter_rs::types::Role::Developer,
|
||||
msg,
|
||||
)])
|
||||
.build()?;
|
||||
|
||||
let response = self.client.chat().create(&request).await?;
|
||||
|
||||
response.choices[0]
|
||||
.content()
|
||||
.map(|msg| String::from(msg))
|
||||
.ok_or(anyhow::anyhow!("No content"))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user