在运行时启用或禁用选项

时间:2019-08-13 16:07:21

标签: java command-line-interface picocli

我正在尝试使用Picocli进行交互式cli,并希望在完成某项操作/要求后出现一些选项。有没有不用CommandSpec就能做到这一点的方法?

之前显示的选项

@Option(names = {"-c","--chooseDevice"}, description = {"Choose Devices"})
    private boolean chooseDevice;

--
some code that will initialize a device
--

在之后显示的选项

@Options(names = {,"-d", "--deviceCommand", description = "some device command")
    private boolean deviceCommand;

输出应为

//before choosing device
-c  --chooseDevice "Choose Devices"

//after choosing device
-c  --chooseDevice   "Choose Devices"
-d  --deviceCommand  "some device command"

1 个答案:

答案 0 :(得分:0)

可以在运行时更改选项的hidden属性,但是确实需要使用编程API(例如CommandSpec类)。

Picocli 4.0添加了从CommandSpec删除选项的功能,因此您可以将其替换为选项的副本,该选项的hidden属性具有不同的值。

类似这样的东西:

CommandLine cmd = new CommandLine(new MyApp());

// replace the old "--device" option with a different one that is not hidden
CommandSpec spec = cmd.getCommandSpec();
OptionSpec old = spec.findOption("--device");
OptionSpec newDeviceOption = OptionSpec.builder(old).hidden(false).build();
spec.remove(old);
spec.add(newDeviceOption);

cmd.execute(args);

有关更多详细信息,请参见GitHub issue #736