review_request 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +18 -0
- data/CLAUDE.md +41 -0
- data/LICENSE +21 -0
- data/README.md +240 -0
- data/exe/jira-overdue-reminder +6 -0
- data/exe/pr-reminder +6 -0
- data/lib/review_request/cache.rb +65 -0
- data/lib/review_request/cli.rb +187 -0
- data/lib/review_request/date_checker.rb +16 -0
- data/lib/review_request/errors.rb +53 -0
- data/lib/review_request/github.rb +164 -0
- data/lib/review_request/http_client.rb +69 -0
- data/lib/review_request/jira.rb +33 -0
- data/lib/review_request/jira_overdue_reminder_service.rb +115 -0
- data/lib/review_request/jira_sprint_notification_service.rb +66 -0
- data/lib/review_request/message_templates.rb +214 -0
- data/lib/review_request/messages.rb +68 -0
- data/lib/review_request/pr_reminder_service.rb +158 -0
- data/lib/review_request/retry.rb +35 -0
- data/lib/review_request/send_message.rb +167 -0
- data/lib/review_request/slack.rb +119 -0
- data/lib/review_request/support.rb +21 -0
- data/lib/review_request/version.rb +5 -0
- data/lib/review_request.rb +32 -0
- metadata +97 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: c5fcf4531e8c3d17af2d39835301bafec3387cfd3bcbb9977ef85058a25b4091
|
|
4
|
+
data.tar.gz: eeca8c0e5721b5c93b1bf20c4286388e7ed65f9c876e1fb315df220257f3a8da
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 2b53e517a7d34d7fba5170fae83dc2c246c41495132c79bfe6ae0da23dab872a2b5d2be94b9818b05a4c4f62793d80adaa2ba5a6221d30584640a8c711d82741
|
|
7
|
+
data.tar.gz: a1a8564338e5cb3782f04d6a5423d6d521a0dcd799bc61a936cd289ca71094d401820b6b80c66b5cc69240d3562baf3b376a21ac41cb173be974ea54a51312a6
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [0.1.0] - 2026-11-20
|
|
8
|
+
|
|
9
|
+
Initial release. A Ruby port of the review-request Python package.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `ReviewRequest::SendMessage`: Slack review requests from slash-command text, with optional `--scheduled=` in Asia/Bangkok time.
|
|
14
|
+
- `ReviewRequest::PRReminderService`: daily digest of open GitHub PRs awaiting a team's review.
|
|
15
|
+
- `ReviewRequest::JiraSprintNotificationService`: Slack summary when a Jira sprint closes.
|
|
16
|
+
- `ReviewRequest::JiraOverdueReminderService`: Slack alert for overdue in-progress Jira issues.
|
|
17
|
+
- `pr-reminder` and `jira-overdue-reminder` executables for cron.
|
|
18
|
+
- Retries with exponential back-off for transient API failures.
|
data/CLAUDE.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# CLAUDE.md
|
|
2
|
+
|
|
3
|
+
Guidance for Claude Code when working in this repository.
|
|
4
|
+
|
|
5
|
+
## Commands
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bundle install
|
|
9
|
+
bundle exec rake # tests + RuboCop (default task; what CI runs)
|
|
10
|
+
bundle exec rake test # tests only
|
|
11
|
+
bundle exec rubocop # lint and style only
|
|
12
|
+
bundle exec ruby -Ilib -Itest test/send_message_test.rb # single file
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Run both `rake test` and `rubocop` before finishing a change. CI fails if either fails.
|
|
16
|
+
|
|
17
|
+
## Layout
|
|
18
|
+
|
|
19
|
+
The gem lives in `lib/review_request/`. It has no web framework dependency. Callers construct services directly with keyword arguments.
|
|
20
|
+
|
|
21
|
+
- `send_message.rb` (`SendMessage`): parses a Slack slash-command payload, fetches the PR, and posts or schedules the message.
|
|
22
|
+
- `pr_reminder_service.rb`, `jira_overdue_reminder_service.rb`, `jira_sprint_notification_service.rb`: the three scheduled and webhook features.
|
|
23
|
+
- `github.rb`, `slack.rb`, `jira.rb`: API clients on top of `http_client.rb` (`Net::HTTP`, no extra gems).
|
|
24
|
+
- `messages.rb` and `message_templates.rb`: Slack text. Templates use `{placeholder}` syntax, and `Messages.render` raises on unknown placeholders.
|
|
25
|
+
- `retry.rb`: retries transient `APIError`s with back-off. Tests set `ReviewRequest::Retry.sleeper` to a no-op.
|
|
26
|
+
- `cache.rb`: thread-safe TTL cache used by GitHub (300 s) and Slack usergroups (24 h).
|
|
27
|
+
- `cli.rb`: entry points behind `exe/pr-reminder` and `exe/jira-overdue-reminder`.
|
|
28
|
+
|
|
29
|
+
## Conventions
|
|
30
|
+
|
|
31
|
+
- Keyword arguments for constructors and public methods. `#call` for the main action of `SendMessage`.
|
|
32
|
+
- Error classes live in `errors.rb`. Use `InvalidInputError` for input that users can fix. Use `APIError` (and subclasses) for external failures, and rescue `APIError` when calling client methods, since transport errors are raised as the base class.
|
|
33
|
+
- Slack Web API calls are POSTs with JSON bodies, including read-only methods such as `usergroups.list`. Tests must stub them as `:post`.
|
|
34
|
+
- Keep the Python package's message wording. Change templates only on purpose.
|
|
35
|
+
- Tests use Minitest with WebMock. Real network calls are blocked by `test_helper.rb`.
|
|
36
|
+
|
|
37
|
+
## Gotchas
|
|
38
|
+
|
|
39
|
+
- `minitest/mock` is a separate gem on Ruby 3.5+ and 4.x. Keep `minitest-mock` in the Gemfile.
|
|
40
|
+
- `logger` is no longer a default gem on Ruby 4.0, so it is a declared runtime dependency.
|
|
41
|
+
- Slack's `channel_not_found` error is not retried. Other Slack `ok: false` codes are retried only if they are in `SlackError::TRANSIENT_CODES`.
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bradley Nguyen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
# review_request
|
|
2
|
+
|
|
3
|
+
A Ruby gem for automating code review requests with Slack, GitHub, and Jira. It is a Ruby port of the [review-request](https://github.com/kingkong0905/review-request) Python package and offers the same features:
|
|
4
|
+
|
|
5
|
+
- Post a Slack review request from a slash-command payload (with optional scheduling)
|
|
6
|
+
- Send a daily digest of open GitHub PRs awaiting a team's review
|
|
7
|
+
- Post a Slack notification when a Jira sprint closes
|
|
8
|
+
- Post a Slack alert for in-progress Jira issues past their due date
|
|
9
|
+
|
|
10
|
+
There is no web framework dependency. Call the services from any Ruby application, or run the bundled CLI commands from cron.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
Requires Ruby 3.2+.
|
|
15
|
+
|
|
16
|
+
```ruby
|
|
17
|
+
# Gemfile
|
|
18
|
+
gem "review_request"
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
gem install review_request
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Runtime dependencies are `dotenv` (used by the CLI) and `logger`. The HTTP layer uses the standard library's `Net::HTTP`.
|
|
26
|
+
|
|
27
|
+
## Configuration
|
|
28
|
+
|
|
29
|
+
There is no global configuration object. Pass credentials and mappings to each service's constructor. The CLI commands read these environment variables (or a `.env` file in the working directory):
|
|
30
|
+
|
|
31
|
+
| Variable | Purpose |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `GITHUB_TOKEN` | GitHub API auth |
|
|
34
|
+
| `BOT_TOKEN` | Slack bot token (`xoxb-...`) |
|
|
35
|
+
| `JIRA_SITE` | e.g. `https://yourorg.atlassian.net` |
|
|
36
|
+
| `JIRA_EMAIL` | Jira account email |
|
|
37
|
+
| `JIRA_API_TOKEN` | Jira API token |
|
|
38
|
+
| `APP_URL` | Public base URL for the bot icon (optional) |
|
|
39
|
+
|
|
40
|
+
## Usage
|
|
41
|
+
|
|
42
|
+
### Send a review request
|
|
43
|
+
|
|
44
|
+
`ReviewRequest::SendMessage` parses a Slack slash-command text payload, fetches the PR from GitHub, and posts or schedules the message in Slack.
|
|
45
|
+
|
|
46
|
+
```ruby
|
|
47
|
+
require "review_request"
|
|
48
|
+
|
|
49
|
+
def handle_review_request(user_id:, text:)
|
|
50
|
+
ReviewRequest::SendMessage.new(
|
|
51
|
+
user_id:,
|
|
52
|
+
message: text,
|
|
53
|
+
github_token: ENV.fetch("GITHUB_TOKEN"),
|
|
54
|
+
bot_token: ENV.fetch("BOT_TOKEN"),
|
|
55
|
+
default_channel_id: "C123456",
|
|
56
|
+
slack_team_mappings: { "@squad-name" => "S123456" }
|
|
57
|
+
).call
|
|
58
|
+
end
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The `text` format:
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
<PR_URL> [@user or #channel or @group] [--scheduled=YYYY/MM/DD HH:MM:SS]
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
| Example | Behaviour |
|
|
68
|
+
|---|---|
|
|
69
|
+
| `https://github.com/org/repo/pull/123 @alice` | Posts immediately, mentions `@alice` |
|
|
70
|
+
| `https://github.com/org/repo/pull/123 #code-review @squad` | Posts to `#code-review`, mentions `@squad` |
|
|
71
|
+
| `https://github.com/org/repo/pull/123 --scheduled=2025/12/01 09:00:00` | Schedules at 09:00 Asia/Bangkok (UTC+7) |
|
|
72
|
+
|
|
73
|
+
If no reviewer is named, the gem uses the teams requested on the GitHub PR and maps them to Slack usergroups. Up to 2 PR URLs can be submitted at once.
|
|
74
|
+
|
|
75
|
+
Invalid input raises `ReviewRequest::InvalidInputError`, which is safe to show to the user:
|
|
76
|
+
|
|
77
|
+
```ruby
|
|
78
|
+
begin
|
|
79
|
+
ReviewRequest::SendMessage.new(user_id:, message: text, github_token:, bot_token:).call
|
|
80
|
+
rescue ReviewRequest::InvalidInputError => e
|
|
81
|
+
{ error: e.message }
|
|
82
|
+
end
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Send a daily PR reminder
|
|
86
|
+
|
|
87
|
+
`ReviewRequest::PRReminderService` scans GitHub for open PRs requested from a team and posts a digest to Slack.
|
|
88
|
+
|
|
89
|
+
```ruby
|
|
90
|
+
service = ReviewRequest::PRReminderService.new(
|
|
91
|
+
github_token: ENV.fetch("GITHUB_TOKEN"),
|
|
92
|
+
slack_token: ENV.fetch("BOT_TOKEN"),
|
|
93
|
+
repositories: [{ url: "https://github.com/org/repo", base_branch: "main" }]
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
service.send_reminder(
|
|
97
|
+
channel_id: "C123456", # Slack channel to post to
|
|
98
|
+
slack_group_id: "@squad", # Slack usergroup handle or ID to mention
|
|
99
|
+
github_team: "my-team", # GitHub team slug
|
|
100
|
+
max_age_pr_days: 30, # ignore PRs older than this
|
|
101
|
+
remind_date: %w[Monday Wednesday Friday] # empty or omitted = every day
|
|
102
|
+
)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`send_reminder` returns `true` when it posted, or when there was nothing to do. It returns `false` if an error occurred. Pass `dry_run: true` to log the message without posting.
|
|
106
|
+
|
|
107
|
+
### Notify on Jira sprint completion
|
|
108
|
+
|
|
109
|
+
`ReviewRequest::JiraSprintNotificationService` posts a sprint summary to a Slack channel.
|
|
110
|
+
|
|
111
|
+
```ruby
|
|
112
|
+
service = ReviewRequest::JiraSprintNotificationService.new(slack_token: ENV.fetch("BOT_TOKEN"))
|
|
113
|
+
|
|
114
|
+
# Direct call
|
|
115
|
+
service.send_notification(
|
|
116
|
+
channel_id: "C123456",
|
|
117
|
+
sprint_name: "Sprint 42",
|
|
118
|
+
start_date: "2025-01-01T00:00:00.000Z",
|
|
119
|
+
end_date: "2025-01-14T00:00:00.000Z",
|
|
120
|
+
completed_by: "Alice"
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# Raw Jira webhook payload (parsed JSON with string keys).
|
|
124
|
+
# Only "sprint_closed" events are sent; other events return nil.
|
|
125
|
+
service.process_webhook(channel_id: "C123456", webhook_data: JSON.parse(request_body))
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Send a Jira overdue reminder
|
|
129
|
+
|
|
130
|
+
`ReviewRequest::JiraOverdueReminderService` runs a JQL query for in-progress issues past their due date and posts a Slack alert. Assignees are mentioned when they belong to the configured usergroup.
|
|
131
|
+
|
|
132
|
+
```ruby
|
|
133
|
+
service = ReviewRequest::JiraOverdueReminderService.new(
|
|
134
|
+
jira_site: "https://yourorg.atlassian.net",
|
|
135
|
+
jira_email: "you@example.com",
|
|
136
|
+
jira_api_token: ENV.fetch("JIRA_API_TOKEN"),
|
|
137
|
+
slack_token: ENV.fetch("BOT_TOKEN")
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
service.send_reminder(
|
|
141
|
+
channel_id: "C123456",
|
|
142
|
+
slack_group_id: "@squad",
|
|
143
|
+
jira_jql: 'project = ET AND statusCategory = "In Progress" AND duedate < now()',
|
|
144
|
+
remind_date: %w[Monday Tuesday Wednesday Thursday Friday]
|
|
145
|
+
)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Omit `jira_jql` to use the default query: in-progress, non-epic issues past their due date.
|
|
149
|
+
|
|
150
|
+
## CLI commands
|
|
151
|
+
|
|
152
|
+
The gem ships two executables, meant for cron jobs:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
pr-reminder # send the PR digest for every configured team
|
|
156
|
+
pr-reminder --dry-run # log the messages without posting to Slack
|
|
157
|
+
pr-reminder --config path.json
|
|
158
|
+
|
|
159
|
+
jira-overdue-reminder # send overdue Jira alerts for every configured team
|
|
160
|
+
jira-overdue-reminder --dry-run
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Both read `review_request_config.json` from the working directory by default, and append logs to `pr_reminder.log` or `jira_overdue_reminder.log`. They exit with `1` if any team failed.
|
|
164
|
+
|
|
165
|
+
Config file for `pr-reminder`:
|
|
166
|
+
|
|
167
|
+
```json
|
|
168
|
+
{
|
|
169
|
+
"repositories": [
|
|
170
|
+
{ "url": "https://github.com/org/repo", "base_branch": "main" }
|
|
171
|
+
],
|
|
172
|
+
"team_reminder_mapping": [
|
|
173
|
+
{
|
|
174
|
+
"channel_id": "C123456",
|
|
175
|
+
"slack_group_id": "@squad",
|
|
176
|
+
"github_team": "my-team",
|
|
177
|
+
"max_age_pr_days": 60,
|
|
178
|
+
"remind_date": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
|
|
179
|
+
}
|
|
180
|
+
]
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Config file for `jira-overdue-reminder`:
|
|
185
|
+
|
|
186
|
+
```json
|
|
187
|
+
{
|
|
188
|
+
"jira_team_reminder_mapping": [
|
|
189
|
+
{
|
|
190
|
+
"name": "Squad A",
|
|
191
|
+
"channel_id": "C123456",
|
|
192
|
+
"slack_group_id": "@squad",
|
|
193
|
+
"jira_jql": "project = ET AND statusCategory = \"In Progress\" AND duedate < now()",
|
|
194
|
+
"remind_date": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
|
|
195
|
+
}
|
|
196
|
+
]
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
## Logging
|
|
201
|
+
|
|
202
|
+
The gem logs through `ReviewRequest.logger`, which defaults to warnings on stderr. Set your own logger in an application:
|
|
203
|
+
|
|
204
|
+
```ruby
|
|
205
|
+
ReviewRequest.logger = Logger.new($stdout, level: :info)
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
## Differences from the Python package
|
|
209
|
+
|
|
210
|
+
The behaviour matches the Python package unless listed here:
|
|
211
|
+
|
|
212
|
+
- **Review status.** PR lines report the real review state (`Approved`, `Changes requested`, or `Waiting for review`) from each reviewer's latest review. The Python package always reported `Waiting for review`, because it read a field that the GitHub list endpoint does not return.
|
|
213
|
+
- **Sprint webhooks.** Only `sprint_closed` events are posted, as the Python README describes. The Python code did not check the event name.
|
|
214
|
+
- **Retries.** Transient failures (network errors, HTTP 5xx, HTTP 429, Slack `ratelimited`) are retried three times with exponential back-off. Other errors, such as GitHub 404s, fail immediately.
|
|
215
|
+
- **Slack usergroup lookup.** If the usergroup lookup fails, review requests still post, using plain reviewer names.
|
|
216
|
+
- **Open PR listing.** Requests ask for up to 100 PRs per page. The Python package fetched only the first page of 30.
|
|
217
|
+
- **Scheduling.** `--scheduled` times are read as Asia/Bangkok time using a fixed UTC+7 offset, which is exact because Bangkok has no daylight saving time.
|
|
218
|
+
- **Reminder text.** The reminder header no longer shows a doubled `!!` after the team mention.
|
|
219
|
+
- **Sequential calls.** Multiple PRs and channels are handled one at a time rather than concurrently. Errors do not stop the remaining items.
|
|
220
|
+
|
|
221
|
+
## Development
|
|
222
|
+
|
|
223
|
+
```bash
|
|
224
|
+
bundle install
|
|
225
|
+
bundle exec rake # tests and RuboCop (the default task)
|
|
226
|
+
bundle exec rake test # tests only
|
|
227
|
+
bundle exec rubocop # lint only
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
Tests use Minitest and WebMock. Real network calls are blocked, and retry back-off is disabled.
|
|
231
|
+
|
|
232
|
+
CI runs on every pull request when it is opened, marked ready for review, or reopened. It runs the tests and RuboCop on Ruby 3.2, 3.3, 3.4, and 4.0. See `.github/workflows/ci.yml`.
|
|
233
|
+
|
|
234
|
+
## Releasing
|
|
235
|
+
|
|
236
|
+
Bump `ReviewRequest::VERSION` in `lib/review_request/version.rb`, then run `bundle exec rake release`. That tags the commit, pushes the tag, and publishes to RubyGems.
|
|
237
|
+
|
|
238
|
+
## License
|
|
239
|
+
|
|
240
|
+
MIT. See [LICENSE](LICENSE).
|
data/exe/pr-reminder
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ReviewRequest
|
|
4
|
+
# Thread-safe in-memory cache with per-entry TTL and a maximum size.
|
|
5
|
+
# When full, the oldest entry is evicted first.
|
|
6
|
+
class Cache
|
|
7
|
+
Entry = Struct.new(:value, :expires_at)
|
|
8
|
+
|
|
9
|
+
def initialize(max_size: 100, ttl: 300, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
|
|
10
|
+
raise ArgumentError, "max_size must be at least 1" if max_size < 1
|
|
11
|
+
|
|
12
|
+
@max_size = max_size
|
|
13
|
+
@ttl = ttl
|
|
14
|
+
@clock = clock
|
|
15
|
+
@store = {}
|
|
16
|
+
@mutex = Mutex.new
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def get(key)
|
|
20
|
+
@mutex.synchronize do
|
|
21
|
+
entry = @store[key]
|
|
22
|
+
next nil if entry.nil?
|
|
23
|
+
|
|
24
|
+
if entry.expires_at <= @clock.call
|
|
25
|
+
@store.delete(key)
|
|
26
|
+
next nil
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
entry.value
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def set(key, value)
|
|
34
|
+
@mutex.synchronize do
|
|
35
|
+
@store.delete(key)
|
|
36
|
+
prune_expired
|
|
37
|
+
@store.shift while @store.size >= @max_size
|
|
38
|
+
@store[key] = Entry.new(value, @clock.call + @ttl)
|
|
39
|
+
end
|
|
40
|
+
value
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def delete(key)
|
|
44
|
+
@mutex.synchronize { !@store.delete(key).nil? }
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def clear
|
|
48
|
+
@mutex.synchronize { @store.clear }
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def size
|
|
52
|
+
@mutex.synchronize do
|
|
53
|
+
prune_expired
|
|
54
|
+
@store.size
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
private
|
|
59
|
+
|
|
60
|
+
def prune_expired
|
|
61
|
+
now = @clock.call
|
|
62
|
+
@store.delete_if { |_key, entry| entry.expires_at <= now }
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "dotenv"
|
|
4
|
+
require "json"
|
|
5
|
+
require "logger"
|
|
6
|
+
require "optparse"
|
|
7
|
+
require_relative "../review_request"
|
|
8
|
+
|
|
9
|
+
module ReviewRequest
|
|
10
|
+
# Entry points for the `pr-reminder` and `jira-overdue-reminder` executables.
|
|
11
|
+
# Intended for cron jobs. Each `run` returns an exit status (0 = success).
|
|
12
|
+
module CLI
|
|
13
|
+
DEFAULT_CONFIG = "review_request_config.json"
|
|
14
|
+
|
|
15
|
+
# Writes to several IO objects at once, e.g. stdout and a log file.
|
|
16
|
+
class Tee
|
|
17
|
+
def initialize(*ios)
|
|
18
|
+
@ios = ios
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def write(*args)
|
|
22
|
+
@ios.each { |io| io.write(*args) }
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def close
|
|
26
|
+
@ios.each { |io| io.close unless io.equal?($stdout) }
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
module_function
|
|
31
|
+
|
|
32
|
+
def parse_options(argv)
|
|
33
|
+
options = { dry_run: false, config: DEFAULT_CONFIG }
|
|
34
|
+
OptionParser.new do |parser|
|
|
35
|
+
parser.banner = "Usage: #{File.basename($PROGRAM_NAME)} [--dry-run] [--config PATH]"
|
|
36
|
+
parser.on("--dry-run", "Show what would be sent without posting") { options[:dry_run] = true }
|
|
37
|
+
parser.on("--config PATH", "Path to JSON config file (default: #{DEFAULT_CONFIG})") do |path|
|
|
38
|
+
options[:config] = path
|
|
39
|
+
end
|
|
40
|
+
end.parse!(argv)
|
|
41
|
+
options
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def build_logger(name, log_file)
|
|
45
|
+
# The logger keeps this handle open for the whole run, so a block form doesn't fit here.
|
|
46
|
+
file = File.open(log_file, "a") # rubocop:disable Style/FileOpen
|
|
47
|
+
file.sync = true
|
|
48
|
+
logger = Logger.new(Tee.new($stdout, file), level: :info)
|
|
49
|
+
logger.formatter = proc do |severity, time, _progname, message|
|
|
50
|
+
"#{time.strftime("%Y-%m-%d %H:%M:%S")} - #{name} - #{severity} - #{message}\n"
|
|
51
|
+
end
|
|
52
|
+
logger
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def load_config(path)
|
|
56
|
+
unless File.exist?(path)
|
|
57
|
+
warn "Error: Config file not found: #{path}"
|
|
58
|
+
return nil
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
JSON.parse(File.read(path))
|
|
62
|
+
rescue JSON::ParserError => e
|
|
63
|
+
warn "Error: Invalid JSON in #{path}: #{e.message}"
|
|
64
|
+
nil
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Prints each validation error. Returns true when there are none.
|
|
68
|
+
def report_errors?(errors)
|
|
69
|
+
errors.each { |error| warn "Error: #{error}" }
|
|
70
|
+
errors.empty?
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# Runs the block for each team and returns a message for every team that failed.
|
|
74
|
+
def each_team(team_mapping, name_key, logger)
|
|
75
|
+
team_mapping.each_with_index.filter_map do |team, index|
|
|
76
|
+
name = team.fetch(name_key, "team_#{index}")
|
|
77
|
+
logger.info("Processing team: #{name}")
|
|
78
|
+
begin
|
|
79
|
+
yield(team) ? nil : "Failed to send reminder for #{name}"
|
|
80
|
+
rescue StandardError => e
|
|
81
|
+
"Error processing #{name}: #{e.message}"
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def log_summary(logger, label, total, failed)
|
|
87
|
+
logger.info("#{label}: teams processed: #{total}, successful: #{total - failed.size}, failed: #{failed.size}")
|
|
88
|
+
failed.each { |error| logger.error(" - #{error}") }
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
module CLI
|
|
93
|
+
# Sends the daily PR digest for every team in `team_reminder_mapping`.
|
|
94
|
+
class PRReminder
|
|
95
|
+
LOG_FILE = "pr_reminder.log"
|
|
96
|
+
|
|
97
|
+
def self.run(argv)
|
|
98
|
+
new.run(argv)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def run(argv)
|
|
102
|
+
options = CLI.parse_options(argv)
|
|
103
|
+
Dotenv.load
|
|
104
|
+
logger = CLI.build_logger("pr_reminder", LOG_FILE)
|
|
105
|
+
ReviewRequest.logger = logger
|
|
106
|
+
logger.info("Starting PR reminder script")
|
|
107
|
+
|
|
108
|
+
config = CLI.load_config(options[:config])
|
|
109
|
+
return 1 if config.nil? || !valid?(config)
|
|
110
|
+
|
|
111
|
+
team_mapping = config.fetch("team_reminder_mapping", [])
|
|
112
|
+
service = build_service(config)
|
|
113
|
+
failed = CLI.each_team(team_mapping, "github_team", logger) do |team|
|
|
114
|
+
service.send_reminder(team, dry_run: options[:dry_run])
|
|
115
|
+
end
|
|
116
|
+
CLI.log_summary(logger, "PR reminder", team_mapping.size, failed)
|
|
117
|
+
failed.empty? ? 0 : 1
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
private
|
|
121
|
+
|
|
122
|
+
def valid?(config)
|
|
123
|
+
errors = []
|
|
124
|
+
errors << "Missing GITHUB_TOKEN" if ENV["GITHUB_TOKEN"].to_s.empty?
|
|
125
|
+
errors << "Missing BOT_TOKEN" if ENV["BOT_TOKEN"].to_s.empty?
|
|
126
|
+
errors << "'repositories' is empty in config" if config.fetch("repositories", []).empty?
|
|
127
|
+
errors << "'team_reminder_mapping' is empty in config" if config.fetch("team_reminder_mapping", []).empty?
|
|
128
|
+
CLI.report_errors?(errors)
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def build_service(config)
|
|
132
|
+
PRReminderService.new(
|
|
133
|
+
github_token: ENV["GITHUB_TOKEN"].to_s,
|
|
134
|
+
slack_token: ENV["BOT_TOKEN"].to_s,
|
|
135
|
+
repositories: config.fetch("repositories", []),
|
|
136
|
+
app_url: ENV["APP_URL"].to_s
|
|
137
|
+
)
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# Sends overdue-issue alerts for every team in `jira_team_reminder_mapping`.
|
|
142
|
+
class JiraOverdueReminder
|
|
143
|
+
LOG_FILE = "jira_overdue_reminder.log"
|
|
144
|
+
|
|
145
|
+
def self.run(argv)
|
|
146
|
+
new.run(argv)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def run(argv)
|
|
150
|
+
options = CLI.parse_options(argv)
|
|
151
|
+
Dotenv.load
|
|
152
|
+
logger = CLI.build_logger("jira_overdue_reminder", LOG_FILE)
|
|
153
|
+
ReviewRequest.logger = logger
|
|
154
|
+
logger.info("Starting Jira overdue reminder script")
|
|
155
|
+
|
|
156
|
+
config = CLI.load_config(options[:config])
|
|
157
|
+
return 1 if config.nil?
|
|
158
|
+
|
|
159
|
+
team_mapping = config.fetch("jira_team_reminder_mapping", [])
|
|
160
|
+
errors = missing_env_errors
|
|
161
|
+
errors << "'jira_team_reminder_mapping' is empty in config" if team_mapping.empty?
|
|
162
|
+
return 1 unless CLI.report_errors?(errors)
|
|
163
|
+
|
|
164
|
+
service = JiraOverdueReminderService.new(
|
|
165
|
+
jira_site: ENV.fetch("JIRA_SITE", nil),
|
|
166
|
+
jira_email: ENV.fetch("JIRA_EMAIL", nil),
|
|
167
|
+
jira_api_token: ENV.fetch("JIRA_API_TOKEN", nil),
|
|
168
|
+
slack_token: ENV.fetch("BOT_TOKEN", nil),
|
|
169
|
+
app_url: ENV["APP_URL"].to_s
|
|
170
|
+
)
|
|
171
|
+
failed = CLI.each_team(team_mapping, "name", logger) do |team|
|
|
172
|
+
service.send_reminder(team, dry_run: options[:dry_run])
|
|
173
|
+
end
|
|
174
|
+
CLI.log_summary(logger, "Jira overdue reminder", team_mapping.size, failed)
|
|
175
|
+
failed.empty? ? 0 : 1
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
private
|
|
179
|
+
|
|
180
|
+
def missing_env_errors
|
|
181
|
+
%w[JIRA_SITE JIRA_EMAIL JIRA_API_TOKEN BOT_TOKEN].filter_map do |name|
|
|
182
|
+
"Missing #{name}" if ENV[name].to_s.empty?
|
|
183
|
+
end
|
|
184
|
+
end
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
end
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ReviewRequest
|
|
4
|
+
# Decides whether a scheduled reminder should run today (system local time).
|
|
5
|
+
module DateChecker
|
|
6
|
+
module_function
|
|
7
|
+
|
|
8
|
+
# An empty or nil list means "every day".
|
|
9
|
+
def should_send_reminder?(remind_dates, now: Time.now)
|
|
10
|
+
return true if remind_dates.nil? || remind_dates.empty?
|
|
11
|
+
|
|
12
|
+
today = now.strftime("%A")
|
|
13
|
+
remind_dates.any? { |day| day.to_s.casecmp?(today) }
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ReviewRequest
|
|
4
|
+
# Base class for every error raised by this gem.
|
|
5
|
+
class Error < StandardError; end
|
|
6
|
+
|
|
7
|
+
# Raised for bad user input, e.g. a Slack message without a valid PR URL.
|
|
8
|
+
# Safe to show to end users.
|
|
9
|
+
class InvalidInputError < Error; end
|
|
10
|
+
|
|
11
|
+
class PRReminderError < Error; end
|
|
12
|
+
|
|
13
|
+
class SprintNotificationError < Error; end
|
|
14
|
+
|
|
15
|
+
# Failure talking to an external API. `transient?` tells the retry helper
|
|
16
|
+
# whether trying again might succeed (network errors, 5xx, 429).
|
|
17
|
+
class APIError < Error
|
|
18
|
+
attr_reader :status, :code
|
|
19
|
+
|
|
20
|
+
def initialize(message = nil, status: nil, code: nil, transient: nil)
|
|
21
|
+
super(message)
|
|
22
|
+
@status = status
|
|
23
|
+
@code = code
|
|
24
|
+
@transient = transient
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def transient?
|
|
28
|
+
return @transient unless @transient.nil?
|
|
29
|
+
return true if status.nil?
|
|
30
|
+
|
|
31
|
+
status == 429 || status >= 500
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
class GitHubError < APIError; end
|
|
36
|
+
|
|
37
|
+
class JiraError < APIError; end
|
|
38
|
+
|
|
39
|
+
class SlackError < APIError
|
|
40
|
+
TRANSIENT_CODES = %w[ratelimited internal_error service_unavailable].freeze
|
|
41
|
+
|
|
42
|
+
def initialize(message = nil, status: 200, code: nil, transient: nil)
|
|
43
|
+
transient = TRANSIENT_CODES.include?(code) if transient.nil? && code
|
|
44
|
+
super
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
class ChannelNotFoundError < SlackError
|
|
49
|
+
def initialize(message = nil, status: 200, code: "channel_not_found")
|
|
50
|
+
super(message, status:, code:, transient: false)
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|