Skip to content

Commit a72c76e

Browse files
committed
Add ability to specify argument arity for multi-valued input
Resolves #1263
1 parent 63a938f commit a72c76e

File tree

6 files changed

+191
-76
lines changed

6 files changed

+191
-76
lines changed

spring-shell-core/src/main/java/org/springframework/shell/core/command/adapter/MethodInvokerCommandAdapter.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ private List<Object> prepareArguments(CommandContext commandContext) {
117117
List<Object> args = new ArrayList<>();
118118
Parameter[] parameters = this.method.getParameters();
119119
Class<?>[] parameterTypes = this.method.getParameterTypes();
120+
int processedArgumentsCount = 0;
120121
for (int i = 0; i < parameters.length; i++) {
121122
// Handle CommandContext injection
122123
if (parameterTypes[i].equals(CommandContext.class)) {
@@ -192,21 +193,26 @@ private List<Object> prepareArguments(CommandContext commandContext) {
192193
Class<?> parameterType = parameterTypes[i];
193194
Object value = this.conversionService.convert(rawValue, parameterType);
194195
args.add(value);
196+
processedArgumentsCount++;
195197
continue;
196198
}
197199
// Handle Arguments list injection
198200
Arguments argumentsAnnotation = parameters[i].getAnnotation(Arguments.class);
199201
if (argumentsAnnotation != null) {
200202
log.debug("Processing arguments for parameter: " + parameters[i].getName());
203+
int arity = argumentsAnnotation.arity();
201204
List<String> rawValues = commandContext.parsedInput()
202205
.arguments()
203206
.stream()
207+
.skip(processedArgumentsCount)
208+
.limit(arity)
204209
.map(CommandArgument::value)
205210
.toList();
206211
Class<?> parameterType = parameterTypes[i];
207212
// TODO check for collection types
208213
Object value = this.conversionService.convert(rawValues, parameterType);
209214
args.add(value);
215+
processedArgumentsCount += rawValues.size();
210216
}
211217

212218
}

spring-shell-core/src/main/java/org/springframework/shell/core/command/annotation/Arguments.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,12 @@
3333
@Documented
3434
public @interface Arguments {
3535

36+
/**
37+
* Define the maximum number of arguments to be collected. By default, all remaining
38+
* arguments are collected.
39+
* @return the maximum number of arguments to be collected
40+
* @since 4.0.2
41+
*/
42+
int arity() default Integer.MAX_VALUE;
43+
3644
}

spring-shell-core/src/test/java/org/springframework/shell/core/command/adapter/MethodInvokerCommandAdapterDefaultValueTests.java

Lines changed: 0 additions & 72 deletions
This file was deleted.
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/*
2+
* Copyright 2025-present the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.shell.core.command.adapter;
17+
18+
import java.io.PrintWriter;
19+
import java.io.StringWriter;
20+
import java.lang.reflect.Method;
21+
22+
import jakarta.validation.Validation;
23+
import jakarta.validation.Validator;
24+
import org.junit.jupiter.api.Test;
25+
import org.mockito.Mockito;
26+
27+
import org.springframework.core.convert.support.DefaultConversionService;
28+
import org.springframework.shell.core.command.CommandArgument;
29+
import org.springframework.shell.core.command.CommandContext;
30+
import org.springframework.shell.core.command.CommandOption;
31+
import org.springframework.shell.core.command.ExitStatus;
32+
import org.springframework.shell.core.command.annotation.Arguments;
33+
import org.springframework.shell.core.command.annotation.Command;
34+
import org.springframework.shell.core.command.annotation.Option;
35+
36+
import static org.assertj.core.api.Assertions.assertThat;
37+
38+
/**
39+
* @author Andrey Litvitski
40+
* @author Mahmoud Ben Hassine
41+
*/
42+
class MethodInvokerCommandAdapterTests {
43+
44+
static class Target {
45+
46+
int seen;
47+
48+
public void run(@Option(longName = "retries", defaultValue = "3") int retries) {
49+
this.seen = retries;
50+
}
51+
52+
}
53+
54+
static class ArgumentsCommand {
55+
56+
float base;
57+
58+
Float[] numbers;
59+
60+
Float[] moreNumbers;
61+
62+
@Command(name = "add", description = "Add numbers together", group = "Math commands",
63+
help = "A command that adds numbers together. Example usage: add --base 10 1 2 3 4 5 6 7 8 9 10")
64+
public void add(
65+
@Option(shortName = 'b', longName = "base", description = "the base number to add to") float base,
66+
@Arguments(arity = 2) Float[] numbers, @Arguments(arity = 3) Float[] moreNumbers) {
67+
this.base = base;
68+
this.numbers = numbers;
69+
this.moreNumbers = moreNumbers;
70+
}
71+
72+
}
73+
74+
@Test
75+
void optionDefaultValueIsUsedForPrimitiveWhenOptionMissing() throws Exception {
76+
Target target = new Target();
77+
Method method = Target.class.getDeclaredMethod("run", int.class);
78+
79+
DefaultConversionService conversionService = new DefaultConversionService();
80+
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
81+
82+
CommandContext ctx = Mockito.mock(CommandContext.class);
83+
Mockito.when(ctx.getOptionByLongName("retries")).thenReturn(null);
84+
85+
StringWriter out = new StringWriter();
86+
Mockito.when(ctx.outputWriter()).thenReturn(new PrintWriter(out));
87+
88+
MethodInvokerCommandAdapter adapter = new MethodInvokerCommandAdapter("name", "desc", "group", "help", false,
89+
method, target, conversionService, validator);
90+
91+
ExitStatus status = adapter.doExecute(ctx);
92+
93+
assertThat(status).isEqualTo(ExitStatus.OK);
94+
assertThat(target.seen).isEqualTo(3);
95+
}
96+
97+
@Test
98+
void argumentsAreParsed() throws Exception {
99+
// given
100+
ArgumentsCommand target = new ArgumentsCommand();
101+
Method method = ArgumentsCommand.class.getDeclaredMethod("add", float.class, Float[].class, Float[].class);
102+
DefaultConversionService conversionService = new DefaultConversionService();
103+
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
104+
CommandContext ctx = Mockito.mock(CommandContext.class, Mockito.RETURNS_DEEP_STUBS);
105+
Mockito.when(ctx.getOptionByLongName("base"))
106+
.thenReturn(CommandOption.with().longName("base").value("10").build());
107+
StringWriter out = new StringWriter();
108+
Mockito.when(ctx.parsedInput().arguments())
109+
.thenReturn(java.util.List.of(new CommandArgument(0, "1"), new CommandArgument(1, "2"),
110+
new CommandArgument(2, "3"), new CommandArgument(3, "4"), new CommandArgument(4, "5"),
111+
new CommandArgument(5, "6"), new CommandArgument(6, "7"), new CommandArgument(7, "8"),
112+
new CommandArgument(8, "9"), new CommandArgument(9, "10")));
113+
Mockito.when(ctx.outputWriter()).thenReturn(new PrintWriter(out));
114+
MethodInvokerCommandAdapter adapter = new MethodInvokerCommandAdapter("name", "desc", "group", "help", false,
115+
method, target, conversionService, validator);
116+
117+
// when
118+
ExitStatus status = adapter.doExecute(ctx);
119+
120+
// then
121+
assertThat(status).isEqualTo(ExitStatus.OK);
122+
assertThat(target.base).isEqualTo(10f);
123+
assertThat(target.numbers).containsExactly(1f, 2f);
124+
assertThat(target.moreNumbers).containsExactly(3f, 4f, 5f);
125+
}
126+
127+
}

spring-shell-docs/modules/ROOT/pages/commands/syntax.adoc

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,22 @@ Options are named, while arguments are positional. Options can have short names
1717

1818
Options can be validated using the Bean Validation API by adding validation annotations to the method parameters, see the xref:commands/validation.adoc[Validating Command Options] section for more details.
1919

20+
Multi-valued arguments can be defined by using the `@Arguments` annotation on an array or a collection type (e.g., `List`, `Set`) as the method parameter type. In this case, all the remaining command line tokens will be collected into the collection:
21+
22+
[source, java, indent=0]
23+
----
24+
include::{snippets}/CommandAnnotationSnippets.java[tag=multi-valued-argument]
25+
----
26+
27+
The `@Arguments` annotation provides an attribute called `arity` that allows you to specify the number of arguments to be collected into the collection.
28+
By default, the arity is not bound, which means that all remaining tokens will be collected. If you set the arity to a specific number, only that many tokens will be collected, and the rest will be treated as separate arguments or options.
29+
Here is an example of using the `arity` attribute:
30+
31+
[source, java, indent=0]
32+
----
33+
include::{snippets}/CommandAnnotationSnippets.java[tag=multi-valued-argument-with-arity]
34+
----
35+
2036
== Parsing rules
2137

2238
Spring Shell follows the same parsing rules as Spring Boot, with enhanced capabilities following the POSIX style.

spring-shell-docs/src/test/java/org/springframework/shell/docs/CommandAnnotationSnippets.java

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,7 @@
1515
*/
1616
package org.springframework.shell.docs;
1717

18-
import org.springframework.shell.core.command.annotation.Command;
19-
import org.springframework.shell.core.command.annotation.Option;
20-
import org.springframework.shell.core.command.annotation.Argument;
21-
import org.springframework.shell.core.command.annotation.EnableCommand;
18+
import org.springframework.shell.core.command.annotation.*;
2219
import org.springframework.stereotype.Component;
2320

2421
class CommandAnnotationSnippets {
@@ -61,6 +58,39 @@ public void sayHi(
6158
}
6259
// end::command-option-arg[]
6360

61+
// tag::multi-valued-argument[]
62+
@Component
63+
class ArgumentsCommands {
64+
65+
@Command(name = "hi", description = "Say hi to given names", group = "greetings",
66+
help = "A command that greets users with a configurable suffix. Example usage: hi -s=! Foo Bar")
67+
public void sayHi(@Option(shortName = 's', longName = "suffix",
68+
description = "the suffix of the greeting message", defaultValue = "!") String suffix,
69+
@Arguments String[] names) {
70+
System.out.println("Hi " + String.join(", ", names) + suffix);
71+
}
72+
73+
}
74+
// end::multi-valued-argument[]
75+
76+
// tag::multi-valued-argument-with-arity[]
77+
@Component
78+
class ArgumentsWithArityCommands {
79+
80+
/**
81+
* Real part of (a + bi)(c + di) = ac − bd.
82+
*/
83+
@Command(name = "real-part", description = "Calculate the real part of the product of two complex numbers",
84+
group = "math",
85+
help = "Calculate the real part of the product of two complex numbers. Example usage: real-part 1 2 3 4")
86+
public double realPartOfComplexProduct(@Arguments(arity = 2) double[] realParts,
87+
@Arguments(arity = 2) double[] imaginaryParts) {
88+
return realParts[0] * realParts[1] - imaginaryParts[0] * imaginaryParts[1];
89+
}
90+
91+
}
92+
// end::multi-valued-argument-with-arity[]
93+
6494
}
6595

6696
}

0 commit comments

Comments
 (0)