Skip to content

Commit

Permalink
Allow -log argument for Eclipse compiler
Browse files Browse the repository at this point in the history
If the -log argument is used, the resulting log file is scanned for compiler output, both text and xml formatting supported. Otherwise a temporary log file is used to capture compiler output.

* Unit tests refactored
* Output emitted as "INFO" are reported as Kind.NOTE
* Column count adjusted to be 1-based index
  • Loading branch information
jftsunami authored and gnodet committed Oct 28, 2023
1 parent 77d2c17 commit 5911e64
Show file tree
Hide file tree
Showing 27 changed files with 2,060 additions and 101 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,20 @@ protected List<String> getClasspath() throws Exception {

protected void configureCompilerConfig(CompilerConfiguration compilerConfig) {}

/**
* Called once per compile iteration to allow configuration customization for
* tests.
*
* @param compilerConfig
* configuration used for this compile iteration.
* @param filename
* file about to be compiled this iteration.
* @since 2.14.0
*/
protected void configureCompilerConfig(CompilerConfiguration compilerConfig, String filename) {
configureCompilerConfig(compilerConfig);
}

@Test
public void testCompilingSources() throws Exception {
List<CompilerMessage> messages = new ArrayList<>();
Expand Down Expand Up @@ -257,7 +271,7 @@ private List<CompilerConfiguration> getCompilerConfigurations() throws Exception

compilerConfig.setForceJavacCompilerUse(this.forceJavacCompilerUse);

configureCompilerConfig(compilerConfig);
configureCompilerConfig(compilerConfig, filename);

String target = getTargetVersion();
if (StringUtils.isNotEmpty(target)) {
Expand Down Expand Up @@ -319,6 +333,12 @@ protected int expectedWarnings() {
return 0;
}

/**
* Count of output generated at the {@link Kind#NOTE} level.
*
* @return count
* @since 2.14.0
*/
protected int expectedNotes() {
return 0;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* The MIT License
*
* Copyright (c) 2005, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.codehaus.plexus.compiler.eclipse;

import java.io.File;
import java.util.List;

import org.codehaus.plexus.compiler.CompilerMessage;

/**
* Log parser interface.
*
* @author <a href="mailto:[email protected]">Jason Faust</a>
* @since 2.14.0
*/
public interface EcjLogParser {

/**
* Pares an Eclipse Compiler log file.
*
* @param logFile file to parse.
* @param errorsAsWarnings if errors should be down-graded to warnings.
* @return the messages.
* @throws Exception on parse errors.
*/
List<CompilerMessage> parse(File logFile, boolean errorsAsWarnings) throws Exception;
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@

/**
* @author <a href="mailto:[email protected]">Frits Jalvingh</a>
* @author <a href="mailto:[email protected]">Jason Faust</a>
* Created on 31-3-18.
*/
public class EcjResponseParser {
public class EcjResponseParser implements EcjLogParser {
/*--------------------------------------------------------------*/
/* CODING: Decode ECJ -log format results. */
/*--------------------------------------------------------------*/
Expand All @@ -40,6 +41,7 @@ private static XMLInputFactory getStreamFactory() {
* @param errorsAsWarnings should we treat errors as warnings
* Scan the specified response file for compilation messages.
*/
@Override
public List<CompilerMessage> parse(File xmltf, boolean errorsAsWarnings) throws Exception {
// if(xmltf.length() < 80)
// return;
Expand Down Expand Up @@ -106,20 +108,33 @@ private void decodeProblem(
throws Exception {
String id = xsr.getAttributeValue(null, "optionKey"); // Key for the problem
int startline = getInt(xsr, "line");
int column = getInt(xsr, "charStart");
int endCol = getInt(xsr, "charEnd");
int column = 0;
int endCol = 0;
String sev = xsr.getAttributeValue(null, "severity");
String message = "Unknown message?";

// -- Go watch for "message"
// -- Go watch for "message" and "source_context"
while (xsr.hasNext()) {
int type = xsr.nextTag();
if (type == XMLStreamConstants.START_ELEMENT) {
if ("message".equals(xsr.getLocalName())) {
message = xsr.getAttributeValue(null, "value");
}
if ("source_context".equals(xsr.getLocalName())) {
column = getInt(xsr, "sourceStart");
if (column != -1) {
column += 1; // Offset to 1-based index
} else {
column = 0;
}
endCol = getInt(xsr, "sourceEnd");
if (endCol != -1) {
endCol += 1; // Offset to 1-based index
} else {
endCol = 0;
}
}
ignoreTillEnd(xsr);

} else if (type == XMLStreamConstants.END_ELEMENT) {
break;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* The MIT License
*
* Copyright (c) 2005, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.codehaus.plexus.compiler.eclipse;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.codehaus.plexus.compiler.CompilerMessage;
import org.codehaus.plexus.compiler.CompilerMessage.Kind;

/**
* Parser for non-XML Eclipse Compiler output.
*
* @author <a href="mailto:[email protected]">Jason Faust</a>
* @since 2.14.0
*/
public class EcjTextLogParser implements EcjLogParser {

private static final String TEN_DASH = "----------";
private static final String PATTERN_LEVEL_FILE = "^\\d+\\.\\s+(\\w+)\\s+in\\s+(.*)\\s+\\(at line (\\d+)\\)$";

private Pattern levelFile = Pattern.compile(PATTERN_LEVEL_FILE);

@Override
public List<CompilerMessage> parse(File logFile, boolean errorsAsWarnings) throws Exception {
List<CompilerMessage> ret = new ArrayList<>();
try (BufferedReader in =
new BufferedReader(new InputStreamReader(new FileInputStream(logFile), StandardCharsets.UTF_8))) {
String line;
List<String> buffer = new LinkedList<>();
boolean header = true;

while ((line = in.readLine()) != null) {
if (header) {
if (!line.startsWith(TEN_DASH)) {
continue;
}
header = false;
}
if (line.startsWith(TEN_DASH)) {
if (!buffer.isEmpty()) {
ret.add(parse(buffer, errorsAsWarnings));
}
buffer.clear();
} else {
buffer.add(line);
}
}
}
return ret;
}

private CompilerMessage parse(List<String> buffer, boolean errorsAsWarnings) {

Kind kind = null;
String file = null;
int lineNum = 0;
int startCol = 0;
int endCol = 0;
String message = null;

// First line, kind, file, lineNum
if (buffer.size() > 1) {
String str = buffer.get(0);
Matcher matcher = levelFile.matcher(str);
if (matcher.find()) {
file = matcher.group(2);
kind = decodeKind(matcher.group(1), errorsAsWarnings);
lineNum = Integer.parseInt(matcher.group(3));
}
}

// Last line, message
if (buffer.size() >= 2) {
String str = buffer.get(buffer.size() - 1);
message = str.trim();
}

// 2nd to last line, columns
if (buffer.size() >= 3) {
String str = buffer.get(buffer.size() - 2);
startCol = str.indexOf('^');
endCol = str.lastIndexOf('^');
}

return new CompilerMessage(file, kind, lineNum, startCol, lineNum, endCol, message);
}

private Kind decodeKind(String str, boolean errorsAsWarnings) {
if (str.equals("ERROR")) {
return errorsAsWarnings ? Kind.WARNING : Kind.ERROR;
}
if (str.equals("INFO")) {
return Kind.NOTE;
}
return Kind.WARNING;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
package org.codehaus.plexus.compiler.eclipse;

/**
* The MIT License
* <p>
Expand All @@ -23,6 +21,8 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.codehaus.plexus.compiler.eclipse;

import javax.inject.Named;
import javax.inject.Singleton;
import javax.tools.Diagnostic;
Expand All @@ -32,6 +32,7 @@
import javax.tools.StandardJavaFileManager;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
Expand All @@ -42,6 +43,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;

Expand Down Expand Up @@ -198,6 +200,28 @@ public CompilerResult performCompile(CompilerConfiguration config) throws Compil
}
}

// Check for custom -log
boolean tempLog;
File logFile;
EcjLogParser logParser;
Map<String, String> extras = config.getCustomCompilerArgumentsAsMap();
if (extras.containsKey("-log")) {
String key = extras.get("-log");
logFile = new File(key);
tempLog = false;
logParser = key.endsWith(".xml") ? new EcjResponseParser() : new EcjTextLogParser();
} else {
try {
logFile = File.createTempFile("ecjerr-", ".xml");
} catch (IOException e) {
throw new CompilerException("Unable to create temporary file for compiler output", e);
}
args.add("-log");
args.add(logFile.toString());
tempLog = true;
logParser = new EcjResponseParser();
}

// -- classpath
List<String> classpathEntries = new ArrayList<>(config.getClasspathEntries());
classpathEntries.add(config.getOutputLocation());
Expand Down Expand Up @@ -343,29 +367,31 @@ public void worked(int i, int i1) {}
});
log.debug(sw.toString());

if (errorF.length() < 80) {
if (logFile.length() < 80) {
throw new EcjFailureException(sw.toString());
}
messageList = new EcjResponseParser().parse(errorF, errorsAsWarnings);
messageList = logParser.parse(errorF, errorsAsWarnings);
} finally {
if (null != errorF) {
if (tempLog) {
try {
errorF.delete();
logFile.delete();
} catch (Exception x) {
}
}
}
}
boolean hasError = false;
for (CompilerMessage compilerMessage : messageList) {
if (compilerMessage.isError()) {
if (compilerMessage.isError()
|| (compilerMessage.getKind() == CompilerMessage.Kind.WARNING
|| compilerMessage.getKind() == CompilerMessage.Kind.MANDATORY_WARNING)
&& config.isFailOnWarning()) {
hasError = true;
break;
}
}
if (!hasError && !success && !errorsAsWarnings) {
CompilerMessage.Kind kind =
errorsAsWarnings ? CompilerMessage.Kind.WARNING : CompilerMessage.Kind.ERROR;
CompilerMessage.Kind kind = CompilerMessage.Kind.ERROR;

// -- Compiler reported failure but we do not seem to have one -> probable
// exception
Expand Down Expand Up @@ -437,7 +463,7 @@ static boolean processCustomArguments(CompilerConfiguration config, List<String>
if (null != optionValue) {
File propFile = new File(optionValue);
if (!propFile.exists() || !propFile.isFile()) {
throw new IllegalArgumentException(
throw new EcjFailureException(
"Properties file specified by -properties " + propFile + " does not exist");
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package org.codehaus.foo;

public class Info {
{
"".equals(Integer.valueOf(1));
}
}
Loading

0 comments on commit 5911e64

Please sign in to comment.