diff --git a/README.md b/README.md index 45e3aca..bcb0587 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ WEBHOOK_URL: <通知用webhook> ALERT_WEBHOOK_URL: <アラート用webhook> GITHUB_TOKEN: NOTIFY_MODE: +EXCLUDE_LABELS: <通知対象から外すラベル名(カンマ区切り。省略時は除外しない)> ENV: <環境名> ``` @@ -31,6 +32,25 @@ Slack では `@channel`(``)、Discord では `@everyone` を使う レビューできる状態になっていない PR でチャンネル全体を叩かないため。 通知そのものは従来どおり届く。 +## ラベルによる除外 + +`EXCLUDE_LABELS` に指定したラベルが 1 つでも付いている PR / Issue の通知は送らない。 +自動マージされる PR のように、人が確認しなくてよい通知を流さないための設定。 + +``` +EXCLUDE_LABELS: automerge,dependencies +``` + +ラベル名はカンマ区切りで複数指定でき、大文字小文字は区別しない(GitHub のラベル名と同じ扱い)。 +省略した場合は除外しない。 + +除外した通知も GitHub 上では既読にする。 +未読のまま残すと、毎分の実行で取得され続けるため。 + +通知の payload にラベルは含まれないので、指定した場合は PR / Issue の通知 1 件につき +API 呼び出しが 1 回増える。 +ラベルを取得できなかった通知は除外せずに送る。 + ## 投稿の分割 メンション対象の通知とそれ以外は、別々の投稿に分けて送る。 diff --git a/spec/github/models_spec.cr b/spec/github/models_spec.cr index b32fd5a..b3d0e31 100644 --- a/spec/github/models_spec.cr +++ b/spec/github/models_spec.cr @@ -502,3 +502,23 @@ NOTIFICATIONS_FIXTURE = <<-JSON } ] JSON + +describe Github::Labeled do + it "ラベル名を小文字の集合で返す" do + labeled = Github::Labeled.from_json({labels: [{name: "AutoMerge"}, {name: "bug"}]}.to_json) + labeled.label_names.should eq Set{"automerge", "bug"} + end + + it "labels が無ければ空集合を返す" do + Github::Labeled.from_json("{}").label_names.should be_empty + end +end + +describe Github::Subject do + it "PR と Issue だけをラベルを持つ type とみなす" do + labeled = %w[PullRequest Issue Commit Discussion Release].select do |type| + Github::Subject.from_json({type: type}.to_json).labeled? + end + labeled.should eq %w[PullRequest Issue] + end +end diff --git a/spec/github/usecase_spec.cr b/spec/github/usecase_spec.cr index f0fc346..9d3fe9f 100644 --- a/spec/github/usecase_spec.cr +++ b/spec/github/usecase_spec.cr @@ -67,7 +67,50 @@ private def build(notify, comment) Github::Usecase.new(StubRepo.new(comment)).build_message(notify) end +# あらかじめ用意したラベルを返すリポジトリ。 +private class LabelRepo < Github::NotificationRepository + def initialize(@labels : Set(String)) + super("token") + end + + def find_labels(notify : Github::Notification) : Set(String) + @labels + end +end + describe Github::Usecase do + describe ".parse_labels" do + it "カンマ区切りを小文字の集合にする" do + Github::Usecase.parse_labels("automerge, Dependencies").should eq Set{"automerge", "dependencies"} + end + + it "空要素を読み捨てる" do + Github::Usecase.parse_labels(" ,automerge,,").should eq Set{"automerge"} + end + + it "未設定なら空集合を返す" do + Github::Usecase.parse_labels(nil).should be_empty + Github::Usecase.parse_labels("").should be_empty + end + end + + describe "#excluded?" do + it "除外ラベルが付いていれば true を返す" do + usecase = Github::Usecase.new LabelRepo.new(Set{"automerge", "bug"}), Set{"automerge"} + usecase.excluded?(notification).should be_true + end + + it "除外ラベルが付いていなければ false を返す" do + usecase = Github::Usecase.new LabelRepo.new(Set{"bug"}), Set{"automerge"} + usecase.excluded?(notification).should be_false + end + + it "除外ラベルが未設定なら false を返す" do + usecase = Github::Usecase.new LabelRepo.new(Set{"automerge"}) + usecase.excluded?(notification).should be_false + end + end + describe "#build_message" do it "reflects the reason in the pretext" do build(notification(reason: "review_requested"), comment).pretext.should eq "[Issue] レビューを依頼されました" diff --git a/spec/notify/usecase_spec.cr b/spec/notify/usecase_spec.cr index 5efebe4..12d01a5 100644 --- a/spec/notify/usecase_spec.cr +++ b/spec/notify/usecase_spec.cr @@ -24,6 +24,9 @@ end private class FakeNotificationRepo < Github::NotificationRepository getter read_calls = [] of Time? getter before_arg : Time? + # 通知の title をキーに、付いているラベルを指定する。 + property labels = {} of String => Set(String) + getter labels_calls = 0 # raise_read_after 回目の既読化呼び出しで例外を投げ、既読化失敗を再現する。 def initialize(@notifications : Array(Github::Notification), @raise_read_after : Int32? = nil) @@ -39,6 +42,11 @@ private class FakeNotificationRepo < Github::NotificationRepository Github::Comment.new "body" end + def find_labels(notify : Github::Notification) : Set(String) + @labels_calls += 1 + @labels[notify.subject.title]? || Set(String).new + end + def notification_to_read(last_read_at : Time? = nil) @read_calls << last_read_at if (limit = @raise_read_after) && @read_calls.size >= limit @@ -89,6 +97,15 @@ private def run(notifications, poster, &) repo end +# automerge ラベルを除外対象にし、labels で指定した title の通知にそのラベルを付けて実行する。 +private def run_excluding(notifications, poster, labeled : Array(String), &) + repo = FakeNotificationRepo.new notifications + labeled.each { |title| repo.labels[title] = Set{"automerge"} } + usecase = Notify::Usecase.new repo, Github::Usecase.new(repo, Set{"automerge"}), poster + yield usecase + repo +end + describe Notify::Usecase do describe "#check_notifications" do # last_read_at は排他的境界(updated_at < last_read_at のみ既読化、issue #100) @@ -209,6 +226,69 @@ describe Notify::Usecase do repo.read_calls.should eq [t(2)] end + # 除外ラベル(EXCLUDE_LABELS)の付いた通知は送らないが、既読化はする。 + + it "除外ラベルの付いた通知は送らない" do + notifications = [ + notif("2026-01-01T00:00:01Z", title: "a"), + notif("2026-01-01T00:00:02Z", title: "b"), + notif("2026-01-01T00:00:03Z", title: "c"), + ] + poster = RecordingPoster.new + run_excluding(notifications, poster, labeled: ["b"], &.check_notifications) + + poster.posts.flat_map(&.map(&.title)).should eq ["a", "c"] + end + + it "除外した通知も送信対象と一緒に既読化する" do + notifications = [ + notif("2026-01-01T00:00:01Z", title: "a"), + notif("2026-01-01T00:00:02Z", title: "b"), + ] + repo = run_excluding(notifications, RecordingPoster.new, labeled: ["b"]) do |usecase| + usecase.check_notifications + end + + # 送信対象は a だけ。全件送信済みなので境界は取得スナップショットまで進み、 + # 除外した b(t(2))も既読化される。 + repo.read_calls.should eq [repo.before_arg] + end + + it "未送信の通知より後に更新された除外通知は既読化しない" do + notifications = [ + notif("2026-01-01T00:00:01Z", title: "a"), + notif("2026-01-01T00:00:02Z", reason: "mention", title: "b"), + notif("2026-01-01T00:00:03Z", title: "c"), + ] + repo = run_excluding(notifications, RecordingPoster.new(fail_at: 1), labeled: ["c"]) do |usecase| + expect_raises(Exception, "send failed") { usecase.check_notifications } + end + + # b の送信に失敗。境界は b の t(2) で、それより後の c は未読に残り、 + # 次回もう一度ラベルを判定される。 + repo.read_calls.should eq [t(2)] + end + + it "全件が除外されたら送信せずに既読化する" do + notifications = [notif("2026-01-01T00:00:01Z", title: "a")] + poster = RecordingPoster.new + repo = run_excluding(notifications, poster, labeled: ["a"]) do |usecase| + usecase.check_notifications + end + + poster.posts.should be_empty + repo.read_calls.should eq [repo.before_arg] + end + + it "除外ラベルが未設定ならラベルを取得しない" do + notifications = [notif("2026-01-01T00:00:01Z")] + repo = run(notifications, RecordingPoster.new) do |usecase| + usecase.check_notifications + end + + repo.labels_calls.should eq 0 + end + it "既読化に失敗したら後続チャンクの送信を止める" do notifications = [notif("2026-01-01T00:00:01Z"), notif("2026-01-01T00:00:02Z"), notif("2026-01-01T00:00:03Z")] poster = ChunkPoster.new([1, 1, 1]) diff --git a/src/github/models.cr b/src/github/models.cr index 2ef8d3a..85db3cc 100644 --- a/src/github/models.cr +++ b/src/github/models.cr @@ -214,10 +214,22 @@ module Github Type::RELEASE, } + # ラベルが付く type。subject.url を取得すると labels を含むオブジェクトが返る。 + LABELED_TYPES = { + Type::PULL_REQUEST, + Type::ISSUE, + } + def update? : Bool type.in?(UPDATE_TYPES) end + # ラベルを持つ type か。ラベルで通知を除外できるのはこの type に限る + # (Github::Usecase#excluded?)。 + def labeled? : Bool + type.in?(LABELED_TYPES) + end + def color : String case type when Type::PULL_REQUEST @@ -325,6 +337,24 @@ module Github end end + # ラベルによる除外の判定に使う subject 本体(PR / Issue)。labels だけ参照する。 + class Labeled + include JSON::Serializable + + getter labels : Array(Label) = [] of Label + + # 比較用に小文字へ揃えたラベル名。GitHub のラベル名は大文字小文字を区別しない。 + def label_names : Set(String) + labels.map(&.name.downcase).to_set + end + + class Label + include JSON::Serializable + + getter name : String = "" + end + end + # チェック状態の判定に使う PR 情報。head の SHA だけ参照する(issue #105)。 class PullRequest include JSON::Serializable diff --git a/src/github/repository.cr b/src/github/repository.cr index 7ea6e06..2a93cff 100644 --- a/src/github/repository.cr +++ b/src/github/repository.cr @@ -153,6 +153,28 @@ module Github runs.merge find_combined_status_state("/repos/#{repo}/commits/#{sha}/status?per_page=#{CHECKS_PER_PAGE}") end + # 通知対象(PR / Issue)に付いているラベル名を小文字で返す。 + # + # 通知の payload にラベルは含まれないため、subject 本体を取得して調べる。 + # 本文表示用に取得するオブジェクト(find_comment_by_url)は、スレッドにコメントが + # あるとコメント側になりラベルを持たないので、それとは別に取得する。 + # + # ラベルを持たない type と取得できなかった場合は空集合を返す。空集合なら + # 呼び出し側は除外しないので、取得の失敗で通知が消えることはない。 + def find_labels(notify : Notification) : Set(String) + empty = Set(String).new + return empty unless notify.subject.labeled? + return empty unless url = notify.subject.url.presence + return empty unless body = get_body url + + begin + Labeled.from_json(body).label_names + rescue + Serverless::Lambda.print_log "failed parse labels data" + empty + end + end + private def find_head_sha(path : String) : String? return unless body = get_body path diff --git a/src/github/usecase.cr b/src/github/usecase.cr index f5b8d62..4dc718b 100644 --- a/src/github/usecase.cr +++ b/src/github/usecase.cr @@ -8,7 +8,27 @@ module Github # 防ぐため組み立て側(Slack / Discord 共通)で切り詰める(issue #96)。 BODY_LIMIT = 500 - def initialize(@repo : NotificationRepository) + # exclude_labels は通知対象から外すラベル名(parse_labels で正規化した集合)。 + def initialize(@repo : NotificationRepository, @exclude_labels : Set(String) = Set(String).new) + end + + # カンマ区切りのラベル名(環境変数 EXCLUDE_LABELS)を集合にする。 + # GitHub のラベル名は大文字小文字を区別しないため、比較用に小文字へ揃える。 + # 前後の空白と空要素(末尾のカンマなど)は設定の揺れとして読み捨てる。 + def self.parse_labels(raw : String?) : Set(String) + return Set(String).new unless raw + + raw.split(',').map(&.strip.downcase).reject(&.empty?).to_set + end + + # 除外ラベルが付いていて、通知対象から外す通知か。 + # + # 除外ラベルが未設定ならラベルを取得せずに false を返す。設定しない限り + # API 呼び出しは増えない。 + def excluded?(notify : Notification) : Bool + return false if @exclude_labels.empty? + + @repo.find_labels(notify).intersects?(@exclude_labels) end def build_message(notify : Notification) : Notify::Message diff --git a/src/main.cr b/src/main.cr index dc95b4e..0459298 100644 --- a/src/main.cr +++ b/src/main.cr @@ -13,6 +13,8 @@ WEBHOOK_URL = ENV["WEBHOOK_URL"] ALERT_WEBHOOK_URL = ENV["ALERT_WEBHOOK_URL"] NOTIFY_MODE = ENV["NOTIFY_MODE"]? || "slack" APP_ENV = ENV["ENV"] +# 通知対象から外すラベル名(カンマ区切り)。未設定なら何も除外しない。 +EXCLUDE_LABELS = Github::Usecase.parse_labels ENV["EXCLUDE_LABELS"]? # NOTIFY_MODE に応じて送信先アダプタを生成する。 # 未設定時は既定の slack だが、想定外の値(typo 等)は起動時に例外にして @@ -36,7 +38,7 @@ end github_repo = Github::NotificationRepository.new GITHUB_TOKEN notify_uc = Notify::Usecase.new( github_repo, - Github::Usecase.new(github_repo), + Github::Usecase.new(github_repo, EXCLUDE_LABELS), build_poster(WEBHOOK_URL), ) error_uc = Error::Usecase.new( diff --git a/src/notify/usecase.cr b/src/notify/usecase.cr index 2e2952b..11c1220 100644 --- a/src/notify/usecase.cr +++ b/src/notify/usecase.cr @@ -28,14 +28,29 @@ module Notify return {msg: "ok"} if notifications.empty? + # 除外ラベル(EXCLUDE_LABELS)の付いた通知は送信対象から外す。 + # + # 外した通知も既読化はする。未読のまま残すと、毎分取得されてそのたびに + # ラベルを調べ直すことになる。既読化の境界は送信対象だけで決めてよい。 + # 境界より前に更新された通知は外したものも含めて既読化され、境界以降の + # ものは未読に残って次回もう一度判定されるだけで、送信はされない。 + targets = notifications.reject { |item| @github_uc.excluded? item } + + # 全件を外した場合は送信が起きず、送信後の既読化も呼ばれない。 + # 取得した集合をここで既読化して、次回の再取得を止める。 + if targets.empty? + @github_repo.notification_to_read fetched_at + return {msg: "ok"} + end + # pretext は reason(なぜ通知されたか)を反映した文言になる(issue #96)。 - notices = notifications.map { |item| @github_uc.build_message item } + notices = targets.map { |item| @github_uc.build_message item } # チャンク送信が成功するたび、そこまでに送信済みの通知だけを既読化する。 # 途中で失敗しても送信済み分は既読化済みなので、未送信分だけが次回 # 再取得され、前半チャンクの重複投稿が起きない。 send_split notices do |sent_count| - mark_read_through notifications, sent_count, fetched_at + mark_read_through targets, sent_count, fetched_at end {msg: "ok"}