子命令

CommandSpec Builder 支持使用分层命令结构,就像下面这样:

  • /mail (父命令)

    • /mail send (子命令)

    • /mail read (子命令)

所有的子命令都有着单独的 CommandSpec ,并且可以像一个正常的命令一样去创建。

import org.spongepowered.api.text.Text;
import org.spongepowered.api.command.spec.CommandSpec;

// /mail read
CommandSpec readCmd = CommandSpec.builder()
    .permission("myplugin.mail.read")
    .description(Text.of("Read your inbox"))
    .executor(...)
    .build();

// /mail send
CommandSpec sendCmd = CommandSpec.builder()
    .permission("myplugin.mail.send")
    .description(Text.of("Send a mail"))
    .arguments(...)
    .executor(...)
    .build();

和正常的命令不同,子命令并不使用直接注册的方式,而是作为父命令的 CommandSpec Builder 的 CommandSpec.Builder#child(CommandCallable, String…) 的方法参数传入。当然,它们可以使用多个不同的别名,第一个别名将用于主名称,并且会在帮助中显示。

import org.spongepowered.api.Sponge;

CommandSpec mailCommandSpec = CommandSpec.builder()
    .permission("myplugin.mail")
    .description(Text.of("Send and receive mails"))
    .child(readCmd, "read", "r", "inbox")
    .child(sendCmd, "send", "s", "write")
    .build();

Sponge.getCommandManager().register(plugin, mailCommandSpec, "mail", "email");

注解

如果父命令指定了一个 CommandExecutor ,那么会在找不到子命令的所有别名时,交由这个 CommandExecutor 处理。当然,这么一个 CommandExecutor 并不是必须的。