Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): Add PseudoEnumArgument #305

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.7.0]
- Core: Added PseudoEnumArgument for simulating an enum argument with strings and a set of allowed values

## [1.6.1]

### Fixed
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ Snapshot builds of Cloud are available through the [Sonatype OSS Snapshot reposi
<dependency>
<groupId>cloud.commandframework</groupId>
<artifactId>cloud-PLATFORM</artifactId>
<version>1.6.1</version>
<version>1.7.0-SNAPSHOT</version>
</dependency>
<!--
~ Optional: Allows you to use annotated methods
Expand All @@ -126,7 +126,7 @@ Snapshot builds of Cloud are available through the [Sonatype OSS Snapshot reposi
<dependency>
<groupId>cloud.commandframework</groupId>
<artifactId>cloud-annotations</artifactId>
<version>1.6.1</version>
<version>1.7.0-SNAPSHOT</version>
</dependency>
```

Expand Down Expand Up @@ -187,7 +187,7 @@ repositories {

```kotlin
dependencies {
implementation("cloud.commandframework", "cloud-PLATFORM", "1.6.1")
implementation("cloud.commandframework", "cloud-PLATFORM", "1.7.0-SNAPSHOT")
}
```

Expand Down
2 changes: 1 addition & 1 deletion build-logic/src/main/kotlin/Versions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ object Versions {
const val adventureApi = "4.9.3"
const val adventurePlatform = "4.0.1"
const val paperApi = "1.16.5-R0.1-SNAPSHOT"
const val velocityApi = "1.1.0"
const val velocityApi = "3.1.0"
const val spongeApi7 = "7.3.0"
const val jetbrainsAnnotations = "23.0.0"
const val guava = "21.0-jre"
Expand Down
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ plugins {
}

group = "cloud.commandframework"
version = "1.6.1"
version = "1.7.0-SNAPSHOT"
description = "Command framework and dispatcher for the JVM"

subprojects {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import cloud.commandframework.arguments.standard.ByteArgument;
import cloud.commandframework.arguments.standard.CharArgument;
import cloud.commandframework.arguments.standard.DoubleArgument;
import cloud.commandframework.arguments.standard.DurationArgument;
import cloud.commandframework.arguments.standard.EnumArgument;
import cloud.commandframework.arguments.standard.FloatArgument;
import cloud.commandframework.arguments.standard.IntegerArgument;
Expand All @@ -43,6 +44,7 @@
import io.leangen.geantyref.GenericTypeReflector;
import io.leangen.geantyref.TypeToken;
import java.lang.annotation.Annotation;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
Expand Down Expand Up @@ -163,6 +165,7 @@ public StandardParserRegistry() {
return new BooleanArgument.BooleanParser<>(liberal);
});
this.registerParserSupplier(TypeToken.get(UUID.class), options -> new UUIDArgument.UUIDParser<>());
this.registerParserSupplier(TypeToken.get(Duration.class), options -> new DurationArgument.DurationParser<>());
}

private static boolean isPrimitive(final @NonNull TypeToken<?> type) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,287 @@
//
// MIT License
//
// Copyright (c) 2021 Alexander Söderberg & Contributors
//
// 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.arguments.standard;

import cloud.commandframework.ArgumentDescription;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.parser.ArgumentParseResult;
import cloud.commandframework.arguments.parser.ArgumentParser;
import cloud.commandframework.captions.CaptionVariable;
import cloud.commandframework.captions.StandardCaptionKeys;
import cloud.commandframework.context.CommandContext;
import cloud.commandframework.exceptions.parsing.NoInputProvidedException;
import cloud.commandframework.exceptions.parsing.ParserException;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Queue;
import java.util.function.BiFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;


/**
* Parses <code>java.time.Duration</code> from a <code>1d2h3m4s</code> format.
* @param <C> Command sender type
* @since 1.7.0
*/
@SuppressWarnings("unused")
public final class DurationArgument<C> extends CommandArgument<C, Duration> {

/**
* Matches durations in the format of: <code>2d15h7m12s</code>
*/
private static final Pattern DURATION_PATTERN = Pattern.compile("(([1-9][0-9]+|[1-9])[dhms])");

private DurationArgument(
final boolean required,
final @NonNull String name,
final @NonNull String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider,
final @NonNull ArgumentDescription defaultDescription
) {
super(
required,
name,
new DurationArgument.DurationParser<>(),
defaultValue,
Duration.class,
suggestionsProvider,
defaultDescription
);
}

/**
* Create a new builder
*
* @param name Name of the component
* @param <C> Command sender type
* @return Created builder
* @since 1.7.0
*/
public static <C> @NonNull Builder<C> newBuilder(final @NonNull String name) {
return new Builder<>(name);
}

/**
* Create a new required command component
*
* @param name Component name
* @param <C> Command sender type
* @return Created component
* @since 1.7.0
*/
public static <C> @NonNull CommandArgument<C, Duration> of(final @NonNull String name) {
return DurationArgument.<C>newBuilder(name).asRequired().build();
}

/**
* Create a new optional command component
*
* @param name Component name
* @param <C> Command sender type
* @return Created component
* @since 1.7.0
*/
public static <C> @NonNull CommandArgument<C, Duration> optional(final @NonNull String name) {
return DurationArgument.<C>newBuilder(name).asOptional().build();
}

/**
* Create a new required command component with a default value
*
* @param name Component name
* @param defaultDuration Default duration
* @param <C> Command sender type
* @return Created component
* @since 1.7.0
*/
public static <C> @NonNull CommandArgument<C, Duration> optional(
final @NonNull String name,
final @NonNull String defaultDuration
) {
return DurationArgument.<C>newBuilder(name).asOptionalWithDefault(defaultDuration).build();
}


public static final class Builder<C> extends CommandArgument.Builder<C, Duration> {

private Builder(final @NonNull String name) {
super(Duration.class, name);
}

/**
* Builder a new boolean component
*
* @return Constructed component
* @since 1.7.0
*/
@Override
public @NonNull DurationArgument<C> build() {
return new DurationArgument<>(this.isRequired(), this.getName(), this.getDefaultValue(),
this.getSuggestionsProvider(), this.getDefaultDescription()
);
}

}


/**
* Represents a duration parser.
* @since 1.7.0
* @param <C> Command sender type
*/
public static final class DurationParser<C> implements ArgumentParser<C, Duration> {

@Override
public @NonNull ArgumentParseResult<Duration> parse(
final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<String> inputQueue
) {
final String input = inputQueue.peek();
if (input == null) {
return ArgumentParseResult.failure(new NoInputProvidedException(
DurationArgument.DurationParseException.class,
commandContext
));
}

final Matcher matcher = DURATION_PATTERN.matcher(input);

Duration duration = Duration.ofNanos(0);

while (matcher.find()) {
String group = matcher.group();
String timeUnit = String.valueOf(group.charAt(group.length() - 1));
int timeValue = Integer.parseInt(group.substring(0, group.length() - 1));
switch (timeUnit) {
case "d":
duration = duration.plusDays(timeValue);
break;
case "h":
duration = duration.plusHours(timeValue);
break;
case "m":
duration = duration.plusMinutes(timeValue);
break;
case "s":
duration = duration.plusSeconds(timeValue);
break;
default:
return ArgumentParseResult.failure(new DurationArgument.DurationParseException(input, commandContext));
}
}

if (duration.isZero()) {
return ArgumentParseResult.failure(new DurationArgument.DurationParseException(input, commandContext));
}

inputQueue.remove();
return ArgumentParseResult.success(duration);
}

/**
* Provides suggestions for Durations.
* @since 1.7.0
*/
@Override
@SuppressWarnings("MixedMutabilityReturnType")
public @NonNull List<@NonNull String> suggestions(
final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
char[] chars = input.toLowerCase(Locale.ROOT).toCharArray();

if (chars.length == 0) {
return IntStream.range(1, 10).boxed()
.sorted()
.map(String::valueOf)
.collect(Collectors.toList());
}

char last = chars[chars.length - 1];

// 1d_, 5d4m_, etc
if (Character.isLetter(last)) {
return Collections.emptyList();
}

// 1d5_, 5d4m2_, etc
return Stream.of("d", "h", "m", "s")
.filter(unit -> !input.contains(unit))
.map(unit -> input + unit)
.collect(Collectors.toList());
}

}

/**
* Represents a duration parse exception.
* @since 1.7.0
*/
public static final class DurationParseException extends ParserException {

private static final long serialVersionUID = 7632293268451349508L;
private final String input;

/**
* Construct a new Duration parse exception
*
* @param input String input
* @param context Command context
* @since 1.7.0
*/
public DurationParseException(
final @NonNull String input,
final @NonNull CommandContext<?> context
) {
super(
DurationArgument.DurationParser.class,
context,
StandardCaptionKeys.ARGUMENT_PARSE_FAILURE_DURATION,
CaptionVariable.of("input", input)
);
this.input = input;
}

/**
* Get the supplied input
*
* @return String value
* @since 1.7.0
*/
public @NonNull String getInput() {
return this.input;
}

}

}
Loading