Skip to content

Commit

Permalink
Added application parameters
Browse files Browse the repository at this point in the history
Fixes #139
  • Loading branch information
lptr committed Sep 17, 2014
1 parent 6b1deba commit c9c3ee9
Show file tree
Hide file tree
Showing 24 changed files with 153 additions and 64 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.prezi.spaghetti.gradle;

import com.google.common.collect.Maps;
import com.prezi.spaghetti.gradle.internal.AbstractSpaghettiTask;
import com.prezi.spaghetti.gradle.internal.ModuleBundleLookupResult;
import com.prezi.spaghetti.packaging.ApplicationPackageParameters;
Expand All @@ -13,6 +14,7 @@

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Callable;

import static com.prezi.spaghetti.gradle.internal.TextFileUtils.getText;
Expand All @@ -25,6 +27,36 @@ public class PackageApplication extends AbstractSpaghettiTask {
private ApplicationType type = ApplicationType.COMMON_JS;
private Boolean execute = null;
private File outputDirectory;
private Map<String, String> parameters = Maps.newLinkedHashMap();

public PackageApplication() {
this.getConventionMapping().map("outputDirectory", new Callable<File>() {
@Override
public File call() throws Exception {
return new File(getProject().getBuildDir(), "spaghetti/application");
}

});
if ((execute == Boolean.TRUE) && (mainModule == null)) {
throw new IllegalArgumentException("You need to set mainModule as well when execute is true");
}
}

@TaskAction
@SuppressWarnings("UnusedDeclaration")
public void makeBundle() throws IOException {
ModuleBundleLookupResult bundles = lookupBundles();
getLogger().info("Creating {} application in {}", getType().getDescription(), getOutputDirectory());
getType().getPackager().packageApplicationDirectory(getOutputDirectory(), new ApplicationPackageParameters(
bundles.getAllBundles(),
getApplicationName(),
getMainModule(),
getExecute(),
getParameters(),
getText(getPrefixes()),
getText(getSuffixes())
));
}

@Input
@Optional
Expand Down Expand Up @@ -128,31 +160,14 @@ public File getApplicationFile() {
return new File(getOutputDirectory(), getApplicationName());
}

public PackageApplication() {
this.getConventionMapping().map("outputDirectory", new Callable<File>() {
@Override
public File call() throws Exception {
return new File(getProject().getBuildDir(), "spaghetti/application");
}

});
if ((execute == Boolean.TRUE) && (mainModule == null)) {
throw new IllegalArgumentException("You need to set mainModule as well when execute is true");
}
@Input
public Map<String, String> getParameters() {
return parameters;
}

@TaskAction
@SuppressWarnings("UnusedDeclaration")
public void makeBundle() throws IOException {
ModuleBundleLookupResult bundles = lookupBundles();
getLogger().info("Creating {} application in {}", getType().getDescription(), getOutputDirectory());
getType().getPackager().packageApplicationDirectory(getOutputDirectory(), new ApplicationPackageParameters(
bundles.getAllBundles(),
getApplicationName(),
getMainModule(),
getExecute(),
getText(getPrefixes()),
getText(getSuffixes())
));
public void parameters(Map<?, ?> parameters) {
for (Map.Entry<?, ?> entry : parameters.entrySet()) {
this.parameters.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.prezi.spaghetti.ast.internal.parser;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.prezi.spaghetti.ast.FQName;
import com.prezi.spaghetti.ast.ModuleNode;
import com.prezi.spaghetti.ast.QualifiedTypeNode;
import com.prezi.spaghetti.ast.internal.DefaultExternInterfaceNode;
import com.prezi.spaghetti.ast.internal.DefaultImportNode;
import com.prezi.spaghetti.ast.internal.DefaultMethodNode;
import com.prezi.spaghetti.ast.internal.DefaultModuleNode;
Expand All @@ -13,8 +16,13 @@

import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class ModuleParser {
private static final Set<QualifiedTypeNode> DEFAULT_EXTERNS = ImmutableSet.<QualifiedTypeNode> builder()
.add(new DefaultExternInterfaceNode(FQName.fromString("SpaghettiParameters")))
.build();

private final List<AbstractModuleTypeParser> typeParsers;
private final List<com.prezi.spaghetti.internal.grammar.ModuleParser.MethodDefinitionContext> moduleMethodsToParse;
private final DefaultModuleNode module;
Expand Down Expand Up @@ -43,6 +51,9 @@ protected ModuleParser(ModuleDefinitionSource source, com.prezi.spaghetti.intern
moduleAlias = StringUtils.capitalize(nameParts.get(nameParts.size() - 1)) + "Module";
}
this.module = new DefaultModuleNode(moduleName, moduleAlias, source);
//noinspection deprecation
module.getExternTypes().addAll(DEFAULT_EXTERNS);

AnnotationsParser.parseAnnotations(moduleCtx.annotations(), module);
DocumentationParser.parseDocumentation(moduleCtx.documentation, module);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public class ReservedWords {
public static final String MODULE_WRAPPER_FUNCTION = "module";

public static final String SPAGHETTI_CLASS = "Spaghetti";
public static final String SPAGHETTI_PARAMETERS_CLASS = "SpaghettiParameters";

@ProtectedWord
public static final String GET_MODULE_VERSION = "getModuleVersion";
Expand All @@ -25,6 +26,9 @@ public class ReservedWords {
@ProtectedWord
public static final String GET_MODULE_NAME = "getModuleName";

@ProtectedWord
public static final String GET_PARAMETER = "getParameter";

public static final String MODULE = "module";

public static final String DEPENDENCIES = "dependencies";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.prezi.spaghetti.bundle.ModuleBundle;

import java.util.Map;
import java.util.Set;

public class ApplicationPackageParameters {
Expand All @@ -11,14 +12,16 @@ public class ApplicationPackageParameters {
public final String applicationName;
public final String mainModule;
public final boolean execute;
public final Map<String, String> parameters;
public final Iterable<String> prefixes;
public final Iterable<String> suffixes;

public ApplicationPackageParameters(Set<ModuleBundle> bundles, String applicationName, String mainModule, boolean execute, Iterable<String> prefixes, Iterable<String> suffixes) {
public ApplicationPackageParameters(Set<ModuleBundle> bundles, String applicationName, String mainModule, boolean execute, Map<String, String> parameters, Iterable<String> prefixes, Iterable<String> suffixes) {
this.bundles = bundles;
this.applicationName = applicationName;
this.mainModule = mainModule;
this.execute = execute;
this.parameters = parameters;
this.prefixes = prefixes;
this.suffixes = suffixes;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,5 @@

public interface ModuleWrapper {
String wrap(ModuleWrapperParameters params) throws IOException;

String makeApplication(Map<String, Set<String>> dependencyTree, String mainModule, boolean execute);
String makeApplication(Map<String, Set<String>> dependencyTree, String mainModule, boolean execute, Map<String, String> parameters);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.prezi.spaghetti.internal.Version;
import com.prezi.spaghetti.packaging.ModuleWrapper;
import com.prezi.spaghetti.packaging.ModuleWrapperParameters;
import org.apache.commons.lang.StringEscapeUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.prezi.spaghetti.generator.ReservedWords.DEPENDENCIES;
import static com.prezi.spaghetti.generator.ReservedWords.GET_MODULE_NAME;
import static com.prezi.spaghetti.generator.ReservedWords.GET_MODULE_VERSION;
import static com.prezi.spaghetti.generator.ReservedWords.GET_RESOURCE_URL;
import static com.prezi.spaghetti.generator.ReservedWords.GET_SPAGHETTI_VERSION;
import static com.prezi.spaghetti.generator.ReservedWords.GET_MODULE_VERSION;
import static com.prezi.spaghetti.packaging.internal.CommentUtils.appendAfterInitialComment;

public abstract class AbstractModuleWrapper implements ModuleWrapper {
Expand Down Expand Up @@ -60,4 +63,18 @@ public String apply(Map.Entry<String, String> entry) {
builder.append("\"spaghettiVersion\":\"").append(Version.SPAGHETTI_VERSION).append("\"");
builder.append("};");
}

protected static void makeParameters(StringBuilder builder, Map<String, String> parameters) {
List<String> entries = Lists.newArrayList();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
entries.add("\"" + StringEscapeUtils.escapeJavaScript(entry.getKey()) + "\":\"" + StringEscapeUtils.escapeJavaScript(entry.getValue()) + "\"");
}
builder.append("{");
builder.append("\"getParameter\":function(name){");
builder.append("return({");
builder.append(Joiner.on(",").join(entries));
builder.append("})[name];");
builder.append("}");
builder.append("}");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public void execute(OutputStream out) throws IOException {
IOUtils.write(prefix, out, Charsets.UTF_8);
}

String wrappedApplication = wrapper.makeApplication(dependencyTree, params.mainModule, params.execute);
String wrappedApplication = wrapper.makeApplication(dependencyTree, params.mainModule, params.execute, params.parameters);

IOUtils.write(wrappedApplication, out, Charsets.UTF_8);
for (String suffix : params.suffixes) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,15 @@ public String wrap(ModuleWrapperParameters params) throws IOException {
}

@Override
public String makeApplication(Map<String, Set<String>> dependencyTree, final String mainModule, boolean execute) {
public String makeApplication(Map<String, Set<String>> dependencyTree, String mainModule, boolean execute, Map<String, String> parameters) {
StringBuilder result = new StringBuilder();
result.append(makeConfig(getModulesDirectory(), Sets.newTreeSet(dependencyTree.keySet())));
if (mainModule != null) {
result.append("require([\"").append(mainModule).append("\"],function(__mainModule){");
if (execute) {
result.append("__mainModule[\"").append(MODULE).append("\"][\"main\"]();");
result.append("__mainModule[\"").append(MODULE).append("\"][\"main\"](");
makeParameters(result, parameters);
result.append(");");
}

result.append("});\n");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ public String wrap(ModuleWrapperParameters params) throws IOException {
}

@Override
public String makeApplication(Map<String, Set<String>> dependencyTree, final String mainModule, boolean execute) {
public String makeApplication(Map<String, Set<String>> dependencyTree, final String mainModule, boolean execute, Map<String, String> parameters) {
StringBuilder result = new StringBuilder();
if (mainModule != null) {
result.append("var mainModule=require(\"").append(mainModule).append("\")[\"").append(MODULE).append("\"];");
if (execute) {
result.append("mainModule[\"main\"]();\n");
result.append("mainModule[\"main\"](");
makeParameters(result, parameters);
result.append(");\n");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public String apply(String it) {
IOUtils.write(Joiner.on('\n').join(dependencyInitializers), out, Charsets.UTF_8);
IOUtils.write("\n", out);

String wrappedApplication = wrapper.makeApplication(dependencyTree, params.mainModule, params.execute);
String wrappedApplication = wrapper.makeApplication(dependencyTree, params.mainModule, params.execute, params.parameters);
IOUtils.write(wrappedApplication, out, Charsets.UTF_8);

for (String suffix : params.suffixes) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@ public String wrap(ModuleWrapperParameters params) throws IOException {
}

@Override
public String makeApplication(Map<String, Set<String>> dependencyTree, final String mainModule, boolean execute) {
public String makeApplication(Map<String, Set<String>> dependencyTree, final String mainModule, boolean execute, Map<String, String> parameters) {
StringBuilder result = new StringBuilder();
if (!Strings.isNullOrEmpty(mainModule)) {
result.append("var mainModule=modules[\"").append(mainModule).append("\"][\"").append(MODULE).append("\"];");
if (execute) {
result.append("mainModule[\"main\"]();");
result.append("mainModule[\"main\"](");
makeParameters(result, parameters);
result.append(");");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ struct MyStruct {
interface Lajos extends Iterable<string> {
}
void main(SpaghettiParameters params)
"""

def parser = ModuleParser.create(ModuleDefinitionSource.fromString("test", definition))
Expand All @@ -39,11 +41,15 @@ interface Lajos extends Iterable<string> {
"com.example.test.MyStruct",
"com.example.test.Lajos",
]
module.externTypes*.qualifiedName*.toString().asList() == [
module.externTypes*.qualifiedName*.toString().asList().sort() == [
"JSON",
"Iterable"
]
"Iterable",
"SpaghettiParameters"
].sort()
0 * _
module.methods*.name == [
"main"
]
}

def "parse import"() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class ReservedWordsTest extends Specification {
def "protected words"() {
expect:
ReservedWords.PROTECTED_WORDS.asList() == [
"getModuleName", "getModuleVersion", "getSpaghettiVersion", "getResourceUrl"
"getModuleName", "getModuleVersion", "getSpaghettiVersion", "getResourceUrl", "getParameter"
].sort()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class AmdModuleWrapperTest extends WrapperTestBase {
"com.example.alma": ["com.example.bela"].toSet(),
"com.example.bela": [].toSet()
]
def result = new AmdModuleWrapper().makeApplication(dependencyTree, "com.example.test", true)
def result = new AmdModuleWrapper().makeApplication(dependencyTree, "com.example.test", true, [alma: "bela"])

expect:
result == [
Expand All @@ -66,7 +66,13 @@ class AmdModuleWrapperTest extends WrapperTestBase {
'}',
'});',
'require(["com.example.test"],function(__mainModule){',
'__mainModule["module"]["main"]();',
'__mainModule["module"]["main"]({',
'"getParameter":function(name){',
'return({',
'"alma":"bela"',
'})[name];',
'}',
'});',
'});',
'\n'
].join("")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,18 @@ class CommonJsModuleWrapperTest extends WrapperTestBase {
"com.example.alma": ["com.example.bela"].toSet(),
"com.example.bela": [].toSet()
]
def result = new CommonJsModuleWrapper().makeApplication(dependencyTree, "com.example.test", true)
def result = new CommonJsModuleWrapper().makeApplication(dependencyTree, "com.example.test", true, [alma: "bela"])

expect:
result == [
'var mainModule=require("com.example.test")["module"];',
'mainModule["main"]();\n',
'mainModule["main"]({',
'"getParameter":function(name){',
'return({',
'"alma":"bela"',
'})[name];',
'}',
'});\n',
].join("")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,18 @@ class SingleFileModuleWrapperTest extends WrapperTestBase {
"com.example.alma": ["com.example.bela"].toSet(),
"com.example.bela": [].toSet()
]
def result = new SingleFileModuleWrapper().makeApplication(dependencyTree, "com.example.test", true)
def result = new SingleFileModuleWrapper().makeApplication(dependencyTree, "com.example.test", true, [alma: "bela"])

expect:
result == [
'var mainModule=modules["com.example.test"]["module"];',
'mainModule["main"]();'
'mainModule["main"]({',
'"getParameter":function(name){',
'return({',
'"alma":"bela"',
'})[name];',
'}',
'});',
].join("")
}
}
Loading

0 comments on commit c9c3ee9

Please sign in to comment.