本文整理汇总了Java中com.google.javascript.jscomp.CommandLineRunner类的典型用法代码示例。如果您正苦于以下问题:Java CommandLineRunner类的具体用法?Java CommandLineRunner怎么用?Java CommandLineRunner使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CommandLineRunner类属于com.google.javascript.jscomp包,在下文中一共展示了CommandLineRunner类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: runSafe
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
@Override
protected void runSafe() throws Exception {
try {
CommandLineRunner clr = new GccCommandLineRunner(
new BufferedInputStream(srcFile.getContents()),
new PrintStream(out),
new PrintStream(console.newMessageStream()));
clr.setExitCodeReceiver((r) -> { return null; });
clr.run();
} finally {
out.close();
}
}
示例2: getDefaultExterns
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
/**
* Gets the default externs set.
*
* Adapted from {@link CommandLineRunner}.
*/
private List<JSSourceFile> getDefaultExterns() {
try {
return CommandLineRunner.getDefaultExterns();
} catch (IOException e) {
throw new BuildException(e);
}
}
示例3: build
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
public static String build(Task task, List<File> inputs) {
List<SourceFile> externs;
try {
externs = CommandLineRunner.getDefaultExterns();
} catch (IOException e) {
throw new BuildException(e);
}
List<SourceFile> jsInputs = new ArrayList<SourceFile>();
for (File f : inputs) {
jsInputs.add(SourceFile.fromFile(f));
}
CompilerOptions options = new CompilerOptions();
CompilationLevel.ADVANCED_OPTIMIZATIONS
.setOptionsForCompilationLevel(options);
WarningLevel.VERBOSE.setOptionsForWarningLevel(options);
for (DiagnosticGroup dg : diagnosticGroups) {
options.setWarningLevel(dg, CheckLevel.ERROR);
}
options.setCodingConvention(new GoogleCodingConvention());
Compiler compiler = new Compiler();
MessageFormatter formatter =
options.errorFormat.toFormatter(compiler, false);
AntErrorManager errorManager = new AntErrorManager(formatter, task);
compiler.setErrorManager(errorManager);
Result r = compiler.compile(externs, jsInputs, options);
if (!r.success) {
return null;
}
String wrapped = "(function(){" + compiler.toSource() + "})();\n";
return wrapped;
}
示例4: getDefaultExterns
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
/**
* Gets the default externs set.
*
* Adapted from {@link CommandLineRunner}.
*/
private List<SourceFile> getDefaultExterns() {
try {
return CommandLineRunner.getDefaultExterns();
} catch (IOException e) {
throw new BuildException(e);
}
}
示例5: closureCompile
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
/**
* Compiles the scripts from the given files into a single script using the
* Google closure compiler. Any problems encountered are logged as warnings
* or errors (depending on severity).
* <p>
* For better understanding what is going on in this method, please read
* "Closure: The Definitve Guide" by M. Bolin. Especially chapters 12 and 14
* explain how to use the compiler programmatically.
*/
private String closureCompile(CompilationLevel level,
List<JavaScriptFile> inputFiles, List<JavaScriptFile> externFiles,
ILogger logger) {
CollectingErrorManager collectingErrorManager = new CollectingErrorManager(
inputFiles, externFiles);
Compiler compiler = new Compiler(collectingErrorManager);
Compiler.setLoggingLevel(Level.OFF);
List<JSSourceFile> defaultExterns = new ArrayList<JSSourceFile>();
try {
defaultExterns = CommandLineRunner.getDefaultExterns();
} catch (IOException e) {
logger.error(
"Could not load closure's default externs! Probably this will prevent compilation.",
e);
}
Result result = compiler.compile(
createJSSourceFiles(externFiles, defaultExterns),
createJSSourceFiles(inputFiles, new ArrayList<JSSourceFile>()),
determineOptions(level));
if (!collectingErrorManager.messages.isEmpty()) {
logger.warn(new ListStructuredLogMessage(
"JavaScript compilation produced "
+ collectingErrorManager.messages.size()
+ " errors and warnings",
collectingErrorManager.messages, JavaScriptManager.LOG_TAG));
}
if (!result.success) {
logger.error("Compilation of JavaScript code failed! Falling back to concatenated script.");
return concatScripts(inputFiles);
}
return StringUtils.normalizeLineBreaks(compiler.toSource());
}
示例6: getBuiltinExterns
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
/**
* Gets the default externs set.
*
* Adapted from {@link CommandLineRunner}.
*/
private List<SourceFile> getBuiltinExterns(CompilerOptions options) {
try {
return CommandLineRunner.getBuiltinExterns(options.getEnvironment());
} catch (IOException e) {
throw new BuildException(e);
}
}
示例7: getInputs
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
private List<String> getInputs() throws IOException {
Set<String> patterns = new HashSet<>();
// The args4j library can't handle multiple files provided within the same flag option,
// like --inputs=file1.js,file2.js so handle that here.
Splitter commaSplitter = Splitter.on(',');
for (String input : inputs) {
patterns.addAll(commaSplitter.splitToList(input));
}
patterns.addAll(arguments);
return CommandLineRunner.findJsFiles(patterns);
}
示例8: getExterns
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
private List<String> getExterns() throws IOException {
Set<String> patterns = new HashSet<>();
// The args4j library can't handle multiple files provided within the same flag option,
// like --externs=file1.js,file2.js so handle that here.
Splitter commaSplitter = Splitter.on(',');
for (String extern : externs) {
patterns.addAll(commaSplitter.splitToList(extern));
}
return CommandLineRunner.findJsFiles(patterns);
}
示例9: compile
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
public Result compile(Node script) throws IOException {
CompilerInput input = new CompilerInput(new SyntheticAst(script));
JSModule jsModule = new JSModule("fuzzedModule");
jsModule.add(input);
Compiler.setLoggingLevel(level.getLevel());
Compiler compiler = new Compiler();
compiler.setTimeout(30);
compiler.disableThreads();
return compiler.compileModules(
CommandLineRunner.getDefaultExterns(),
Arrays.asList(jsModule), getOptions());
}
示例10: compile
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
public Result compile(Node script) throws IOException {
CompilerInput input = new CompilerInput(new SyntheticAst(script));
JSModule jsModule = new JSModule("fuzzedModule");
jsModule.add(input);
Compiler compiler = new Compiler();
compiler.setTimeout(30);
return compiler.compileModules(
CommandLineRunner.getDefaultExterns(),
Arrays.asList(jsModule), getOptions());
}
示例11: execute
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
File theBaseDirectory = new File(buldDirectory);
File theBytecoderDirectory = new File(theBaseDirectory, "bytecoder");
theBytecoderDirectory.mkdirs();
try {
ClassLoader theLoader = prepareClassLoader();
Class theTargetClass = theLoader.loadClass(mainClass);
CompileTarget theCompileTarget = new CompileTarget(theLoader, CompileTarget.BackendType.valueOf(backend));
File theBytecoderFileName = new File(theBytecoderDirectory, theCompileTarget.generatedFileName());
BytecodeMethodSignature theSignature = new BytecodeMethodSignature(BytecodePrimitiveTypeRef.VOID,
new BytecodeTypeRef[] { new BytecodeArrayTypeRef(BytecodeObjectTypeRef.fromRuntimeClass(TString.class), 1) });
CompileOptions theOptions = new CompileOptions(new Slf4JLogger(), debugOutput, KnownOptimizer.ALL, relooperEnabled);
CompileResult theCode = theCompileTarget.compileToJS(theOptions, theTargetClass, "main", theSignature);
try (PrintWriter theWriter = new PrintWriter(new FileWriter(theBytecoderFileName))) {
theWriter.println(theCode.getData());
}
if (optimizeWithGoogleClosure) {
Compiler theCompiler = new Compiler();
CompilerOptions theClosureOptions = new CompilerOptions();
theClosureOptions.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT5_STRICT);
theClosureOptions.setLanguageOut(CompilerOptions.LanguageMode.ECMASCRIPT5_STRICT);
CompilationLevel.valueOf(closureOptimizationLevel).setOptionsForCompilationLevel(theClosureOptions);
List<SourceFile> theSourceFiles = CommandLineRunner.getBuiltinExterns(CompilerOptions.Environment.BROWSER);
theSourceFiles.add(SourceFile.fromCode("bytecoder.js", (String) theCode.getData()));
theCompiler.compile(new ArrayList<>(), theSourceFiles, theClosureOptions);
String theClosureCode = theCompiler.toSource();
File theBytecoderClosureFileName = new File(theBytecoderDirectory, "bytecoder-closure.js");
try (PrintWriter theWriter = new PrintWriter(new FileWriter(theBytecoderClosureFileName))) {
theWriter.println(theClosureCode);
}
}
if (theCode instanceof WASMCompileResult) {
WASMCompileResult theWASMCompileResult = (WASMCompileResult) theCode;
int[] theWASM = wat2wasm(theWASMCompileResult);
File theBytecoderWASMFileName = new File(theBytecoderDirectory, "bytecoder.wasm");
try (FileOutputStream theFos = new FileOutputStream(theBytecoderWASMFileName)) {
for (int aTheWASM : theWASM) {
theFos.write(aTheWASM);
}
}
}
} catch (Exception e) {
throw new MojoExecutionException("Error running bytecoder", e);
}
}
示例12: execute
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
@Override
public void execute() {
if (this.outputFile == null) {
throw new BuildException("outputFile attribute must be set");
}
Compiler.setLoggingLevel(Level.OFF);
CompilerOptions options = createCompilerOptions();
Compiler compiler = createCompiler(options);
List<SourceFile> externs = findExternFiles(options);
List<SourceFile> sources = findSourceFiles();
if (isStale() || forceRecompile) {
log("Compiling " + sources.size() + " file(s) with " +
externs.size() + " extern(s)");
Result result = compiler.compile(externs, sources, options);
if (result.success) {
StringBuilder source = new StringBuilder(compiler.toSource());
if (this.outputWrapperFile != null) {
try {
this.outputWrapper = Files.asCharSource(this.outputWrapperFile, UTF_8).read();
} catch (Exception e) {
throw new BuildException("Invalid output_wrapper_file specified.");
}
}
if (this.outputWrapper != null) {
int pos = this.outputWrapper.indexOf(CommandLineRunner.OUTPUT_MARKER);
if (pos > -1) {
String prefix = this.outputWrapper.substring(0, pos);
source.insert(0, prefix);
// end of outputWrapper
int suffixStart = pos + CommandLineRunner.OUTPUT_MARKER.length();
String suffix = this.outputWrapper.substring(suffixStart);
source.append(suffix);
} else {
throw new BuildException("Invalid output_wrapper specified. " +
"Missing '" + CommandLineRunner.OUTPUT_MARKER + "'.");
}
}
if (result.sourceMap != null) {
flushSourceMap(result.sourceMap);
}
writeResult(source.toString());
} else {
throw new BuildException("Compilation failed.");
}
} else {
log("None of the files changed. Compilation skipped.");
}
}
示例13: doMain
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
private void doMain(String[] args) throws Exception {
CmdLineParser parser = new CmdLineParser(this);
parser.parseArgument(args);
if (args.length < 1 || displayHelp) {
CmdLineParser p = new CmdLineParser(this);
p.printUsage(System.out);
return;
}
checkArgument(
!Strings.isNullOrEmpty(refasterJsTemplate), "--refasterjs_template must be provided");
List<String> fileInputs = getInputs();
checkArgument(
!fileInputs.isEmpty(), "At least one input must be provided in the --inputs flag.");
for (String input : fileInputs) {
Preconditions.checkArgument(
new File(input).exists(), "Input file %s does not exist.", input);
}
if (!verbose) {
// This is done here instead of using the Compiler#setLoggingLevel function since the
// Compiler is created and then run inside of RefactoringDriver.
Logger errorManagerLogger = Logger.getLogger("com.google.javascript.jscomp");
errorManagerLogger.setLevel(Level.OFF);
}
RefasterJsScanner scanner = new RefasterJsScanner();
scanner.setTypeMatchingStrategy(typeMatchingStrategy);
scanner.loadRefasterJsTemplate(refasterJsTemplate);
CompilerOptions options = new CompilerOptions();
options.setEnvironment(environment);
RefactoringDriver driver =
new RefactoringDriver.Builder()
.addExterns(CommandLineRunner.getBuiltinExterns(environment))
.addExternsFromFile(getExterns())
.addInputsFromFile(fileInputs)
.build();
System.out.println("Compiling JavaScript code and searching for suggested fixes.");
// TODO(bangert): allow picking a non-default choice in RefasterJS, e.g. via a switch.
List<SuggestedFix> fixes = driver.drive(scanner);
if (!verbose) {
// When running in quiet mode, the Compiler's error manager will not have printed
// this information itself.
ErrorManager errorManager = driver.getCompiler().getErrorManager();
System.out.println("Compiler results: " + errorManager.getErrorCount()
+ " errors and " + errorManager.getWarningCount() + " warnings.");
}
System.out.println("Found " + fixes.size() + " suggested fixes.");
if (dryRun) {
if (!fixes.isEmpty()) {
System.out.println("SuggestedFixes: " + fixes);
}
} else {
Set<String> affectedFiles = new TreeSet<>();
for (SuggestedFix fix : fixes) {
affectedFiles.addAll(fix.getReplacements().keySet());
}
System.out.println("Modifying affected files: " + affectedFiles);
ApplySuggestedFixes.applySuggestedFixesToFiles(fixes);
}
}
示例14: assertFileRefactoring
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
/**
* Performs refactoring using a RefasterJs template and asserts that result is as expected.
*
* @param refasterJsTemplate path of the file or resource containing the RefasterJs template to
* apply
* @param testDataPathPrefix path prefix of the directory from which input and expected-output
* file will be read
* @param originalFile file name of the JavaScript source file to apply the refaster template to
* @param additionalSourceFiles list of additional source files to provide to the compiler (e.g.
* dependencies)
* @param expectedFileChoices the expected result options of applying the specified template to
* {@code originalFile}
* @throws IOException
*/
public static void assertFileRefactoring(
String refasterJsTemplate,
String testDataPathPrefix,
String originalFile,
List<String> additionalSourceFiles,
String... expectedFileChoices)
throws IOException {
RefasterJsScanner scanner = new RefasterJsScanner();
scanner.loadRefasterJsTemplate(refasterJsTemplate);
final String originalFilePath = testDataPathPrefix + File.separator + originalFile;
ImmutableList.Builder<String> expectedCodeBuilder = ImmutableList.builder();
for (String expectedFile : expectedFileChoices) {
expectedCodeBuilder.add(slurpFile(testDataPathPrefix + File.separator + expectedFile));
}
final ImmutableList<String> expectedCode = expectedCodeBuilder.build();
RefactoringDriver.Builder driverBuilder =
new RefactoringDriver.Builder()
.addExterns(CommandLineRunner.getBuiltinExterns(CompilerOptions.Environment.BROWSER));
for (String additionalSource : additionalSourceFiles) {
driverBuilder.addInputsFromFile(testDataPathPrefix + File.separator + additionalSource);
}
RefactoringDriver driver = driverBuilder.addInputsFromFile(originalFilePath).build();
List<SuggestedFix> fixes = driver.drive(scanner);
assertThat(driver.getCompiler().getErrors()).isEmpty();
assertThat(driver.getCompiler().getWarnings()).isEmpty();
ImmutableList<String> newCode =
ApplySuggestedFixes.applyAllSuggestedFixChoicesToCode(
fixes, ImmutableMap.of(originalFilePath, slurpFile(originalFilePath)))
.stream()
.map(m -> m.get(originalFilePath))
.collect(ImmutableList.toImmutableList());
assertThat(newCode)
.comparingElementsUsing(new IgnoringWhitespaceCorrespondence())
.containsExactlyElementsIn(expectedCode);
}
示例15: execute
import com.google.javascript.jscomp.CommandLineRunner; //导入依赖的package包/类
@Override
public void execute() {
if (this.outputFile == null) {
throw new BuildException("outputFile attribute must be set");
}
Compiler.setLoggingLevel(Level.OFF);
CompilerOptions options = createCompilerOptions();
Compiler compiler = createCompiler(options);
List<SourceFile> externs = findExternFiles();
List<SourceFile> sources = findSourceFiles();
if (isStale() || forceRecompile) {
log("Compiling " + sources.size() + " file(s) with " +
externs.size() + " extern(s)");
Result result = compiler.compile(externs, sources, options);
if (result.success) {
StringBuilder source = new StringBuilder(compiler.toSource());
if (this.outputWrapper != null) {
int pos = -1;
pos = this.outputWrapper.indexOf(CommandLineRunner.OUTPUT_MARKER);
if (pos > -1) {
String prefix = this.outputWrapper.substring(0, pos);
source.insert(0, prefix);
// end of outputWrapper
int suffixStart = pos + CommandLineRunner.OUTPUT_MARKER.length();
String suffix = this.outputWrapper.substring(suffixStart);
source.append(suffix);
}
}
if (result.sourceMap != null) {
flushSourceMap(result.sourceMap);
source.append(System.getProperty("line.separator"));
source.append("//@ sourceMappingURL=" + sourceMapOutputFile.getName());
}
writeResult(source.toString());
} else {
throw new BuildException("Compilation failed.");
}
} else {
log("None of the files changed. Compilation skipped.");
}
}