use of com.google.template.soy.msgs.SoyMsgBundle in project closure-templates by google.
the class FeaturesUsage method execMain.
private void execMain(String[] args) throws IOException {
CmdLineParser cmdLineParser = new CmdLineParser(this);
cmdLineParser.setUsageWidth(100);
try {
cmdLineParser.parseArgument(args);
} catch (CmdLineException cle) {
System.err.println("\nError: " + cle.getMessage() + "\n\n");
System.err.println(USAGE_PREFIX);
cmdLineParser.printUsage(System.err);
System.exit(1);
}
Injector injector = Guice.createInjector(new SoyModule());
SoyFileSet.Builder sfsBuilder = injector.getInstance(SoyFileSet.Builder.class);
SoyFileSet sfs = sfsBuilder.add(Resources.getResource("simple.soy")).add(Resources.getResource("features.soy")).setCompileTimeGlobals(Resources.getResource("FeaturesUsage_globals.txt")).build();
SoyTofu tofu = sfs.compileToTofu().forNamespace("soy.examples.features");
SoyMsgBundle msgBundle;
if (locale.length() > 0) {
// Use translations from an XLIFF file.
SoyMsgBundleHandler msgBundleHandler = injector.getInstance(SoyMsgBundleHandler.class);
URL xliffResource = Resources.getResource(XLIFF_RESOURCE_PREFIX + locale + ".xlf");
msgBundle = msgBundleHandler.createFromResource(xliffResource);
if (msgBundle.getLocaleString() == null) {
throw new IOException("Error reading message resource \"" + XLIFF_RESOURCE_PREFIX + locale + ".xlf\".");
}
} else {
// Use the messages from the Soy source files.
msgBundle = null;
}
// Note: In the examples below, I sometimes use the version of render() that takes a SoyMapData
// and sometimes use the version that takes a Map<String, ?>. They both work. The version that
// takes a SoyMapData is more efficient if you need to reuse the same template data object for
// multiple calls of render() (because the version that takes a Map<String, ?> internally
// converts it to a new SoyMapData on every call).
writeExampleHeader("demoComments");
System.out.println(tofu.newRenderer(DEMO_COMMENTS).setMsgBundle(msgBundle).render());
writeExampleHeader("demoLineJoining");
System.out.println(tofu.newRenderer(DEMO_LINE_JOINING).setMsgBundle(msgBundle).render());
writeExampleHeader("demoRawTextCommands");
System.out.println(tofu.newRenderer(DEMO_RAW_TEXT_COMMANDS).setMsgBundle(msgBundle).setContentKind(SanitizedContent.ContentKind.TEXT).render());
writeExampleHeader("demoPrint");
System.out.println(tofu.newRenderer(DEMO_PRINT).setData(new SoyMapData(DemoPrintSoyTemplateInfo.BOO, "Boo!", DemoPrintSoyTemplateInfo.TWO, 2)).setMsgBundle(msgBundle).render());
writeExampleHeader("demoAutoescapeTrue");
System.out.println(tofu.newRenderer(DEMO_AUTOESCAPE_TRUE).setData(new SoyMapData(DemoAutoescapeTrueSoyTemplateInfo.ITALIC_HTML, "<i>italic</i>")).setMsgBundle(msgBundle).render());
writeExampleHeader("demoMsg");
System.out.println(tofu.newRenderer(DEMO_MSG).setData(ImmutableMap.of(DemoMsgSoyTemplateInfo.NAME, "Ed", DemoMsgSoyTemplateInfo.LABS_URL, "http://labs.google.com")).setMsgBundle(msgBundle).render());
writeExampleHeader("demoIf");
System.out.println(tofu.newRenderer(DEMO_IF).setData(new SoyMapData("pi", 3.14159)).setMsgBundle(msgBundle).render());
System.out.println(tofu.newRenderer(DEMO_IF).setData(new SoyMapData("pi", 2.71828)).setMsgBundle(msgBundle).render());
System.out.println(tofu.newRenderer(DEMO_IF).setData(new SoyMapData("pi", 1.61803)).setMsgBundle(msgBundle).render());
writeExampleHeader("demoSwitch");
System.out.println(tofu.newRenderer(DEMO_SWITCH).setData(ImmutableMap.of("name", "Fay")).setMsgBundle(msgBundle).render());
System.out.println(tofu.newRenderer(DEMO_SWITCH).setData(ImmutableMap.of("name", "Go")).setMsgBundle(msgBundle).render());
System.out.println(tofu.newRenderer(DEMO_SWITCH).setData(ImmutableMap.of("name", "Hal")).setMsgBundle(msgBundle).render());
System.out.println(tofu.newRenderer(DEMO_SWITCH).setData(ImmutableMap.of("name", "Ivy")).setMsgBundle(msgBundle).render());
writeExampleHeader("demoFor");
SoyListData persons = new SoyListData();
persons.add(new SoyMapData("name", "Jen", "numWaffles", 1));
persons.add(new SoyMapData("name", "Kai", "numWaffles", 3));
persons.add(new SoyMapData("name", "Lex", "numWaffles", 1));
persons.add(new SoyMapData("name", "Mel", "numWaffles", 2));
System.out.println(tofu.newRenderer(DEMO_FOR).setData(new SoyMapData(DemoForSoyTemplateInfo.PERSONS, persons)).setMsgBundle(msgBundle).render());
writeExampleHeader("demoFor_Range");
System.out.println(tofu.newRenderer(DEMO_FOR_RANGE).setData(new SoyMapData(DemoForRangeSoyTemplateInfo.NUM_LINES, 3)).setMsgBundle(msgBundle).render());
writeExampleHeader("demoCallWithoutParam");
System.out.println(tofu.newRenderer(DEMO_CALL_WITHOUT_PARAM).setData(new SoyMapData(DemoCallWithoutParamSoyTemplateInfo.NAME, "Neo", DemoCallWithoutParamSoyTemplateInfo.TRIP_INFO, new SoyMapData("name", "Neo", "destination", "The Matrix"))).setMsgBundle(msgBundle).render());
writeExampleHeader("demoCallWithParam");
System.out.println(tofu.newRenderer(DEMO_CALL_WITH_PARAM).setData(ImmutableMap.of(DemoCallWithParamSoyTemplateInfo.NAME, "Oz", DemoCallWithParamSoyTemplateInfo.COMPANION_NAME, "Pip", DemoCallWithParamSoyTemplateInfo.DESTINATIONS, ImmutableList.of("Gillikin Country", "Munchkin Country", "Quadling Country", "Winkie Country"))).setMsgBundle(msgBundle).render());
writeExampleHeader("demoCallWithParamBlock");
System.out.println(tofu.newRenderer(DEMO_CALL_WITH_PARAM_BLOCK).setData(new SoyMapData(DemoCallWithParamBlockSoyTemplateInfo.NAME, "Quo")).setMsgBundle(msgBundle).render());
writeExampleHeader("demoExpressions");
SoyListData students = new SoyListData();
students.add(new SoyMapData("name", "Rob", "major", "Physics", "year", 1999));
students.add(new SoyMapData("name", "Sha", "major", "Finance", "year", 1980));
students.add(new SoyMapData("name", "Tim", "major", "Engineering", "year", 2005));
students.add(new SoyMapData("name", "Uma", "major", "Biology", "year", 1972));
System.out.println(tofu.newRenderer(DEMO_EXPRESSIONS).setData(new SoyMapData(DemoExpressionsSoyTemplateInfo.STUDENTS, students, DemoExpressionsSoyTemplateInfo.CURRENT_YEAR, 2008)).setMsgBundle(msgBundle).render());
writeExampleHeader("demoDoubleBraces");
System.out.println(tofu.newRenderer(DEMO_DOUBLE_BRACES).setData(ImmutableMap.of(DemoDoubleBracesSoyTemplateInfo.SET_NAME, "prime numbers", DemoDoubleBracesSoyTemplateInfo.SET_MEMBERS, ImmutableList.of(2, 3, 5, 7, 11, 13))).setMsgBundle(msgBundle).setContentKind(SanitizedContent.ContentKind.TEXT).render());
// The Hebrew in the following example comes out as question marks in the output because
// System.out (and by default stdout generally) is set up to use a Latin encoding. To see
// this really in action, run the Javascript example.
writeExampleHeader("demoBidiSupport");
System.out.println(tofu.newRenderer(DEMO_BIDI_SUPPORT).setData(ImmutableMap.of(DemoBidiSupportSoyTemplateInfo.TITLE, "2008: A BiDi Odyssey", DemoBidiSupportSoyTemplateInfo.AUTHOR, "John Doe, Esq.", DemoBidiSupportSoyTemplateInfo.YEAR, "1973", DemoBidiSupportSoyTemplateInfo.KEYWORDS, ImmutableList.of("Bi(Di)", "2008 (\u05E9\u05E0\u05D4)", "2008 (year)"))).setMsgBundle(msgBundle).render());
}
use of com.google.template.soy.msgs.SoyMsgBundle in project closure-templates by google.
the class XliffMsgPluginTest method testGenerateExtractedMsgsFile.
@Test
public void testGenerateExtractedMsgsFile() throws Exception {
URL testSoyFile = Resources.getResource(XliffMsgPluginTest.class, "test_data/test-v2.soy");
SoyMsgBundle msgBundle = SoyFileSet.builder().add(testSoyFile).build().extractMsgs();
XliffMsgPlugin msgPlugin = new XliffMsgPlugin();
// Test without target language.
OutputFileOptions outputFileOptions = new OutputFileOptions();
CharSequence extractedMsgsFile = msgPlugin.generateExtractedMsgsFile(msgBundle, outputFileOptions, ErrorReporter.exploding());
URL expectedExtractedMsgsFile = Resources.getResource(XliffMsgPluginTest.class, "test_data/test-v2_extracted.xlf");
assertEquals(Resources.toString(expectedExtractedMsgsFile, UTF_8), extractedMsgsFile.toString());
// Test with target language.
outputFileOptions.setTargetLocaleString("x-zz");
extractedMsgsFile = msgPlugin.generateExtractedMsgsFile(msgBundle, outputFileOptions, ErrorReporter.exploding());
expectedExtractedMsgsFile = Resources.getResource(XliffMsgPluginTest.class, "test_data/test-v2_extracted_x-zz.xlf");
assertEquals(Resources.toString(expectedExtractedMsgsFile, UTF_8), extractedMsgsFile.toString());
}
use of com.google.template.soy.msgs.SoyMsgBundle in project closure-templates by google.
the class XliffMsgPluginTest method testParseTranslatedMsgsFile.
@Test
public void testParseTranslatedMsgsFile() throws Exception {
URL translatedMsgsFile = Resources.getResource(XliffMsgPluginTest.class, "test_data/test-v2_translated_x-zz.xlf");
XliffMsgPlugin msgPlugin = new XliffMsgPlugin();
SoyMsgBundle msgBundle = msgPlugin.parseTranslatedMsgsFile(Resources.toString(translatedMsgsFile, UTF_8));
assertEquals(5, msgBundle.getNumMsgs());
List<SoyMsg> msgs = Lists.newArrayList();
for (SoyMsg msg : msgBundle) {
msgs.add(msg);
}
assertEquals(5, msgs.size());
SoyMsg moscowMsg = msgs.get(0);
assertEquals(626010707674174792L, moscowMsg.getId());
List<SoyMsgPart> moscowMsgParts = moscowMsg.getParts();
assertEquals(1, moscowMsgParts.size());
assertEquals("Zmoscow", ((SoyMsgRawTextPart) moscowMsgParts.get(0)).getRawText());
assertEquals(948230478248061386L, msgs.get(1).getId());
SoyMsg mooseMsg = msgs.get(2);
assertEquals(2764913337766789440L, mooseMsg.getId());
List<SoyMsgPart> mooseMsgParts = mooseMsg.getParts();
assertEquals(7, mooseMsgParts.size());
assertEquals("Zmoose ", ((SoyMsgRawTextPart) mooseMsgParts.get(0)).getRawText());
assertEquals("START_ITALIC", ((SoyMsgPlaceholderPart) mooseMsgParts.get(1)).getPlaceholderName());
assertEquals("zalso", ((SoyMsgRawTextPart) mooseMsgParts.get(2)).getRawText());
assertEquals("END_ITALIC", ((SoyMsgPlaceholderPart) mooseMsgParts.get(3)).getPlaceholderName());
assertEquals(" zsays ", ((SoyMsgRawTextPart) mooseMsgParts.get(4)).getRawText());
assertEquals("XXX", ((SoyMsgPlaceholderPart) mooseMsgParts.get(5)).getPlaceholderName());
assertEquals(".", ((SoyMsgRawTextPart) mooseMsgParts.get(6)).getRawText());
SoyMsg cowMsg = msgs.get(3);
assertEquals(6632711700686641662L, cowMsg.getId());
List<SoyMsgPart> cowMsgParts = cowMsg.getParts();
assertEquals(3, cowMsgParts.size());
assertEquals("Zcow zsays ", ((SoyMsgRawTextPart) cowMsgParts.get(0)).getRawText());
assertEquals("MOO", ((SoyMsgPlaceholderPart) cowMsgParts.get(1)).getPlaceholderName());
assertEquals(".", ((SoyMsgRawTextPart) cowMsgParts.get(2)).getRawText());
assertEquals(8577643341484516105L, msgs.get(4).getId());
}
use of com.google.template.soy.msgs.SoyMsgBundle in project closure-templates by google.
the class SoyFileSet method compileToJsSrcFiles.
/**
* Compiles this Soy file set into JS source code files and writes these JS files to disk.
*
* @param outputPathFormat The format string defining how to build the output file path
* corresponding to an input file path.
* @param inputFilePathPrefix The prefix prepended to all input file paths (can be empty string).
* @param jsSrcOptions The compilation options for the JS Src output target.
* @param locales The list of locales. Can be an empty list if not applicable.
* @param msgPlugin The {@link SoyMsgPlugin} to use, or null if not applicable
* @param messageFilePathFormat The message file path format, or null if not applicable.
* @throws SoyCompilationException If compilation fails.
* @throws IOException If there is an error in opening/reading a message file or opening/writing
* an output JS file.
*/
@SuppressWarnings("deprecation")
void compileToJsSrcFiles(String outputPathFormat, String inputFilePathPrefix, SoyJsSrcOptions jsSrcOptions, List<String> locales, @Nullable SoyMsgPlugin msgPlugin, @Nullable String messageFilePathFormat) throws IOException {
ParseResult result = preprocessJsSrcResults(jsSrcOptions);
SoyFileSetNode soyTree = result.fileSet();
TemplateRegistry registry = result.registry();
if (locales.isEmpty()) {
// Not generating localized JS.
new JsSrcMain(apiCallScopeProvider, typeRegistry).genJsFiles(soyTree, registry, jsSrcOptions, null, null, outputPathFormat, inputFilePathPrefix, errorReporter);
} else {
checkArgument(msgPlugin != null, "a message plugin must be provided when generating localized sources");
checkArgument(messageFilePathFormat != null, "a messageFilePathFormat must be provided when generating localized sources");
// Generating localized JS.
for (String locale : locales) {
SoyFileSetNode soyTreeClone = soyTree.copy(new CopyState());
String msgFilePath = MainEntryPointUtils.buildFilePath(messageFilePathFormat, locale, null, inputFilePathPrefix);
SoyMsgBundle msgBundle = new SoyMsgBundleHandler(msgPlugin).createFromFile(new File(msgFilePath));
if (msgBundle.getLocaleString() == null) {
// begins with "en", because falling back to the Soy source will probably be fine.
if (!locale.startsWith("en")) {
throw new IOException("Error opening or reading message file " + msgFilePath);
}
}
new JsSrcMain(apiCallScopeProvider, typeRegistry).genJsFiles(soyTreeClone, registry, jsSrcOptions, locale, msgBundle, outputPathFormat, inputFilePathPrefix, errorReporter);
}
}
throwIfErrorsPresent();
reportWarnings();
}
use of com.google.template.soy.msgs.SoyMsgBundle in project closure-templates by google.
the class SoyFileSet method pruneTranslatedMsgs.
/**
* Prunes messages from a given message bundle, keeping only messages used in this Soy file set.
*
* <p>Important: Do not use directly. This is subject to change and your code will break.
*
* <p>Note: This method memoizes intermediate results to improve efficiency in the case that it is
* called multiple times (which is a common case). Thus, this method will not work correctly if
* the underlying Soy files are modified between calls to this method.
*
* @param origTransMsgBundle The message bundle to prune.
* @return The pruned message bundle.
* @throws SoyCompilationException If compilation fails.
*/
public SoyMsgBundle pruneTranslatedMsgs(SoyMsgBundle origTransMsgBundle) {
resetErrorReporter();
if (memoizedExtractedMsgIdsForPruning == null) {
ParseResult result = parse(passManagerBuilder(SyntaxVersion.V1_0).allowUnknownGlobals().disableAllTypeChecking(), // can't resolve strict types
SoyTypeRegistry.DEFAULT_UNKNOWN, new PluginResolver(PluginResolver.Mode.ALLOW_UNDEFINED, printDirectives, soyFunctionMap, errorReporter));
throwIfErrorsPresent();
SoyFileSetNode soyTree = result.fileSet();
TemplateRegistry registry = result.registry();
List<TemplateNode> allPublicTemplates = Lists.newArrayList();
for (SoyFileNode soyFile : soyTree.getChildren()) {
for (TemplateNode template : soyFile.getChildren()) {
if (template.getVisibility() == Visibility.PUBLIC) {
allPublicTemplates.add(template);
}
}
}
Map<TemplateNode, TransitiveDepTemplatesInfo> depsInfoMap = new FindTransitiveDepTemplatesVisitor(registry).execOnMultipleTemplates(allPublicTemplates);
TransitiveDepTemplatesInfo mergedDepsInfo = TransitiveDepTemplatesInfo.merge(depsInfoMap.values());
SoyMsgBundle extractedMsgBundle = new ExtractMsgsVisitor().execOnMultipleNodes(mergedDepsInfo.depTemplateSet);
ImmutableSet.Builder<Long> extractedMsgIdsBuilder = ImmutableSet.builder();
for (SoyMsg extractedMsg : extractedMsgBundle) {
extractedMsgIdsBuilder.add(extractedMsg.getId());
}
throwIfErrorsPresent();
memoizedExtractedMsgIdsForPruning = extractedMsgIdsBuilder.build();
}
// ------ Prune. ------
ImmutableList.Builder<SoyMsg> prunedTransMsgsBuilder = ImmutableList.builder();
for (SoyMsg transMsg : origTransMsgBundle) {
if (memoizedExtractedMsgIdsForPruning.contains(transMsg.getId())) {
prunedTransMsgsBuilder.add(transMsg);
}
}
throwIfErrorsPresent();
return new SoyMsgBundleImpl(origTransMsgBundle.getLocaleString(), prunedTransMsgsBuilder.build());
}
Aggregations