forked from quarkiverse/quarkus-github-app
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AbstractCommandDispatcher.java
270 lines (213 loc) · 10.2 KB
/
AbstractCommandDispatcher.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package io.quarkiverse.githubapp.command.airline.runtime;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.jboss.logging.Logger;
import org.kohsuke.github.GHEventPayload;
import org.kohsuke.github.GHEventPayload.IssueComment;
import org.kohsuke.github.GHReaction;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHTeam;
import org.kohsuke.github.GHUser;
import org.kohsuke.github.ReactionContent;
import com.github.rvesse.airline.Cli;
import com.github.rvesse.airline.builder.ParserBuilder;
import com.github.rvesse.airline.help.Help;
import com.github.rvesse.airline.model.MetadataLoader;
import com.github.rvesse.airline.parser.ParseResult;
import com.github.rvesse.airline.parser.errors.ParseException;
import com.github.rvesse.airline.parser.errors.handlers.CollectAll;
import io.quarkiverse.githubapp.command.airline.runtime.util.Commandline;
import io.quarkiverse.githubapp.command.airline.runtime.util.Reactions;
import io.quarkus.arc.ClientProxy;
import io.quarkus.arc.Subclass;
public abstract class AbstractCommandDispatcher<C> {
private static final Logger LOGGER = Logger.getLogger(AbstractCommandDispatcher.class);
private final Cli<C> cli;
private final CliConfig cliConfig;
private final Map<String, CommandConfig> commandConfigs;
private final Map<String, CommandPermissionConfig> commandPermissionConfigs;
private final Map<String, CommandTeamConfig> commandTeamConfigs;
protected AbstractCommandDispatcher(Class<?> cliClass, CliConfig cliConfig) {
ParserBuilder<C> parserBuilder = new ParserBuilder<C>();
parserBuilder.withCommandFactory(new ArcCommandFactory<>());
parserBuilder.withErrorHandler(new CollectAll());
this.cli = new Cli<>(MetadataLoader.loadGlobal(cliClass, parserBuilder.build()));
this.cliConfig = cliConfig;
this.commandConfigs = getCommandConfigs();
this.commandPermissionConfigs = getCommandPermissionConfigs();
this.commandTeamConfigs = getCommandTeamConfigs();
}
protected abstract Map<String, CommandConfig> getCommandConfigs();
protected abstract Map<String, CommandPermissionConfig> getCommandPermissionConfigs();
protected abstract Map<String, CommandTeamConfig> getCommandTeamConfigs();
protected Optional<CommandExecutionContext<C>> getCommand(GHEventPayload.IssueComment issueCommentPayload) {
String body = issueCommentPayload.getComment().getBody();
if (body == null || body.isBlank()) {
return Optional.empty();
}
Optional<String> firstLineOptional = body.trim().lines().findFirst();
if (firstLineOptional.isEmpty() || firstLineOptional.get().isBlank()) {
return Optional.empty();
}
String firstLine = firstLineOptional.get().trim();
List<String> commandLine = Commandline.translateCommandline(firstLine);
String cliName = commandLine.remove(0);
if (!matches(cliName)) {
return Optional.empty();
}
ParseResult<C> parseResult = cli.parseWithResult(commandLine);
if (parseResult.wasSuccessful()) {
String commandClassName = normalizeCommandClass(parseResult.getCommand().getClass()).getName();
CommandConfig commandConfig = commandConfigs.getOrDefault(commandClassName,
cliConfig.getDefaultCommandConfig());
if (!commandConfig.getScope().isInScope(issueCommentPayload.getIssue().isPullRequest())) {
return Optional.empty();
}
CommandPermissionConfig commandPermissionConfig = commandPermissionConfigs.getOrDefault(commandClassName,
cliConfig.getDefaultCommandPermissionConfig());
CommandTeamConfig commandTeamConfig = commandTeamConfigs.getOrDefault(commandClassName,
cliConfig.getDefaultCommandTeamConfig());
if (!hasPermission(commandPermissionConfig, commandTeamConfig, issueCommentPayload.getRepository(),
issueCommentPayload.getSender())) {
Reactions.createReaction(issueCommentPayload, ReactionContent.MINUS_ONE);
return Optional.empty();
}
GHReaction ackReaction = Reactions.createReaction(issueCommentPayload, ReactionContent.ROCKET);
return Optional.of(new CommandExecutionContext<>(firstLine, parseResult.getCommand(), commandConfig, ackReaction));
}
Reactions.createReaction(issueCommentPayload, ReactionContent.CONFUSED);
handleParseError(issueCommentPayload, firstLine, commandLine, parseResult);
return Optional.empty();
}
private static Class<?> normalizeCommandClass(Class<?> commandClass) {
if (Subclass.class.isAssignableFrom(commandClass)) {
return commandClass.getSuperclass();
}
if (ClientProxy.class.isAssignableFrom(commandClass)) {
return commandClass.getSuperclass();
}
return commandClass;
}
private boolean matches(String cli) {
for (String alias : cliConfig.getAliases()) {
if (alias.equals(cli)) {
return true;
}
}
return false;
}
private boolean hasPermission(CommandPermissionConfig commandPermissionConfig,
CommandTeamConfig commandTeamConfig,
GHRepository repository, GHUser user) {
try {
if (commandPermissionConfig.getPermission() != null) {
if (user == null) {
return false;
}
if (!repository.hasPermission(user, commandPermissionConfig.getPermission())) {
return false;
}
}
if (!commandTeamConfig.getTeams().isEmpty()) {
if (user == null) {
return false;
}
List<GHTeam> matchingTeams = repository.getTeams().stream()
.filter(t -> commandTeamConfig.getTeams().contains(t.getSlug()))
.collect(Collectors.toList());
for (GHTeam matchingTeam : matchingTeams) {
if (matchingTeam.hasMember(user)) {
return true;
}
}
return false;
}
return true;
} catch (IOException e) {
throw new CommandExecutionException("Unable to check the permissions for the command", e);
}
}
private void handleParseError(IssueComment issueCommentPayload, String command, List<String> commandLine,
ParseResult<C> parseResult) {
if (!cliConfig.getParseErrorStrategy().addMessage()) {
return;
}
StringBuilder message = new StringBuilder();
message.append(String.format(cliConfig.getParseErrorMessage(), command));
if (cliConfig.getParseErrorStrategy().includeErrors()) {
message.append("\n\nErrors:\n\n");
for (ParseException error : parseResult.getErrors()) {
message.append("- " + error.getMessage());
}
}
if (cliConfig.getParseErrorStrategy().includeHelp()) {
try {
ByteArrayOutputStream helpOs = new ByteArrayOutputStream();
if (parseResult.getState().getCommand() != null) {
Help.help(parseResult.getState().getCommand(), helpOs);
} else {
Help.help(cli.getMetadata(), Collections.emptyList(), helpOs);
}
String help = helpOs.toString(StandardCharsets.UTF_8);
if (!help.isBlank()) {
message.append("\n\nHelp:\n\n").append("```\n" + help.trim() + "\n```");
}
} catch (IOException e) {
LOGGER.warn("Error trying to generate help for command `" + command + "` in "
+ issueCommentPayload.getRepository().getFullName() + "#" + issueCommentPayload.getIssue().getNumber(),
e);
}
}
try {
issueCommentPayload.getIssue().comment(message.toString());
} catch (Exception e) {
LOGGER.warn("Error trying to add command parse error comment for command `" + command + "` in "
+ issueCommentPayload.getRepository().getFullName() + "#" + issueCommentPayload.getIssue().getNumber(), e);
}
}
protected void handleExecutionError(GHEventPayload.IssueComment issueCommentPayload,
CommandExecutionContext<C> commandExecutionContext) {
CommandConfig commandConfig = commandExecutionContext.getCommandConfig();
String commandLine = commandExecutionContext.getCommandLine();
if (!commandConfig.getExecutionErrorStrategy().addMessage()) {
return;
}
try {
issueCommentPayload.getIssue()
.comment(String.format(commandConfig.getExecutionErrorMessage(), commandLine));
} catch (Exception e) {
LOGGER.warn("Error trying to add command execution error comment for command `" + commandLine + "` in "
+ issueCommentPayload.getRepository().getFullName() + "#" + issueCommentPayload.getIssue().getNumber(), e);
}
}
public static class CommandExecutionContext<C> {
private final String commandLine;
private final C command;
private final GHReaction ackReaction;
private final CommandConfig commandConfig;
public CommandExecutionContext(String commandLine, C command, CommandConfig commandConfig, GHReaction ackReaction) {
this.commandLine = commandLine;
this.command = command;
this.commandConfig = commandConfig;
this.ackReaction = ackReaction;
}
public String getCommandLine() {
return commandLine;
}
public C getCommand() {
return command;
}
public CommandConfig getCommandConfig() {
return commandConfig;
}
public GHReaction getAckReaction() {
return ackReaction;
}
}
}