use clap::{Args, Parser, Subcommand};
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::time::{sleep, timeout_at, Instant};
use tokio_tungstenite::tungstenite::Message;
const NOW: u64 = 9_007_199_254_740_991;
const KINDS: [&str; 7] = ["pr", "issue", "comment", "review", "check", "push", "ping"];
#[derive(Parser)]
#[command(version, about = "GitHub webhook events from your ghwh hub, one JSON object per line.",
after_help = "Hub and key: $GHWH_URL / $GHWH_KEY, else ~/.config/ghwh/config.json (written by `ghwh setup`).\n\
Without a key you only see public repos' events, if the hub serves them.\n\
Exit codes: 0 ok, 1 error, 2 unauthorized, 124 `wait` timed out.\n\n\
Agent loop: ghwh wait --state ~/.ghwh/my-agent --repo owner/name -t 600")]
struct Cli {
#[arg(long, global = true)]
url: Option<String>,
#[command(subcommand)]
cmd: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
Tail(Run),
Wait {
#[command(flatten)]
run: Run,
#[arg(long, short = 'n', default_value_t = 1)]
count: usize,
#[arg(long, short = 't', default_value_t = 300)]
timeout: u64,
},
List {
#[command(flatten)]
filter: Filter,
#[arg(long, default_value_t = 0)]
since: u64,
#[arg(long, default_value_t = 50)]
limit: usize,
},
Status,
Setup {
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
}
#[derive(Args, Clone)]
struct Run {
#[command(flatten)]
filter: Filter,
#[arg(long)]
since: Option<u64>,
#[arg(long)]
state: Option<PathBuf>,
}
#[derive(Args, Clone, Default)]
struct Filter {
#[arg(long, short = 'r')]
repo: Vec<String>,
#[arg(long, short = 'k', value_parser = clap::builder::PossibleValuesParser::new(KINDS))]
kind: Vec<String>,
#[arg(long, short = 'a')]
action: Vec<String>,
#[arg(long)]
text: bool,
}
impl Filter {
fn matches(&self, ev: &Value) -> bool {
let s = |k: &str| ev.get(k).and_then(Value::as_str).unwrap_or("");
let kind = s("kind");
let kind_ok = if self.kind.is_empty() { kind != "ping" } else { self.kind.iter().any(|k| k == kind) };
let repo = s("repo").to_ascii_lowercase();
let repo_ok = self.repo.is_empty()
|| self.repo.iter().any(|r| {
let r = r.to_ascii_lowercase();
match r.strip_suffix("/*") { Some(owner) => repo.starts_with(&format!("{owner}/")), None => r == repo }
});
let action_ok = self.action.is_empty() || self.action.iter().any(|a| a == s("action"));
kind_ok && repo_ok && action_ok
}
fn render(&self, seq: u64, ev: &Value) -> String {
if !self.text {
let mut o = serde_json::Map::new();
o.insert("seq".into(), seq.into());
if let Some(m) = ev.as_object() { o.extend(m.clone()); }
return Value::Object(o).to_string();
}
let s = |k: &str| ev.get(k).and_then(Value::as_str).unwrap_or("");
let n = ev.get("number").and_then(Value::as_u64).map(|n| format!("#{n}")).unwrap_or_default();
let short = |v: &str| v.chars().take(7).collect::<String>();
let one_line = |v: &str, max: usize| {
let l = v.lines().next().unwrap_or("");
if l.chars().count() > max { format!("{}…", l.chars().take(max).collect::<String>()) } else { l.to_string() }
};
let (repo, author, url) = (s("repo"), s("author"), s("url"));
let what = match s("kind") {
"pr" if s("action") == "closed" && ev.get("merged").and_then(Value::as_bool) == Some(true) => {
format!("{repo}{n} pr merged {:?} by {author}", s("title"))
}
"pr" | "issue" => {
let label = if s("label").is_empty() { String::new() } else { format!(" [{}]", s("label")) };
format!("{repo}{n} {} {}{label} {:?} by {author}", s("kind"), s("action"), s("title"))
}
"comment" => format!("{repo}{n} comment by {author}: {:?}", one_line(s("body"), 80)),
"review" => format!("{repo}{n} review {} by {author}", s("state")),
"check" => {
let prs: Vec<String> = ev.get("prs").and_then(Value::as_array).map(|a| a.iter().map(|p| format!("#{p}")).collect()).unwrap_or_default();
format!("{repo} check {:?} {} on {}@{}{}", s("name"), s("conclusion"), s("branch"), short(s("sha")),
if prs.is_empty() { String::new() } else { format!(" ({})", prs.join(" ")) })
}
"push" => format!("{repo} push {}@{} {:?} by {author}", s("branch"), short(s("sha")), s("message")),
"ping" => format!("{repo} ping (hook {})", ev.get("hookId").unwrap_or(&Value::Null)),
k => format!("{repo}{n} {k} {}", s("action")),
};
if url.is_empty() { format!("[{seq}] {what}") } else { format!("[{seq}] {what} {url}") }
}
}
#[derive(Debug)]
enum Fail { Unauthorized, Other(String) }
struct Hub { stream: String, key: Option<String> }
fn config_path() -> Option<PathBuf> {
if let Ok(p) = std::env::var("GHWH_CONFIG") { return Some(PathBuf::from(p)); }
let base = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).filter(|p| p.is_absolute()).or_else(|| {
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(|h| PathBuf::from(h).join(".config"))
})?;
Some(base.join("ghwh").join("config.json"))
}
fn stream_url(url: &str) -> String {
let url = url.trim().trim_end_matches('/');
let (scheme, rest) = match url.split_once("://") {
Some(("http", r)) | Some(("ws", r)) => ("ws", r),
Some((_, r)) => ("wss", r),
None => if url.starts_with("localhost") || url.starts_with("127.0.0.1") { ("ws", url) } else { ("wss", url) },
};
let rest = rest.trim_end_matches("/github/stream").trim_end_matches("/github").trim_end_matches("/mcp");
format!("{scheme}://{rest}/github/stream")
}
fn hub(flag: Option<String>) -> Result<Hub, String> {
let env = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
let file: Option<Value> = config_path().and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok());
let from_file = |k: &str| file.as_ref().and_then(|f| f.get(k)).and_then(Value::as_str).map(str::to_string).filter(|v| !v.is_empty());
let url = flag.or_else(|| env("GHWH_URL")).or_else(|| from_file("url")).ok_or_else(|| {
format!("no hub configured: run `bunx ghwh setup`, or set GHWH_URL (and GHWH_KEY){}",
config_path().map(|p| format!(" — looked in {}", p.display())).unwrap_or_default())
})?;
Ok(Hub { stream: stream_url(&url), key: env("GHWH_KEY").or_else(|| from_file("key")) })
}
fn read_state(p: &Path) -> Option<u64> { std::fs::read_to_string(p).ok()?.trim().parse().ok() }
fn write_state(p: &Path, seq: u64) -> std::io::Result<()> {
if let Some(dir) = p.parent() { if !dir.as_os_str().is_empty() { std::fs::create_dir_all(dir)?; } }
let tmp = p.with_extension("tmp");
std::fs::write(&tmp, format!("{seq}\n"))?;
std::fs::rename(tmp, p)
}
enum Frame { Event(u64, Value), Hello { last: u64, first: u64, more: bool } }
async fn session(hub: &Hub, since: u64, deadline: Option<Instant>, on: &mut dyn FnMut(Frame) -> bool) -> Result<bool, Fail> {
let connect = tokio_tungstenite::connect_async(hub.stream.as_str());
let (mut ws, _) = match deadline {
Some(d) => match timeout_at(d, connect).await { Ok(r) => r, Err(_) => return Ok(false) },
None => connect.await,
}
.map_err(|e| Fail::Other(format!("connect {}: {e}", hub.stream)))?;
let mut hello = json!({ "since": since, "all": true });
if let Some(k) = &hub.key { hello["auth"] = k.clone().into(); }
ws.send(Message::Text(hello.to_string().into())).await.map_err(|e| Fail::Other(format!("send: {e}")))?;
let mut ping = tokio::time::interval(Duration::from_secs(30));
ping.tick().await;
loop {
let next = async {
tokio::select! {
m = ws.next() => Some(m),
_ = ping.tick() => None,
}
};
let got = match deadline {
Some(d) => match timeout_at(d, next).await { Ok(g) => g, Err(_) => return Ok(false) },
None => next.await,
};
let msg = match got {
None => { ws.send(Message::Text("ping".into())).await.map_err(|e| Fail::Other(format!("ping: {e}")))?; continue; }
Some(None) => return Err(Fail::Other("connection closed".into())),
Some(Some(Err(e))) => return Err(Fail::Other(format!("read: {e}"))),
Some(Some(Ok(m))) => m,
};
match msg {
Message::Text(t) => {
let Ok(v) = serde_json::from_str::<Value>(t.as_str()) else { continue }; let frame = match v.get("type").and_then(Value::as_str) {
Some("event") => match (v.get("seq").and_then(Value::as_u64), v.get("event")) {
(Some(s), Some(e)) => Frame::Event(s, e.clone()),
_ => continue,
},
Some("hello") => Frame::Hello {
last: v.get("last").and_then(Value::as_u64).unwrap_or(0),
first: v.get("first").and_then(Value::as_u64).unwrap_or(0),
more: v.get("more").and_then(Value::as_bool).unwrap_or(false),
},
_ => continue,
};
if !on(frame) { let _ = ws.close(None).await; return Ok(true); }
}
Message::Close(c) => {
if c.as_ref().map(|c| u16::from(c.code)) == Some(4001) { return Err(Fail::Unauthorized); }
return Err(Fail::Other(format!("closed by hub: {}", c.map(|c| c.reason.to_string()).unwrap_or_default())));
}
_ => {}
}
}
}
async fn follow(hub: &Hub, run: &Run, deadline: Option<Instant>, mut on: impl FnMut(u64, &Value) -> bool) -> Result<bool, Fail> {
let mut since = run.since.or_else(|| run.state.as_deref().and_then(read_state)).unwrap_or(NOW);
let mut backoff = 1u64;
let mut warned_gap = false;
loop {
let (mut stop, mut again) = (false, false);
let start = since; let res = session(hub, since, deadline, &mut |f| {
match f {
Frame::Hello { last, first, more } => {
backoff = 1;
if start != NOW && start > 0 && first > start + 1 && !warned_gap {
eprintln!("ghwh: events {}..{} were dropped from the hub before we read them (it keeps the last 1000)", start + 1, first - 1);
warned_gap = true;
}
if since == NOW { since = last; }
else if since > last { eprintln!("ghwh: the hub's log restarted (at {last}, we were at {since}); reading it from the start"); since = 0; again = true; return false; }
else if more { again = true; return false; } else { since = since.max(last); } }
Frame::Event(seq, ev) => {
if since != NOW && seq <= since { return true; }
since = seq;
if run.filter.matches(&ev) && !on(seq, &ev) { stop = true; return false; }
}
}
true
})
.await;
match res {
Ok(true) if again => continue,
Ok(true) => return Ok(stop),
Ok(false) => return Ok(false),
Err(Fail::Unauthorized) => return Err(Fail::Unauthorized),
Err(Fail::Other(e)) => {
if deadline.is_some_and(|d| Instant::now() >= d) { return Ok(false); }
eprintln!("ghwh: {e}; reconnecting in {backoff}s");
sleep(Duration::from_secs(backoff)).await;
backoff = (backoff * 2).min(60);
}
}
}
}
fn emit(line: &str) -> bool {
let mut out = std::io::stdout().lock();
writeln!(out, "{line}").and_then(|_| out.flush()).is_ok() }
#[tokio::main(flavor = "current_thread")]
async fn main() {
let cli = Cli::parse();
let code = match real_main(cli).await {
Ok(c) => c,
Err(Fail::Unauthorized) => { eprintln!("ghwh: unauthorized (check GHWH_KEY or the key in the config file; without a key the hub must serve public events)"); 2 }
Err(Fail::Other(e)) => { eprintln!("ghwh: {e}"); 1 }
};
std::process::exit(code);
}
fn setup(args: &[String]) -> i32 {
let pkg = format!("ghwh@{}", env!("CARGO_PKG_VERSION"));
for (cmd, pre) in [("bunx", vec![pkg.as_str()]), ("npx", vec!["-y", pkg.as_str()])] {
match std::process::Command::new(cmd).args(&pre).arg("setup").args(args).status() {
Ok(s) => return s.code().unwrap_or(1),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => { eprintln!("ghwh: {cmd}: {e}"); return 1; }
}
}
eprintln!("ghwh: setup needs Bun or Node.js (it runs `bunx {pkg} setup`). Install one, or follow the manual guide: https://github.com/snomiao/github-webhooks/blob/main/docs/manual-setup.md");
1
}
async fn real_main(cli: Cli) -> Result<i32, Fail> {
if let Cmd::Setup { args } = &cli.cmd { return Ok(setup(args)); }
let hub = hub(cli.url).map_err(Fail::Other)?;
let save = |state: &Option<PathBuf>, seq: u64| {
if let Some(p) = state { if let Err(e) = write_state(p, seq) { eprintln!("ghwh: state {}: {e}", p.display()); } }
};
match cli.cmd {
Cmd::Setup { .. } => unreachable!(),
Cmd::Tail(run) => {
let r = follow(&hub, &run, None, |seq, ev| {
let ok = emit(&run.filter.render(seq, ev));
if ok { save(&run.state, seq); }
ok
});
tokio::select! {
r = r => r.map(|_| 0),
_ = tokio::signal::ctrl_c() => Ok(130),
}
}
Cmd::Wait { run, count, timeout } => {
let deadline = Instant::now() + Duration::from_secs(timeout);
let mut n = 0;
follow(&hub, &run, Some(deadline), |seq, ev| {
if !emit(&run.filter.render(seq, ev)) { return false; }
save(&run.state, seq);
n += 1;
n < count.max(1)
})
.await?;
Ok(if n > 0 { 0 } else { 124 })
}
Cmd::List { filter, since, limit } => {
let mut rows: Vec<(u64, Value)> = Vec::new();
let deadline = Some(Instant::now() + Duration::from_secs(30));
let mut since = since;
loop {
let (mut done, mut reset) = (false, false);
let ok = session(&hub, since, deadline, &mut |f| match f {
Frame::Event(seq, ev) => { since = since.max(seq); if filter.matches(&ev) { rows.push((seq, ev)); } true }
Frame::Hello { last, more, .. } => { reset = since > last && rows.is_empty(); done = !more; false }
})
.await?;
if !ok { return Err(Fail::Other("timed out".into())); }
if reset { since = 0; continue; }
if done { break; }
}
let skip = rows.len().saturating_sub(limit);
for (seq, ev) in &rows[skip..] { if !emit(&filter.render(*seq, ev)) { break; } }
Ok(0)
}
Cmd::Status => {
println!("hub: {}", hub.stream);
println!("key: {}", if hub.key.is_some() { "set" } else { "none (public repos only)" });
if let Some(p) = config_path() { println!("config: {}{}", p.display(), if p.exists() { "" } else { " (missing)" }); }
let mut last = None;
let deadline = Some(Instant::now() + Duration::from_secs(15));
match session(&hub, NOW, deadline, &mut |f| { if let Frame::Hello { last: l, .. } = f { last = Some(l); } false }).await {
Ok(true) => { println!("stream: ok, last seq {}", last.unwrap_or(0)); Ok(0) }
Ok(false) => Err(Fail::Other("stream: no answer within 15s".into())),
Err(e) => Err(e),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stream_urls() {
assert_eq!(stream_url("https://hooks.example.com"), "wss://hooks.example.com/github/stream");
assert_eq!(stream_url("hooks.example.com/"), "wss://hooks.example.com/github/stream");
assert_eq!(stream_url("wss://hooks.example.com/github/stream"), "wss://hooks.example.com/github/stream");
assert_eq!(stream_url("https://hooks.example.com/mcp"), "wss://hooks.example.com/github/stream");
assert_eq!(stream_url("http://localhost:8787"), "ws://localhost:8787/github/stream");
assert_eq!(stream_url("localhost:8787"), "ws://localhost:8787/github/stream");
}
#[test]
fn filters() {
let ev = json!({"kind": "pr", "action": "opened", "repo": "Acme/App"});
let f = |repo: &[&str], kind: &[&str]| Filter { repo: repo.iter().map(|s| s.to_string()).collect(), kind: kind.iter().map(|s| s.to_string()).collect(), ..Default::default() };
assert!(f(&[], &[]).matches(&ev));
assert!(f(&["acme/*"], &[]).matches(&ev));
assert!(f(&["acme/app"], &["pr"]).matches(&ev));
assert!(!f(&["acm/*"], &[]).matches(&ev));
assert!(!f(&[], &["issue"]).matches(&ev));
assert!(!f(&[], &[]).matches(&json!({"kind": "ping", "repo": "acme/app"})));
}
#[test]
fn json_lines_put_seq_first() {
let line = Filter::default().render(5, &json!({"kind": "push", "repo": "a/b"}));
assert!(line.starts_with(r#"{"seq":5,"#), "{line}");
}
}