Fix use of default values

- Change parsing to extract and use option default value
  and also hook it with @ShellOption.
- Fixes #409
This commit is contained in:
Janne Valkealahti
2022-05-11 07:16:00 +01:00
parent 6738c92117
commit 75ff6e976f
4 changed files with 75 additions and 0 deletions

View File

@@ -18,6 +18,7 @@ package org.springframework.shell.command;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.List;
@@ -313,6 +314,21 @@ public interface CommandParser {
}
})
.collect(Collectors.toList());
// Check options which didn't get matched and add parser result
// for those having default value.
List<CommandOption> defaultValueOptionsToCheck = new ArrayList<>(options);
results.stream()
.forEach(pr -> {
if (pr.option != null) {
defaultValueOptionsToCheck.remove(pr.option);
}
});
defaultValueOptionsToCheck.stream()
.filter(co -> co.getDefaultValue() != null)
.forEach(co -> {
results.add(ParserResult.of(co, Collections.emptyList(), co.getDefaultValue(), null));
});
return ParserResults.of(results);
}

View File

@@ -421,6 +421,25 @@ public class CommandExecutionTests extends AbstractCommandTests {
assertThat(pojo1.method4Arg1).isNull();
}
@Test
public void testDefaultValue() {
CommandRegistration r1 = CommandRegistration.builder()
.command("command1")
.withOption()
.longNames("arg1")
.defaultValue("defaultValue1")
// .position(0)
// .arity(OptionArity.EXACTLY_ONE)
.and()
.withTarget()
.method(pojo1, "method4")
.and()
.build();
execution.evaluate(r1, new String[]{});
assertThat(pojo1.method4Count).isEqualTo(1);
assertThat(pojo1.method4Arg1).isEqualTo("defaultValue1");
}
@Test
public void testRequiredArg() {
CommandRegistration r1 = CommandRegistration.builder()