gpt4 book ai didi

java - 解析多个 picocli(子)命令和 shell

转载 作者:行者123 更新时间:2023-12-04 09:40:56 25 4
gpt4 key购买 nike

如何构建一个 Spring Boot 2.3 多命令 CLI 应用程序,该应用程序可以使用单个命令、@script 并在 picocli 中交互运行?它的行为应该像这样:

manager -u <user> -p <pass> [list|create|delete] # run and exit
manager -u <user> -p <pass> @script # run and exit
manager -u <user> -p <pass> # run shell

需要用户名-u和密码-p,三个命令(listcreate删除)各自有不同的选项和参数。

最佳答案

Spring Boot 应用程序很简单:

@SpringBootApplication
public class Application {
public static void main(String[] args) {
System.exit(SpringApplication.exit(
SpringApplication.run(Application.class, args))
);
}

}

带有返回值的 Spring Boot CommandLineRunner 也很简单,调用 picocliCommandLine 来解析和执行命令:

@Component
public class ApplicationRunner implements CommandLineRunner, ExitCodeGenerator {
private int exitCode;

@Override
public void run(String... args) throws Exception {
exitCode = new CommandLine(new ConnectCommand()).execute(args);
}

@Override
public int getExitCode() {
return exitCode;
}

}

ConnectCommand 具有 showAtFileInUsageHelp = true(启用 picocli 的 @-file 支持)和 mixinStandardHelpOptions(启用)带有“标准”选项的帮助和版本信息(-h--help 等):

@Command(
name = "manager",
description = "The manager description",
showAtFileInUsageHelp = true,
mixinStandardHelpOptions = true,
subcommands = {
ListCommand.class,
CreateCommand.class,
DeleteCommand.class
})
@Component
public class ConnectCommand implements Runnable, ExitCodeGenerator {
@Option(
names = {"-u", "--username"},
description = "The username")
private String username;

@Option(
names = {"-p", "--password"},
description = "The password")
private String password;

private int exitCode;

@Override
public void run() {
// WIP: kick-off shell
}

@Override
public int getExitCode() {
return exitCode;
}

}

所有(子)命令都采用这种形式(根据需要撒入 picocli@Option@Parameters):

@Command(
name = "list",
mixinStandardHelpOptions = true,
header = "list stuff")
@Component
class ListCommand implements Runnable{
@Override
public void run() {
System.out.println("listing...");
}

}

有了这个,帮助现在看起来像:

Usage: manager [-hV] [-u=username] [-p=password] [@<filename>...] [COMMAND]
The manager description
[@<filename>...] One or more argument files containing options.
-u, --username=name The username
-p, --password=pass The password
-h, --help Show this help message and exit.
-V, --version Print version information and exit.
Commands:
list list stuff
create create stuff
delete delete stuff

运行单个命令即可:

java -jar manager.jar -u=myname -p=mypass list
listing...

运行包含“list”的@文件也可以:

java -jar manager.jar -u=myname -p=mypass @listing
listing...

这是一个sample repository 。现在我们需要折叠外壳......

关于java - 解析多个 picocli(子)命令和 shell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62334604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com