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

Add per-repo config and prepare for org-wide webhook #9

Merged
merged 6 commits into from
Apr 16, 2019
Merged
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
17 changes: 17 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ hex = "0.3.2"
env_logger = "0.6"
parser = { path = "parser" }
rust_team_data = { git = "https://github.com/rust-lang/team" }
glob = "0.3.0"
toml = "0.5.0"

[dependencies.serde]
version = "1"
Expand Down
12 changes: 6 additions & 6 deletions parser/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ use crate::code_block::ColorCodeBlocks;
use crate::error::Error;
use crate::token::{Token, Tokenizer};

pub mod label;
pub mod relabel;

pub fn find_commmand_start(input: &str, bot: &str) -> Option<usize> {
input.find(&format!("@{}", bot))
}

#[derive(Debug)]
pub enum Command<'a> {
Label(Result<label::LabelCommand, Error<'a>>),
Relabel(Result<relabel::RelabelCommand, Error<'a>>),
None,
}

Expand Down Expand Up @@ -50,14 +50,14 @@ impl<'a> Input<'a> {

{
let mut tok = original_tokenizer.clone();
let res = label::LabelCommand::parse(&mut tok);
let res = relabel::RelabelCommand::parse(&mut tok);
match res {
Ok(None) => {}
Ok(Some(cmd)) => {
success.push((tok, Command::Label(Ok(cmd))));
success.push((tok, Command::Relabel(Ok(cmd))));
}
Err(err) => {
success.push((tok, Command::Label(Err(err))));
success.push((tok, Command::Relabel(Err(err))));
}
}
}
Expand Down Expand Up @@ -94,7 +94,7 @@ impl<'a> Input<'a> {
impl<'a> Command<'a> {
pub fn is_ok(&self) -> bool {
match self {
Command::Label(r) => r.is_ok(),
Command::Relabel(r) => r.is_ok(),
Command::None => true,
}
}
Expand Down
8 changes: 4 additions & 4 deletions parser/src/command/label.rs → parser/src/command/relabel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use std::error::Error as _;
use std::fmt;

#[derive(Debug)]
pub struct LabelCommand(pub Vec<LabelDelta>);
pub struct RelabelCommand(pub Vec<LabelDelta>);

#[derive(Debug, PartialEq, Eq)]
pub enum LabelDelta {
Expand Down Expand Up @@ -124,7 +124,7 @@ fn delta_empty() {
assert_eq!(err.position(), 1);
}

impl LabelCommand {
impl RelabelCommand {
pub fn parse<'a>(input: &mut Tokenizer<'a>) -> Result<Option<Self>, Error<'a>> {
let mut toks = input.clone();
if let Some(Token::Word("modify")) = toks.next_token()? {
Expand Down Expand Up @@ -163,7 +163,7 @@ impl LabelCommand {
if let Some(Token::Dot) | Some(Token::EndOfLine) = toks.peek_token()? {
toks.next_token()?;
*input = toks;
return Ok(Some(LabelCommand(deltas)));
return Ok(Some(RelabelCommand(deltas)));
}
}
}
Expand All @@ -172,7 +172,7 @@ impl LabelCommand {
#[cfg(test)]
fn parse<'a>(input: &'a str) -> Result<Option<Vec<LabelDelta>>, Error<'a>> {
let mut toks = Tokenizer::new(input);
Ok(LabelCommand::parse(&mut toks)?.map(|c| c.0))
Ok(RelabelCommand::parse(&mut toks)?.map(|c| c.0))
}

#[test]
Expand Down
61 changes: 61 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use crate::github::GithubClient;
use failure::Error;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

static CONFIG_FILE_NAME: &str = "triagebot.toml";
const REFRESH_EVERY: Duration = Duration::from_secs(2 * 60); // Every two minutes

lazy_static::lazy_static! {
static ref CONFIG_CACHE: RwLock<HashMap<String, (Arc<Config>, Instant)>> =
RwLock::new(HashMap::new());
}

#[derive(serde::Deserialize)]
pub(crate) struct Config {
pub(crate) relabel: Option<RelabelConfig>,
}

#[derive(serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) struct RelabelConfig {
#[serde(default)]
pub(crate) allow_unauthenticated: Vec<String>,
}

pub(crate) fn get(gh: &GithubClient, repo: &str) -> Result<Arc<Config>, Error> {
if let Some(config) = get_cached_config(repo) {
Ok(config)
} else {
get_fresh_config(gh, repo)
}
}

fn get_cached_config(repo: &str) -> Option<Arc<Config>> {
let cache = CONFIG_CACHE.read().unwrap();
cache.get(repo).and_then(|(config, fetch_time)| {
if fetch_time.elapsed() < REFRESH_EVERY {
Some(config.clone())
} else {
None
}
})
}

fn get_fresh_config(gh: &GithubClient, repo: &str) -> Result<Arc<Config>, Error> {
let contents = gh
.raw_file(repo, "master", CONFIG_FILE_NAME)?
.ok_or_else(|| {
failure::err_msg(
"This repository is not enabled to use triagebot.\n\
Add a `triagebot.toml` in the root of the master branch to enable it.",
)
})?;
let config = Arc::new(toml::from_slice::<Config>(&contents)?);
CONFIG_CACHE
.write()
.unwrap()
.insert(repo.to_string(), (config.clone(), Instant::now()));
Ok(config)
}
60 changes: 59 additions & 1 deletion src/github.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use failure::{Error, ResultExt};
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use reqwest::{Client, Error as HttpError, RequestBuilder, Response};
use reqwest::{Client, Error as HttpError, RequestBuilder, Response, StatusCode};
use std::io::Read;

#[derive(Debug, serde::Deserialize)]
pub struct User {
Expand Down Expand Up @@ -149,6 +150,46 @@ impl Issue {
}
}

#[derive(PartialEq, Eq, Debug, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum IssueCommentAction {
Created,
Edited,
Deleted,
}

#[derive(Debug, serde::Deserialize)]
pub struct IssueCommentEvent {
pub action: IssueCommentAction,
pub issue: Issue,
pub comment: Comment,
pub repository: Repository,
}

#[derive(Debug, serde::Deserialize)]
pub struct Repository {
pub full_name: String,
}

#[derive(Debug)]
pub enum Event {
IssueComment(IssueCommentEvent),
}

impl Event {
pub fn repo_name(&self) -> &str {
match self {
Event::IssueComment(event) => &event.repository.full_name,
}
}

pub fn issue(&self) -> Option<&Issue> {
match self {
Event::IssueComment(event) => Some(&event.issue),
}
}
}

trait RequestSend: Sized {
fn configure(self, g: &GithubClient) -> Self;
fn send_req(self) -> Result<Response, HttpError>;
Expand Down Expand Up @@ -183,6 +224,23 @@ impl GithubClient {
&self.client
}

pub fn raw_file(&self, repo: &str, branch: &str, path: &str) -> Result<Option<Vec<u8>>, Error> {
let url = format!(
"https://raw.githubusercontent.com/{}/{}/{}",
repo, branch, path
);
let mut resp = self.get(&url).send()?;
match resp.status() {
StatusCode::OK => {
let mut buf = Vec::with_capacity(resp.content_length().unwrap_or(4) as usize);
resp.read_to_end(&mut buf)?;
Ok(Some(buf))
}
StatusCode::NOT_FOUND => Ok(None),
status => failure::bail!("failed to GET {}: {}", url, status),
}
}

fn get(&self, url: &str) -> RequestBuilder {
log::trace!("get {:?}", url);
self.client.get(url).configure(self)
Expand Down
65 changes: 48 additions & 17 deletions src/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,51 @@
use crate::github::GithubClient;
use crate::registry::HandleRegistry;
use std::sync::Arc;
use crate::github::{Event, GithubClient};
use failure::Error;

//mod assign;
mod label;
//mod tracking_issue;
macro_rules! handlers {
($($name:ident = $handler:expr,)*) => {
$(mod $name;)*

pub fn register_all(registry: &mut HandleRegistry, client: GithubClient, username: Arc<String>) {
registry.register(label::LabelHandler {
client: client.clone(),
username: username.clone(),
});
//registry.register(assign::AssignmentHandler {
// client: client.clone(),
//});
//registry.register(tracking_issue::TrackingIssueHandler {
// client: client.clone(),
//});
pub fn handle(ctx: &Context, event: &Event) -> Result<(), Error> {
$(if let Some(input) = Handler::parse_input(&$handler, ctx, event)? {
let config = crate::config::get(&ctx.github, event.repo_name())?;
if let Some(config) = &config.$name {
Handler::handle_input(&$handler, ctx, config, event, input)?;
} else {
failure::bail!(
"The feature `{}` is not enabled in this repository.\n\
To enable it add its section in the `triagebot.toml` \
in the root of the repository.",
stringify!($name)
);
}
})*
Ok(())
}
}
}

handlers! {
//assign = assign::AssignmentHandler,
relabel = relabel::RelabelHandler,
//tracking_issue = tracking_issue::TrackingIssueHandler,
}

pub struct Context {
pub github: GithubClient,
pub username: String,
}

pub trait Handler: Sync + Send {
type Input;
type Config;

fn parse_input(&self, ctx: &Context, event: &Event) -> Result<Option<Self::Input>, Error>;

fn handle_input(
&self,
ctx: &Context,
config: &Self::Config,
event: &Event,
input: Self::Input,
) -> Result<(), Error>;
}
Loading