Fixes to commands where (sub)commands never extend pkl:Command (#1882)

This commit is contained in:
Jen Basch authored and GitHub committed 2026-09-29 23:19:28 +00:00
1 parent e83d8fa14b
commit 1271da2741
6 files changed
+185 -23

No files matched your search

@@ -1286,4 +1286,41 @@ class CliCommandRunnerTest {
;;"""
)
}
@Test
fun `exec of amended subcommand`() {
writePklFile(
"sub.pkl",
"""
extends "pkl:Command"
target: String
"""
.trimIndent(),
)
val moduleUri =
writePklFile(
"cmd.pkl",
"""
amends "pkl:Command"
import "sub.pkl"
command {
name = "root"
subcommands {
new sub { target = "foo" }
}
}
"""
.trimIndent(),
)
val output = runToStdout(CliBaseOptions(sourceModules = listOf(moduleUri)), listOf("sub"))
assertThat(output)
.isEqualTo(
"""
target = "foo"
"""
.trimIndent()
)
}
}
@@ -24,8 +24,11 @@ import java.io.UncheckedIOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
@@ -49,6 +52,7 @@ import org.pkl.core.PklBugException;
import org.pkl.core.SecurityManager;
import org.pkl.core.SecurityManagerException;
import org.pkl.core.StackFrameTransformer;
import org.pkl.core.ast.ConstantValueNode;
import org.pkl.core.ast.ExpressionNode;
import org.pkl.core.ast.VmModifier;
import org.pkl.core.ast.expression.literal.AmendModuleNodeGen;
@@ -98,6 +102,36 @@ public final class CommandSpecParser {
}
public CommandSpec parse(VmTyped command) {
var path = new ArrayDeque<String>();
path.push("[root]");
try {
return doParse(command, path);
} catch (VmException e) {
var hint = new StringBuilder("Error occurred while parsing command definition: ");
assert !path.isEmpty();
var iter = path.descendingIterator();
hint.append(iter.next());
while (iter.hasNext()) {
hint.append(" > ").append(iter.next());
}
var hintBuilder = e.getHintBuilder();
if (hintBuilder != null) {
e.setHintBuilder(
(builder, flag) -> {
hintBuilder.accept(builder, flag);
builder.append("\n\n");
builder.append(hint);
});
} else {
e.setHint(hint.toString());
}
throw e;
}
}
private CommandSpec doParse(VmTyped command, Deque<String> path) {
VmUtils.checkAmends(command, CommandModule.getModule().getVmClass());
checkPropertyIsUndefined(command, Identifier.OPTIONS);
checkPropertyIsUndefined(command, Identifier.PARENT);
@@ -107,22 +141,27 @@ public final class CommandSpecParser {
VmUtils.checkAmends(
VmUtils.readMember(command, Identifier.COMMAND), CommandModule.getCommandInfoClass());
var commandName = (String) VmUtils.readMember(commandInfo, Identifier.NAME);
if (path.size() > 1) {
path.pop();
path.push(commandName);
}
var optionSpecs = collectOptions(optionsClass);
return new CommandSpec(
commandName,
exportNullableString(commandInfo, Identifier.DESCRIPTION),
(Boolean) VmUtils.readMember(commandInfo, Identifier.HIDE),
(Boolean) VmUtils.readMember(commandInfo, Identifier.NOOP),
(boolean) VmUtils.readMember(commandInfo, Identifier.HIDE),
(boolean) VmUtils.readMember(commandInfo, Identifier.NOOP),
optionSpecs,
collectSubcommands(commandInfo),
collectSubcommands(commandInfo, path),
(options, parent) ->
new CommandSpec.State(
buildExecutionModule(
command,
buildObject(optionsClass, options),
// NB: these next two lines are the only place where we lose type safety.
// SubcommandState is type-erased to Object in the public API to hide internals.
// SubcommandState is type-erased to Object in the public API to hide
// internals.
// Consumers of this API must ensure CommandSpec.apply is only ever passed an
// instance of CommandSpec.State previously returned from a prior invocation
// of CommandSpec.apply.
@@ -130,24 +169,31 @@ public final class CommandSpecParser {
(it) -> handleErrors(() -> evaluateResult(command, (SubcommandState) it))));
}
private List<CommandSpec> collectSubcommands(VmTyped commandInfo) {
private List<CommandSpec> collectSubcommands(VmTyped commandInfo, Deque<String> path) {
var subcommands = new ArrayList<CommandSpec>();
var subcommandNames = new HashSet<String>();
var subcommandNames = new HashMap<String, Object>();
var subcommandsProperty = (VmObject) VmUtils.readMember(commandInfo, Identifier.SUBCOMMANDS);
subcommandsProperty.force(false, false);
subcommandsProperty.iterateAlreadyForcedMemberValues(
(key, member, value) -> {
var spec = parse((VmTyped) value);
if (subcommandNames.contains(spec.name())) {
// track the subcommand index at first
// replaced by subcommand name in doParse if reading name succeeds
path.push("subcommands[" + key + "]");
var spec = doParse((VmTyped) value, path);
path.pop();
var existingNameIndex = subcommandNames.get(spec.name());
if (existingNameIndex != null) {
throw exceptionBuilder()
.withSourceSection(member.getSourceSection())
.evalError(
"commandSubcommandConflict",
VmUtils.readMember(commandInfo, Identifier.NAME),
spec.name())
spec.name(),
existingNameIndex,
key)
.build();
}
subcommandNames.add(spec.name());
subcommandNames.put(spec.name(), key);
subcommands.add(spec);
return true;
});
@@ -282,7 +328,7 @@ public final class CommandSpecParser {
boolean hide = false;
if (flagAnnotation != null) {
shortName = exportNullableString(flagAnnotation, Identifier.SHORT_NAME);
hide = (Boolean) VmUtils.readMember(flagAnnotation, Identifier.HIDE);
hide = (boolean) VmUtils.readMember(flagAnnotation, Identifier.HIDE);
}
checkFlagNames(prop, name, shortName);
@@ -1176,11 +1222,13 @@ public final class CommandSpecParser {
new ExpressionNode[] {},
parent.members,
moduleInfo,
new ImportNode(
language,
VmUtils.unavailableSourceSection(),
resolvedModule,
module.getModuleInfo().getResolvedModuleKey().getUri()));
module.isModuleObject()
? new ImportNode(
language,
VmUtils.unavailableSourceSection(),
resolvedModule,
module.getModuleInfo().getResolvedModuleKey().getUri())
: new ConstantValueNode(VmUtils.unavailableSourceSection(), module));
var moduleNode =
new ModuleNode(
@@ -37,7 +37,7 @@ public abstract class VmException extends AbstractTruffleException {
private final List<StackFrame> leadingStackFrames;
@Nullable private final BiConsumer<AnsiStringBuilder, Boolean> messageBuilder;
@Nullable protected BiConsumer<AnsiStringBuilder, Boolean> hintBuilder;
private boolean forExpressionInput;
private boolean forExpressionInput = false;
public VmException(
@Nullable String message,
@@ -63,7 +63,6 @@ public abstract class VmException extends AbstractTruffleException {
this.insertedStackFrames = insertedStackFrames;
this.leadingStackFrames = leadingStackFrames;
this.hintBuilder = hintBuilder;
this.forExpressionInput = forExpressionInput;
}
public final boolean isExternalMessage() {
@@ -110,6 +109,10 @@ public abstract class VmException extends AbstractTruffleException {
return hintBuilder;
}
public void setHintBuilder(BiConsumer<AnsiStringBuilder, Boolean> hintBuilder) {
this.hintBuilder = hintBuilder;
}
public void setHint(String hint) {
this.hintBuilder = ((builder, aBoolean) -> builder.append(hint));
}
@@ -1123,7 +1123,7 @@ characterCodingException=\
Invalid bytes for charset "{0}".
commandSubcommandConflict=\
Command `{0}` has subcommands with conflicting name "{1}".\n\
Command `{0}` has subcommands with conflicting name "{1}" at index `{2}` and index `{3}`.\n\
Elements of `command.subcommands` must have unique `name` values.
commandMustNotAssignOrAmendProperty=\
@@ -699,7 +699,10 @@ class CommandSpecParserTest {
)
val exc = assertThrows<PklException> { parse(moduleUri) }
assertThat(exc.message).contains("Command `cmd` has subcommands with conflicting name \"foo\".")
assertThat(exc.message)
.contains(
"Command `cmd` has subcommands with conflicting name \"foo\" at index `0` and index `1`."
)
}
@Test
@@ -839,4 +842,72 @@ class CommandSpecParserTest {
assertThat(this.showAsRequired).isFalse()
}
}
@Test
fun `amend-only command parses without error and has null description`() {
val moduleUri =
writePklFile(
"cmd.pkl",
"""
amends "pkl:Command"
import "sub.pkl"
command {
name = "root"
subcommands {
new sub { target = "foo" }
}
}
"""
.trimIndent(),
)
writePklFile(
"sub.pkl",
"""
extends "pkl:Command"
target: String
"""
.trimIndent(),
)
val spec = parse(moduleUri)
assertThat(spec.helpText).isNull()
}
@Test
fun `command parsing output includes command path`() {
val moduleUri =
writePklFile(
"cmd.pkl",
"""
extends "pkl:Command"
import "pkl:Command"
command {
name = "root"
subcommands {
new Sub1 {
command {
subcommands {
new Sub2 {
command {
name = throw("oops")
}
}
}
}
}
}
}
class Sub1 extends Command
class Sub2 extends Command
"""
.trimIndent(),
)
val exc = assertThrows<PklException> { parse(moduleUri) }
assertThat(exc.message)
.contains("Error occurred while parsing command definition: [root] > Sub1 > subcommands[0]")
}
}
+6 -3
View File
@@ -36,12 +36,15 @@ import "pkl:Command"
import "pkl:reflect"
local commandClass = reflect.Class(getClass())
local commandModule = reflect.Module(Command)
/// Command configuration.
hidden command: CommandInfo = new {
name = // choose the name of the module if the command is a module or the class otherwise
if (commandClass.name == "ModuleClass") reflect.Module(module).name else commandClass.name
description = commandClass.docComment // works for both classes and module classes
when (commandClass != commandModule.moduleClass) {
name =
if (commandClass.name == "ModuleClass") reflect.moduleOf(module).name else commandClass.name
description = commandClass.docComment
}
}
/// Command line options.