位置

位置信息主要与命令目标方法相关

CommandRegistration.builder()
	.withOption()
		.longNames("arg1")
		.position(0)
		.and()
	.build();
请谨慎使用位置参数,因为它很快就会让人混淆这些参数映射到哪些选项。

通常,当命令行中定义了参数时(无论是长选项还是短选项),它们会被映射到某个选项。一般来说,有选项选项参数参数,其中后者是未映射到任何特定选项的参数。

未识别的参数可以进行二次映射逻辑,此时位置信息很重要。通过选项位置,您实际上是在告诉命令解析器如何解释普通的原始模糊参数。

让我们看看不定义位置时会发生什么。

CommandRegistration.builder()
	.command("arity-strings-1")
	.withOption()
		.longNames("arg1")
		.required()
		.type(String[].class)
		.arity(0, 2)
		.and()
	.withTarget()
		.function(ctx -> {
			String[] arg1 = ctx.getOptionValue("arg1");
			return "Hello " + Arrays.asList(arg1);
		})
		.and()
	.build();

选项 arg1 是必需的,并且没有关于如何处理参数 one 的信息,因此导致缺少选项的错误。

shell:>arity-strings-1 one
Missing mandatory option --arg1.

现在让我们定义一个位置 0

CommandRegistration.builder()
	.command("arity-strings-2")
	.withOption()
		.longNames("arg1")
		.required()
		.type(String[].class)
		.arity(0, 2)
		.position(0)
		.and()
	.withTarget()
		.function(ctx -> {
			String[] arg1 = ctx.getOptionValue("arg1");
			return "Hello " + Arrays.asList(arg1);
		})
		.and()
	.build();

参数被处理,直到我们得到 2 个参数。

shell:>arity-strings-2 one
Hello [one]

shell:>arity-strings-2 one two
Hello [one, two]

shell:>arity-strings-2 one two three
Hello [one, two]
© . This site is unofficial and not affiliated with VMware.