forked from quarkusio/quarkus-github-lottery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GitHubRepository.java
195 lines (170 loc) · 7.34 KB
/
GitHubRepository.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package io.quarkus.github.lottery.github;
import static io.quarkus.github.lottery.util.UncheckedIOFunction.uncheckedIO;
import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.kohsuke.github.GHDirection;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHIssueComment;
import org.kohsuke.github.GHIssueQueryBuilder;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import org.kohsuke.github.PagedIterable;
import io.quarkiverse.githubapp.ConfigFile;
import io.quarkiverse.githubapp.GitHubClientProvider;
import io.quarkiverse.githubapp.GitHubConfigFileProvider;
import io.quarkus.github.lottery.config.LotteryConfig;
import io.quarkus.logging.Log;
import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient;
/**
* A GitHub repository as viewed from a GitHub App installation.
*/
public class GitHubRepository implements AutoCloseable {
private final GitHubClientProvider clientProvider;
private final GitHubConfigFileProvider configFileProvider;
private final GitHubRepositoryRef ref;
private GitHub client;
private GHRepository repository;
private DynamicGraphQLClient graphQLClient;
public GitHubRepository(GitHubClientProvider clientProvider, GitHubConfigFileProvider configFileProvider,
GitHubRepositoryRef ref) {
this.clientProvider = clientProvider;
this.configFileProvider = configFileProvider;
this.ref = ref;
}
@Override
public void close() {
if (graphQLClient != null) {
try {
graphQLClient.close();
} catch (Exception e) {
Log.errorf(e, "Could not close GraphQL client");
}
}
}
public GitHubRepositoryRef ref() {
return ref;
}
public String selfLogin() {
return ref.installationRef().appName() + "[bot]";
}
private GitHub client() {
if (client == null) {
client = clientProvider.getInstallationClient(ref.installationRef().installationId());
}
return client;
}
private GHRepository repository() throws IOException {
if (repository == null) {
repository = client().getRepository(ref.repositoryName());
}
return repository;
}
private DynamicGraphQLClient graphQLClient() {
if (graphQLClient == null) {
graphQLClient = clientProvider.getInstallationGraphQLClient(ref.installationRef().installationId());
}
return graphQLClient;
}
public Optional<LotteryConfig> fetchLotteryConfig() throws IOException {
return configFileProvider.fetchConfigFile(repository(), LotteryConfig.FILE_NAME, ConfigFile.Source.DEFAULT,
LotteryConfig.class);
}
public Stream<Issue> issuesWithLabel(String label) throws IOException {
return toStream(repository().queryIssues().label(label)
.state(GHIssueState.OPEN)
.sort(GHIssueQueryBuilder.Sort.UPDATED)
.direction(GHDirection.DESC)
.list())
.map(ghIssue -> new Issue(ghIssue.getNumber(), ghIssue.getTitle(), ghIssue.getHtmlUrl()));
}
public void commentOnDedicatedIssue(String username, String topic, String markdownBody) throws IOException {
var existingIssue = getDedicatedIssue(username, topic);
GHIssue issue;
if (existingIssue.isPresent()) {
issue = existingIssue.get();
if (GHIssueState.CLOSED.equals(issue.getState())) {
issue.reopen();
}
try {
getLastAppComment(issue).ifPresent(this::minimizeOutdatedComment);
} catch (Exception e) {
Log.errorf(e, "Failed to minimize last notification for issue %s#%s", ref.repositoryName(), issue.getNumber());
}
} else {
issue = createDedicatedIssue(username, topic);
}
issue.comment(markdownBody);
}
public Stream<String> extractCommentsFromDedicatedIssue(String login, String topic, Instant since)
throws IOException {
return getDedicatedIssue(login, topic)
.map(uncheckedIO(issue -> getAppCommentsSince(issue, since)))
.orElse(Stream.of())
.map(GHIssueComment::getBody);
}
private Optional<GHIssue> getDedicatedIssue(String username, String topic) throws IOException {
for (var issue : repository().queryIssues().assignee(username).list()) {
if (issue.getTitle().equals(topic)) {
return Optional.of(issue);
}
}
return Optional.empty();
}
private GHIssue createDedicatedIssue(String username, String topic) throws IOException {
return repository().createIssue(topic)
.assignee(username)
.body("This issue is dedicated to " + topic + ".")
.create();
}
private Optional<GHIssueComment> getLastAppComment(GHIssue issue) throws IOException {
String selfLogin = selfLogin();
// TODO ideally we'd use the "since" API parameter to ignore
// older comments (e.g. 1+ year old) that are unlikely to be relevant
// (see 'since' in https://docs.github.com/en/rest/issues/comments#list-issue-comments)
// but that's not supported yet in the library we're using...
GHIssueComment lastNotificationComment = null;
for (GHIssueComment comment : issue.listComments()) {
if (selfLogin.equals(comment.getUser().getLogin())) {
lastNotificationComment = comment;
}
}
return Optional.ofNullable(lastNotificationComment);
}
private Stream<GHIssueComment> getAppCommentsSince(GHIssue issue, Instant since) throws IOException {
String selfLogin = selfLogin();
// TODO ideally we'd use the "since" API parameter to ignore older comments
// (see 'since' in https://docs.github.com/en/rest/issues/comments#list-issue-comments)
// but that's not supported yet in the library we're using...
return toStream(issue.listComments())
.filter(uncheckedIO((GHIssueComment comment) -> selfLogin.equals(comment.getUser().getLogin())
&& !comment.getCreatedAt().toInstant().isBefore(since))::apply);
}
private void minimizeOutdatedComment(GHIssueComment comment) {
try {
Map<String, Object> variables = new HashMap<>();
variables.put("subjectId", comment.getNodeId());
graphQLClient().executeSync("""
mutation MinimizeOutdatedContent($subjectId: ID!) {
minimizeComment(input: {
subjectId: $subjectId,
classifier: OUTDATED}) {
minimizedComment {
isMinimized
}
}
}
""", variables);
} catch (Exception e) {
throw new RuntimeException("Could not minimize comment " + comment.getNodeId(), e);
}
}
private <T> Stream<T> toStream(PagedIterable<T> iterable) {
return StreamSupport.stream(iterable.spliterator(), false);
}
}