Skip to content

Commit

Permalink
Make CommandSuggestionProcessors operate on a stream (#600)
Browse files Browse the repository at this point in the history
* Make CommandSuggestionProcessors operate on a stream

this allows filter/sort/limit without collecting multiple times

* Don't re-collect with a pass-through processor

* Add CommandSuggestionProcessor chaining utilities

* Update cloud-core/src/main/java/cloud/commandframework/execution/FilteringCommandSuggestionProcessor.java

Co-authored-by: Alexander Söderberg <[email protected]>

* spotlessApply

---------

Co-authored-by: Alexander Söderberg <[email protected]>
  • Loading branch information
jpenilla and Citymonstret authored Jan 10, 2024
1 parent fd46c83 commit c5329b7
Show file tree
Hide file tree
Showing 5 changed files with 136 additions and 29 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//
// MIT License
//
// Copyright (c) 2024 Incendo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
package cloud.commandframework.execution;

import cloud.commandframework.arguments.suggestion.Suggestion;
import cloud.commandframework.execution.preprocessor.CommandPreprocessingContext;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.apiguardian.api.API;
import org.checkerframework.checker.nullness.qual.NonNull;

@API(status = API.Status.INTERNAL)
final class ChainedCommandSuggestionProcessor<C> implements CommandSuggestionProcessor<C> {

private final List<CommandSuggestionProcessor<C>> links;

/**
* Creates a chained processor from the provided processors. Chained processors will be
* recursively flattened.
*
* @param links processors to chain
*/
ChainedCommandSuggestionProcessor(final List<CommandSuggestionProcessor<C>> links) {
final List<CommandSuggestionProcessor<C>> list = new ArrayList<>();
flattenChain(list, links);
this.links = Collections.unmodifiableList(list);
}

private static <C> void flattenChain(
final @NonNull List<CommandSuggestionProcessor<C>> into,
final @NonNull Collection<CommandSuggestionProcessor<C>> links
) {
for (final CommandSuggestionProcessor<C> link : links) {
if (link instanceof ChainedCommandSuggestionProcessor) {
flattenChain(into, ((ChainedCommandSuggestionProcessor<C>) link).links);
} else {
into.add(link);
}
}
}

@Override
public @NonNull Stream<@NonNull Suggestion> process(
final @NonNull CommandPreprocessingContext<C> context,
final @NonNull Stream<@NonNull Suggestion> suggestions
) {
Stream<Suggestion> currentLink = suggestions;
for (final CommandSuggestionProcessor<C> link : this.links) {
currentLink = link.process(context, currentLink);
}
return currentLink;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@

import cloud.commandframework.arguments.suggestion.Suggestion;
import cloud.commandframework.execution.preprocessor.CommandPreprocessingContext;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Stream;
import org.apiguardian.api.API;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
* Processor that formats command suggestions
* Processor that operates on the {@link Stream stream} of {@link Suggestion suggestions} before it is collected
* for the suggestion result passed to platform implementations or other callers.
*
* @param <C> command sender type
* @since 2.0.0
Expand All @@ -40,23 +43,36 @@
public interface CommandSuggestionProcessor<C> {

/**
* Creates a {@link CommandSuggestionProcessor} that simply returns the input suggestion.
* Creates a {@link CommandSuggestionProcessor} that simply returns the input suggestions.
*
* @param <C> command sender type
* @return the processor
*/
static <C> @NonNull CommandSuggestionProcessor<C> passThrough() {
return (ctx, suggestion) -> suggestion;
return (ctx, suggestions) -> suggestions;
}

/**
* Processes the given {@code suggestion} and returns the result.
* Adds operations to the {@link Suggestion suggestions} {@link Stream stream} and returns the result.
*
* <p>If {@code null} is returned, the suggestion will be dropped.</p>
* @param context command preprocessing context which can be used to access the command context and command input
* @param suggestions the suggestions to process
* @return the processed suggestions
*/
@NonNull Stream<@NonNull Suggestion> process(
@NonNull CommandPreprocessingContext<C> context,
@NonNull Stream<@NonNull Suggestion> suggestions
);

/**
* Create a chained {@link CommandSuggestionProcessor processor} that invokes {@code this} processor and then the
* {@code nextProcessor} with the result.
*
* @param context command preprocessing context which can be used to access the command context and command input
* @param suggestion the suggestion to process
* @return the processed suggestion, or {@code null}
* @param nextProcessor next suggestion processor
* @return chained processor
*/
@Nullable Suggestion process(@NonNull CommandPreprocessingContext<C> context, @NonNull Suggestion suggestion);
default @NonNull CommandSuggestionProcessor<C> and(final @NonNull CommandSuggestionProcessor<C> nextProcessor) {
Objects.requireNonNull(nextProcessor, "nextProcessor");
return new ChainedCommandSuggestionProcessor<>(Arrays.asList(this, nextProcessor));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.stream.Stream;
import org.apiguardian.api.API;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
Expand All @@ -39,7 +41,7 @@
* Command suggestion processor filters suggestions based on the remaining unconsumed input in the
* queue.
*
* @param <C> Command sender type
* @param <C> command sender type
*/
@API(status = API.Status.STABLE)
public final class FilteringCommandSuggestionProcessor<C> implements CommandSuggestionProcessor<C> {
Expand Down Expand Up @@ -67,27 +69,29 @@ public FilteringCommandSuggestionProcessor(final @NonNull Filter<C> filter) {
}

@Override
public @Nullable Suggestion process(
public @NonNull Stream<@NonNull Suggestion> process(
final @NonNull CommandPreprocessingContext<C> context,
final @NonNull Suggestion suggestion
final @NonNull Stream<@NonNull Suggestion> suggestions
) {
final String input;
if (context.commandInput().isEmpty(true /* ignoreWhitespace */)) {
input = "";
} else {
input = context.commandInput().skipWhitespace().remainingInput();
}
final String filtered = this.filter.filter(context, suggestion.suggestion(), input);
if (filtered == null) {
return null;
}
return suggestion.withSuggestion(filtered);
return suggestions.map(suggestion -> {
final String filtered = this.filter.filter(context, suggestion.suggestion(), input);
if (filtered == null) {
return null;
}
return suggestion.withSuggestion(filtered);
}).filter(Objects::nonNull);
}

/**
* Filter function that tests (and potentially changes) each suggestion against the input and context.
*
* @param <C> sender type
* @param <C> command sender type
* @since 1.8.0
*/
@API(status = API.Status.STABLE, since = "1.8.0")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apiguardian.api.API;
import org.checkerframework.checker.nullness.qual.NonNull;

Expand Down Expand Up @@ -65,7 +68,17 @@ public SuggestionContext(
* @return list of suggestions
*/
public @NonNull List<@NonNull Suggestion> suggestions() {
return Collections.unmodifiableList(this.suggestions);
final Stream<Suggestion> stream = this.suggestions.stream();
final Stream<Suggestion> processedStream = this.processor.process(this.preprocessingContext, stream);
if (stream == processedStream) {
// don't re-collect with a pass-through processor
return Collections.unmodifiableList(this.suggestions);
}
return Collections.unmodifiableList(
processedStream
.peek(obj -> Objects.requireNonNull(obj, "suggestion"))
.collect(Collectors.toList())
);
}

/**
Expand All @@ -92,10 +105,7 @@ public void addSuggestions(final @NonNull Iterable<@NonNull Suggestion> suggesti
* @param suggestion the suggestion to add
*/
public void addSuggestion(final @NonNull Suggestion suggestion) {
final Suggestion result = this.processor.process(this.preprocessingContext, suggestion);
if (result == null) {
return;
}
this.suggestions.add(result);
Objects.requireNonNull(suggestion, "suggestion");
this.suggestions.add(suggestion);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ void setup() {
@Test
void testModifying() {
// Arrange
this.commandManager.commandSuggestionProcessor((ctx, suggestion) -> suggestion.withSuggestion(
String.format("test-%s", suggestion.suggestion()))
);
this.commandManager.commandSuggestionProcessor((ctx, suggestions) -> suggestions.map(s -> s.withSuggestion(
String.format("test-%s", s.suggestion()))
));
this.commandManager.command(
this.commandManager.commandBuilder("test").required(
"arg",
Expand All @@ -71,7 +71,7 @@ void testModifying() {
@Test
void testFiltering() {
// Arrange
this.commandManager.commandSuggestionProcessor((ctx, suggestion) -> null);
this.commandManager.commandSuggestionProcessor((ctx, suggestions) -> suggestions.limit(0));
this.commandManager.command(
this.commandManager.commandBuilder("test").required(
"arg",
Expand Down

0 comments on commit c5329b7

Please sign in to comment.