6. Completion

Spring Shell can provide completion proposals for both interactive shell and a command-line. There are differences however as when shell is in interactive mode we have an active instance of a shell meaning it’s easier to provide more programmatic ways to provide completion hints. When shell is purely run as a command-line tool a completion can only be accomplished with integration into OS level shell’s like bash.spring-doc.cn

6.1. Interactive

Hints for completions are calculated with function or interface style methods which takes CompletionContext and returns a list of CompletionProposal instances. CompletionContext gives you various information about a current context like command registration and option.spring-doc.cn

Generic resolvers can be registered as a beans if those are useful for all commands and scenarious. For example existing completion implementation RegistrationOptionsCompletionResolver handles completions for a option names.
static class MyValuesCompletionResolver implements CompletionResolver {

	@Override
	public List<CompletionProposal> apply(CompletionContext t) {
		return Arrays.asList("val1", "val2").stream()
			.map(CompletionProposal::new)
			.collect(Collectors.toList());
	}
}

Option values with builder based command registration can be defined per option.spring-doc.cn

void dump1() {
	CommandRegistration.builder()
		.withOption()
			.longNames("arg1")
			.completion(ctx -> {
				return Arrays.asList("val1", "val2").stream()
					.map(CompletionProposal::new)
					.collect(Collectors.toList());
			})
			.and()
		.build();
}

Option values with annotation based command registration are handled via ValueProvider interface which can be defined with @ShellOption annotation.spring-doc.cn

static class MyValuesProvider implements ValueProvider {

	@Override
	public List<CompletionProposal> complete(CompletionContext completionContext) {
		return Arrays.asList("val1", "val2").stream()
			.map(CompletionProposal::new)
			.collect(Collectors.toList());
	}
}

Actual ValueProvider with annotation based command needs to be registered as a Bean.spring-doc.cn

@ShellMethod(value = "complete", key = "complete")
public String complete(
	@ShellOption(valueProvider = MyValuesProvider.class) String arg1)
{
	return "You said " + arg1;
}

6.2. Command-Line

Command-line completion currently only support bash and is documented in a built-in completion command Completion.spring-doc.cn