Browse Source

store shared data needed by handlers in a Context struct

Pietro Albini 6 năm trước cách đây
mục cha
commit
be2ac6e4de
4 tập tin đã thay đổi với 27 bổ sung24 xóa
  1. 7 6
      src/handlers.rs
  2. 8 11
      src/handlers/label.rs
  3. 6 4
      src/main.rs
  4. 6 3
      src/registry.rs

+ 7 - 6
src/handlers.rs

@@ -1,16 +1,17 @@
 use crate::github::GithubClient;
 use crate::registry::HandleRegistry;
-use std::sync::Arc;
 
 //mod assign;
 mod label;
 //mod tracking_issue;
 
-pub fn register_all(registry: &mut HandleRegistry, client: GithubClient, username: Arc<String>) {
-    registry.register(label::LabelHandler {
-        client: client.clone(),
-        username: username.clone(),
-    });
+pub struct Context {
+    pub github: GithubClient,
+    pub username: String,
+}
+
+pub fn register_all(registry: &mut HandleRegistry) {
+    registry.register(label::LabelHandler);
     //registry.register(assign::AssignmentHandler {
     //    client: client.clone(),
     //});

+ 8 - 11
src/handlers/label.rs

@@ -10,21 +10,18 @@
 
 use crate::{
     github::{self, Event, GithubClient},
+    handlers::Context,
     interactions::ErrorComment,
     registry::Handler,
 };
 use failure::Error;
 use parser::command::label::{LabelCommand, LabelDelta};
 use parser::command::{Command, Input};
-use std::sync::Arc;
 
-pub struct LabelHandler {
-    pub client: GithubClient,
-    pub username: Arc<String>,
-}
+pub struct LabelHandler;
 
 impl Handler for LabelHandler {
-    fn handle_event(&self, event: &Event) -> Result<(), Error> {
+    fn handle_event(&self, ctx: &Context, event: &Event) -> Result<(), Error> {
         #[allow(irrefutable_let_patterns)]
         let event = if let Event::IssueComment(e) = event {
             e
@@ -36,7 +33,7 @@ impl Handler for LabelHandler {
         let repo = &event.repository.full_name;
         let mut issue_labels = event.issue.labels().to_owned();
 
-        let mut input = Input::new(&event.comment.body, &self.username);
+        let mut input = Input::new(&event.comment.body, &ctx.username);
         let deltas = match input.parse_command() {
             Command::Label(Ok(LabelCommand(deltas))) => deltas,
             Command::Label(Err(err)) => {
@@ -47,7 +44,7 @@ impl Handler for LabelHandler {
                         event.comment.html_url, err
                     ),
                 )
-                .post(&self.client)?;
+                .post(&ctx.github)?;
                 failure::bail!(
                     "label parsing failed for issue #{}, error: {:?}",
                     event.issue.number,
@@ -60,8 +57,8 @@ impl Handler for LabelHandler {
         let mut changed = false;
         for delta in &deltas {
             let name = delta.label().as_str();
-            if let Err(msg) = check_filter(name, repo, &event.comment.user, &self.client) {
-                ErrorComment::new(&event.issue, msg.to_string()).post(&self.client)?;
+            if let Err(msg) = check_filter(name, repo, &event.comment.user, &ctx.github) {
+                ErrorComment::new(&event.issue, msg.to_string()).post(&ctx.github)?;
                 return Ok(());
             }
             match delta {
@@ -83,7 +80,7 @@ impl Handler for LabelHandler {
         }
 
         if changed {
-            event.issue.set_labels(&self.client, issue_labels)?;
+            event.issue.set_labels(&ctx.github, issue_labels)?;
         }
 
         Ok(())

+ 6 - 4
src/main.rs

@@ -10,7 +10,6 @@ use rocket::request;
 use rocket::State;
 use rocket::{http::Status, Outcome, Request};
 use std::env;
-use std::sync::Arc;
 
 mod handlers;
 mod registry;
@@ -99,9 +98,12 @@ fn main() {
         client.clone(),
         env::var("GITHUB_API_TOKEN").expect("Missing GITHUB_API_TOKEN"),
     );
-    let username = Arc::new(github::User::current(&gh).unwrap().login);
-    let mut registry = HandleRegistry::new();
-    handlers::register_all(&mut registry, gh.clone(), username);
+    let ctx = handlers::Context {
+        github: gh.clone(),
+        username: github::User::current(&gh).unwrap().login,
+    };
+    let mut registry = HandleRegistry::new(ctx);
+    handlers::register_all(&mut registry);
 
     let mut config = rocket::Config::active().unwrap();
     config.set_port(

+ 6 - 3
src/registry.rs

@@ -1,14 +1,17 @@
 use crate::github::Event;
+use crate::handlers::Context;
 use failure::Error;
 
 pub struct HandleRegistry {
     handlers: Vec<Box<dyn Handler>>,
+    ctx: Context,
 }
 
 impl HandleRegistry {
-    pub fn new() -> HandleRegistry {
+    pub fn new(ctx: Context) -> HandleRegistry {
         HandleRegistry {
             handlers: Vec::new(),
+            ctx,
         }
     }
 
@@ -19,7 +22,7 @@ impl HandleRegistry {
     pub fn handle(&self, event: &Event) -> Result<(), Error> {
         let mut last_error = None;
         for h in &self.handlers {
-            match h.handle_event(event) {
+            match h.handle_event(&self.ctx, event) {
                 Ok(()) => {}
                 Err(e) => {
                     eprintln!("event handling failed: {:?}", e);
@@ -36,5 +39,5 @@ impl HandleRegistry {
 }
 
 pub trait Handler: Sync + Send {
-    fn handle_event(&self, event: &Event) -> Result<(), Error>;
+    fn handle_event(&self, ctx: &Context, event: &Event) -> Result<(), Error>;
 }