final String script;
try {
script = new String(source, "UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new CommandException(ErrorKind.INTERNAL, "Could not compile command script " + name, e);
}
// Get the description using a partial compilation because it is much faster than compiling the class
// the class will be compiled lazyly
String resolveDescription = null;
CompilationUnit cu = new CompilationUnit(objectGroovyClassFactory.config);
cu.addSource(name, script);
try {
cu.compile(Phases.CONVERSION);
}
catch (CompilationFailedException e) {
throw new CommandException(ErrorKind.INTERNAL, "Could not compile command", e);
}
CompileUnit ast = cu.getAST();
if (ast.getClasses().size() > 0) {
ClassNode classNode= (ClassNode)ast.getClasses().get(0);
if (classNode != null) {
for (AnnotationNode annotation : classNode.getAnnotations()) {
if (annotation.getClassNode().getName().equals(Usage.class.getSimpleName())) {
resolveDescription = annotation.getMember("value").getText();
break;
}
}
if (resolveDescription == null) {
for (MethodNode main : classNode.getMethods("main")) {
for (AnnotationNode annotation : main.getAnnotations()) {
if (annotation.getClassNode().getName().equals(Usage.class.getSimpleName())) {
resolveDescription = annotation.getMember("value").getText();
break;
}
}
}
}
}
}
final String description = resolveDescription;
//
return new CommandResolution() {
Command<?> command;
@Override
public String getDescription() {
return description;
}
@Override
public Command<?> getCommand() throws CommandException {
if (command == null) {
Class<?> clazz = objectGroovyClassFactory.parse(name, script);
if (BaseCommand.class.isAssignableFrom(clazz)) {
Class<? extends BaseCommand> cmd = clazz.asSubclass(BaseCommand.class);
try {
command = make(cmd);
}
catch (IntrospectionException e) {
throw new CommandException(ErrorKind.INTERNAL, "Invalid cli annotations for command " + name, e);
}
}
else if (GroovyScriptCommand.class.isAssignableFrom(clazz)) {
Class<? extends GroovyScriptCommand> cmd = clazz.asSubclass(GroovyScriptCommand.class);
try {
command = make2(cmd);
}
catch (IntrospectionException e) {
throw new CommandException(ErrorKind.INTERNAL, "Invalid cli annotations for command " + name, e);
}
}
else {
throw new CommandException(ErrorKind.INTERNAL, "Could not create command " + name + " instance");
}
}
return command;
}
};