Skip to content

Commit 0f2bd3a

Browse files
committed
improve command aliasing in CommandRegistration.BaseBuilder
1 parent 2f00d73 commit 0f2bd3a

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

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

+24-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2022-2023 the original author or authors.
2+
* Copyright 2022-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -41,6 +41,7 @@
4141
* Interface defining a command registration endpoint.
4242
*
4343
* @author Janne Valkealahti
44+
* @author Andrey Litvitski
4445
*/
4546
public interface CommandRegistration {
4647

@@ -764,6 +765,14 @@ public interface Builder {
764765
*/
765766
AliasSpec withAlias();
766767

768+
/**
769+
* Define an alias what this command should execute
770+
*
771+
* @param commands the commands
772+
* @return builder for chaining
773+
*/
774+
Builder withAlias(String... commands);
775+
767776
/**
768777
* Define an exit code what this command should execute
769778
*
@@ -1421,6 +1430,20 @@ public AliasSpec withAlias() {
14211430
return spec;
14221431
}
14231432

1433+
@Override
1434+
public Builder withAlias(String... commands) {
1435+
Assert.notNull(commands, "commands must be set");
1436+
DefaultAliasSpec spec = new DefaultAliasSpec(this);
1437+
spec.commands = Arrays.asList(commands).stream()
1438+
.flatMap(c -> Stream.of(c.split(" ")))
1439+
.filter(c -> StringUtils.hasText(c))
1440+
.map(c -> c.trim())
1441+
.collect(Collectors.toList())
1442+
.toArray(new String[0]);
1443+
this.aliasSpecs.add(spec);
1444+
return this;
1445+
}
1446+
14241447
@Override
14251448
public ExitCodeSpec withExitCode() {
14261449
DefaultExitCodeSpec spec = new DefaultExitCodeSpec(this);

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

+3-2
Original file line numberDiff line numberDiff line change
@@ -411,15 +411,16 @@ public void testAliases() {
411411
.command("alias2")
412412
.group("Alias Group")
413413
.and()
414+
.withAlias("alias3")
414415
.withTarget()
415416
.function(function1)
416417
.and()
417418
.build();
418419
assertThat(registration.getCommand()).isEqualTo("command1");
419420
assertThat(registration.getGroup()).isEqualTo("Test Group");
420-
assertThat(registration.getAliases()).hasSize(2);
421+
assertThat(registration.getAliases()).hasSize(3);
421422
assertThat(registration.getAliases().stream().map(CommandAlias::getCommand)).containsExactlyInAnyOrder("alias1",
422-
"alias2");
423+
"alias2", "alias3");
423424
assertThat(registration.getAliases().get(0).getGroup()).isEqualTo("Alias Group");
424425
assertThat(registration.getAliases().get(1).getGroup()).isEqualTo("Alias Group");
425426
}

0 commit comments

Comments
 (0)