package org.eclipse.ant.internal.core.ant;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Vector;
import org.apache.tools.ant.AntTypeDefinition;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.BuildLogger;
import org.apache.tools.ant.ComponentHelper;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.DemuxOutputStream;
import org.apache.tools.ant.Diagnostics;
import org.apache.tools.ant.Main;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.TaskAdapter;
import org.apache.tools.ant.XmlLogger;
import org.eclipse.ant.core.AntCorePlugin;
import org.eclipse.ant.core.AntCorePreferences;
import org.eclipse.ant.core.AntSecurityException;
import org.eclipse.ant.core.ProjectInfo;
import org.eclipse.ant.core.Property;
import org.eclipse.ant.core.TargetInfo;
import org.eclipse.ant.core.Task;
import org.eclipse.ant.core.Type;
import org.eclipse.ant.internal.core.AbstractEclipseBuildLogger;
import org.eclipse.ant.internal.core.AntCoreUtil;
import org.eclipse.ant.internal.core.AntSecurityManager;
import org.eclipse.ant.internal.core.IAntCoreConstants;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.variables.VariablesPlugin;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;
public class InternalAntRunner {
private IProgressMonitor monitor;
private ArrayList<String> buildListeners;
private String buildFileLocation;
private Vector<String> targets;
private Map<String, String> userProperties;
private boolean noExplicitUserProperties = true;
private Project currentProject;
private String defaultTarget;
private BuildLogger buildLogger = null;
private String antVersionNumber = null;
private int messageOutputLevel = Project.MSG_INFO;
private boolean emacsMode = false;
private boolean projectHelp = false;
private PrintStream out = System.out;
private PrintStream err = System.err;
private String loggerClassname = null;
private String[] = null;
private boolean executed = false;
private ArrayList<String> propertyFiles = new ArrayList<>();
private URL[] customClasspath = null;
private String inputHandlerClassname = null;
private String buildAntHome = null;
private boolean keepGoing = false;
private boolean allowInput = true;
private String fEarlyErrorMessage = null;
private boolean unknownTargetsFound = false;
public void addBuildListeners(List<String> classNames) {
if (buildListeners == null) {
buildListeners = new ArrayList<>(classNames.size());
}
buildListeners.addAll(classNames);
}
protected void addBuildListener(String clazz) {
if (buildListeners == null) {
buildListeners = new ArrayList<>();
}
buildListeners.add(clazz);
}
public void addBuildLogger(String className) {
loggerClassname = className;
}
public void addUserProperties(Map<String, String> properties) {
if (userProperties == null) {
userProperties = new HashMap<>(properties);
} else {
userProperties.putAll(properties);
}
noExplicitUserProperties = false;
}
public void addPropertyFiles(String[] additionalPropertyFiles) {
propertyFiles.addAll(Arrays.asList(additionalPropertyFiles));
}
protected void addBuildListeners(Project project, boolean log) {
String className = null;
try {
BuildLogger logger = createLogger();
if (logger != null) {
project.addBuildListener(logger);
}
if (buildListeners != null) {
for (Iterator<String> iterator = buildListeners.iterator(); iterator.hasNext();) {
className = iterator.next();
Class<?> listener = Class.forName(className);
project.addBuildListener((BuildListener) listener.newInstance());
}
}
}
catch (ClassCastException e) {
String message = MessageFormat.format(InternalAntMessages.InternalAntRunner_not_an_instance_of_apache_ant_BuildListener, new Object[] {
className });
if (log) {
logMessage(null, message, Project.MSG_ERR);
}
throw new BuildException(message, e);
}
catch (BuildException e) {
throw e;
}
catch (Exception e) {
throw new BuildException(e);
}
}
private void setProperties(Project project, boolean substituteVariables) {
setBuiltInProperties(project);
if (userProperties != null) {
for (Iterator<Map.Entry<String, String>> iterator = userProperties.entrySet().iterator(); iterator.hasNext();) {
Entry<String, String> entry = iterator.next();
String value = entry.getValue();
if (substituteVariables && value != null) {
try {
value = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(value);
}
catch (CoreException e) {
}
}
if (value != null)
project.setUserProperty(entry.getKey(), value);
}
if (noExplicitUserProperties) {
setGlobalProperties(project, substituteVariables);
}
} else {
setGlobalProperties(project, substituteVariables);
}
}
protected void setBuiltInProperties(Project project) {
project.setUserProperty("ant.file", getBuildFileLocation());
project.setUserProperty("ant.version", Main.getAntVersion());
}
private void setGlobalProperties(Project project, boolean substituteVariables) {
AntCorePreferences prefs = AntCorePlugin.getPlugin().getPreferences();
List<Property> properties = prefs.getProperties();
if (properties != null) {
for (Property property : properties) {
String value = property.getValue(substituteVariables);
if (value != null) {
project.setUserProperty(property.getName(), value);
}
}
}
}
private void setTasks(Project project) {
List<Task> tasks = AntCorePlugin.getPlugin().getPreferences().getTasks();
for (Task task : tasks) {
if (isVersionCompatible("1.6")) {
AntTypeDefinition def = new AntTypeDefinition();
String name = ProjectHelper.genComponentName(task.getURI(), task.getTaskName());
def.setName(name);
def.setClassName(task.getClassName());
def.setClassLoader(this.getClass().getClassLoader());
def.setAdaptToClass(org.apache.tools.ant.Task.class);
def.setAdapterClass(TaskAdapter.class);
ComponentHelper.getComponentHelper(project).addDataTypeDefinition(def);
} else {
try {
Class<?> taskClass = Class.forName(task.getClassName());
if (isVersionCompatible("1.5")) {
try {
project.checkTaskClass(taskClass);
}
catch (BuildException e) {
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_RUNNING_BUILD, MessageFormat.format(InternalAntMessages.InternalAntRunner_Error_setting_Ant_task, new Object[] {
task.getTaskName() }), e);
AntCorePlugin.getPlugin().getLog().log(status);
continue;
}
}
project.addTaskDefinition(task.getTaskName(), taskClass);
}
catch (ClassNotFoundException e) {
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_RUNNING_BUILD, MessageFormat.format(InternalAntMessages.InternalAntRunner_Class_not_found_for_task, new Object[] {
task.getClassName(), task.getTaskName() }), e);
AntCorePlugin.getPlugin().getLog().log(status);
}
}
}
}
private void setTypes(Project project) {
List<Type> types = AntCorePlugin.getPlugin().getPreferences().getTypes();
for (Iterator<Type> iterator = types.iterator(); iterator.hasNext();) {
Type type = iterator.next();
if (isVersionCompatible("1.6")) {
AntTypeDefinition def = new AntTypeDefinition();
String name = ProjectHelper.genComponentName(type.getURI(), type.getTypeName());
def.setName(name);
def.setClassName(type.getClassName());
def.setClassLoader(this.getClass().getClassLoader());
ComponentHelper.getComponentHelper(project).addDataTypeDefinition(def);
} else {
try {
Class<?> typeClass = Class.forName(type.getClassName());
project.addDataTypeDefinition(type.getTypeName(), typeClass);
}
catch (ClassNotFoundException e) {
IStatus status = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.ERROR_RUNNING_BUILD, MessageFormat.format(InternalAntMessages.InternalAntRunner_Class_not_found_for_type, new Object[] {
type.getClassName(), type.getTypeName() }), e);
AntCorePlugin.getPlugin().getLog().log(status);
}
}
}
}
protected void parseBuildFile(Project project) {
File buildFile = new File(getBuildFileLocation());
if (!buildFile.exists()) {
throw new BuildException(MessageFormat.format(InternalAntMessages.InternalAntRunner_Buildfile_does_not_exist, new Object[] {
buildFile.getAbsolutePath() }));
}
if (!buildFile.isFile()) {
throw new BuildException(MessageFormat.format(InternalAntMessages.InternalAntRunner_Buildfile_is_not_a_file, new Object[] {
buildFile.getAbsolutePath() }));
}
if (!isVersionCompatible("1.5")) {
parseBuildFile(project, buildFile);
} else {
ProjectHelper helper = ProjectHelper.getProjectHelper();
project.addReference("ant.projectHelper", helper);
helper.parse(project, buildFile);
}
}
@Deprecated
private void parseBuildFile(Project project, File buildFile) {
ProjectHelper.configureProject(project, buildFile);
}
public List<TargetInfo> getTargets() {
try {
setJavaClassPath();
Project antProject = getProject();
processAntHome(false);
antProject.init();
setTypes(antProject);
boolean exceptionState = processProperties(AntCoreUtil.getArrayList(extraArguments));
if (fEarlyErrorMessage != null) {
if (exceptionState) {
throw new BuildException(fEarlyErrorMessage);
}
}
setProperties(antProject, false);
if (isVersionCompatible("1.5")) {
new InputHandlerSetter().setInputHandler(antProject, "org.eclipse.ant.internal.core.ant.NullInputHandler");
}
parseBuildFile(antProject);
defaultTarget = antProject.getDefaultTarget();
Hashtable<String, Target> projectTargets = antProject.getTargets();
ArrayList<TargetInfo> infos = new ArrayList<>();
ProjectInfo pinfo = new ProjectInfo(antProject.getName(), antProject.getDescription());
boolean defaultFound = false;
for (Target target : projectTargets.values()) {
String name = target.getName();
if (name.length() == 0) {
continue;
}
if (target.getName().equals(defaultTarget)) {
defaultFound = true;
}
ArrayList<String> dependencies = new ArrayList<>();
Enumeration<String> enumeration = target.getDependencies();
while (enumeration.hasMoreElements()) {
dependencies.add(enumeration.nextElement());
}
String[] dependencyArray = new String[dependencies.size()];
dependencies.toArray(dependencyArray);
TargetInfo info = new TargetInfo(pinfo, name, target.getDescription(), dependencyArray, defaultFound);
infos.add(info);
}
if (!defaultFound) {
throw new BuildException(MessageFormat.format(InternalAntMessages.InternalAntRunner_Default_target_does_not_exist, new Object[] { "'",
defaultTarget, "'" }));
}
return infos;
}
finally {
processAntHome(true);
}
}
private List<String> getTargetNames() {
try {
setJavaClassPath();
Project antProject;
antProject = getProject();
processAntHome(false);
antProject.init();
setTypes(antProject);
processProperties(AntCoreUtil.getArrayList(extraArguments));
setProperties(antProject, false);
if (isVersionCompatible("1.5")) {
new InputHandlerSetter().setInputHandler(antProject, "org.eclipse.ant.internal.core.ant.NullInputHandler");
}
parseBuildFile(antProject);
Hashtable<String, Target> projectTargets = antProject.getTargets();
ArrayList<String> names = new ArrayList<>();
for (Target target : projectTargets.values()) {
String name = target.getName();
if (name.length() == 0) {
continue;
}
names.add(name);
}
return names;
}
finally {
processAntHome(true);
}
}
private Project getProject() {
Project antProject;
if (isVersionCompatible("1.6")) {
if (isVersionCompatible("1.6.3")) {
antProject = new InternalProject2();
} else {
antProject = new Project();
}
} else {
antProject = new InternalProject();
}
return antProject;
}
public String getDefaultTarget() {
return defaultTarget;
}
public void run() {
run(AntCoreUtil.getArrayList(extraArguments));
}
private void printArguments(Project project) {
if ((messageOutputLevel != Project.MSG_DEBUG) && (messageOutputLevel != Project.MSG_VERBOSE)) {
return;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < extraArguments.length; i++) {
sb.append(extraArguments[i]);
sb.append(' ');
}
project.log(MessageFormat.format(InternalAntMessages.InternalAntRunner_Arguments, new Object[] { sb.toString().trim() }));
}
private void createMonitorBuildListener(Project project) {
if (monitor == null) {
return;
}
Vector<String> chosenTargets = targets;
if (chosenTargets == null || chosenTargets.isEmpty()) {
chosenTargets = new Vector<>(1);
String defltTarget = project.getDefaultTarget();
if (defltTarget != null) {
chosenTargets.add(defltTarget);
}
}
project.addBuildListener(new ProgressBuildListener(project, chosenTargets, monitor));
}
public void run(Object argArray) throws Exception {
run(AntCoreUtil.getArrayList((String[]) argArray));
}
private void run(List<String> argList) {
setCurrentProject(new Project());
if (isVersionCompatible("1.6.3")) {
new ExecutorSetter().setExecutor(currentProject);
}
Throwable error = null;
PrintStream originalErr = System.err;
PrintStream originalOut = System.out;
InputStream originalIn = System.in;
SecurityManager originalSM = System.getSecurityManager();
setJavaClassPath();
executed = true;
processAntHome(false);
try {
if (argList != null && (argList.remove("-projecthelp") || argList.remove("-p"))) {
projectHelp = true;
}
getCurrentProject().init();
if (argList != null) {
executed = preprocessCommandLine(argList);
if (!executed) {
return;
}
}
boolean exceptionState = processProperties(argList);
addBuildListeners(getCurrentProject(), true);
addInputHandler(getCurrentProject());
remapSystemIn();
System.setOut(new PrintStream(new DemuxOutputStream(getCurrentProject(), false)));
System.setErr(new PrintStream(new DemuxOutputStream(getCurrentProject(), true)));
if (!projectHelp) {
fireBuildStarted(getCurrentProject());
}
if (fEarlyErrorMessage != null) {
logMessage(getCurrentProject(), fEarlyErrorMessage, Project.MSG_ERR);
if (exceptionState) {
throw new BuildException(fEarlyErrorMessage);
}
}
setProperties(getCurrentProject(), true);
if (argList != null && !argList.isEmpty()) {
try {
executed = processCommandLine(argList);
}
catch (BuildException e) {
executed = false;
throw e;
}
}
if (!executed) {
return;
}
if (allowInput && (inputHandlerClassname != null && inputHandlerClassname.length() > 0)) {
if (isVersionCompatible("1.6")) {
System.getProperties().remove("eclipse.ant.noInput");
}
} else {
System.setProperty("eclipse.ant.noInput", "true");
if (isVersionCompatible("1.5") && (inputHandlerClassname == null || inputHandlerClassname.length() == 0)) {
InputHandlerSetter setter = new InputHandlerSetter();
setter.setInputHandler(getCurrentProject(), "org.eclipse.ant.internal.core.ant.FailInputHandler");
}
}
if (!projectHelp) {
logMessage(currentProject, MessageFormat.format(InternalAntMessages.InternalAntRunner_Build_file, new Object[] {
getBuildFileLocation() }), Project.MSG_INFO);
setTasks(getCurrentProject());
setTypes(getCurrentProject());
if (isVersionCompatible("1.6")) {
getCurrentProject().setKeepGoingMode(keepGoing);
}
parseBuildFile(getCurrentProject());
}
createMonitorBuildListener(getCurrentProject());
if (projectHelp) {
if (isVersionCompatible("1.7")) {
new EclipseMainHelper().runProjectHelp(getBuildFileLocation(), getCurrentProject());
return;
}
logMessage(currentProject, InternalAntMessages.InternalAntRunner_ant_1_7_needed_for_help_info, Project.MSG_ERR);
executed = false;
return;
}
if (extraArguments != null) {
printArguments(getCurrentProject());
}
System.setSecurityManager(new AntSecurityManager(originalSM, Thread.currentThread()));
if (targets == null) {
targets = new Vector<>(1);
}
String dtarget = currentProject.getDefaultTarget();
if (targets.isEmpty() && dtarget != null) {
targets.add(dtarget);
}
if (!isVersionCompatible("1.6.3")) {
getCurrentProject().addReference(IAntCoreConstants.TARGET_VECTOR_NAME, targets);
}
getCurrentProject().executeTargets(targets);
}
catch (OperationCanceledException e) {
executed = false;
logMessage(currentProject, e.getMessage(), Project.MSG_INFO);
throw e;
}
catch (AntSecurityException e) {
}
catch (RuntimeException e) {
error = e;
throw e;
}
catch (Error e) {
error = e;
throw e;
}
finally {
System.setErr(originalErr);
System.setOut(originalOut);
System.setIn(originalIn);
if (System.getSecurityManager() instanceof AntSecurityManager) {
System.setSecurityManager(originalSM);
}
if (!projectHelp) {
if (AntCorePlugin.getPlugin().getBundle().getState() != Bundle.ACTIVE) {
return;
}
fireBuildFinished(getCurrentProject(), error);
}
if (err != originalErr) {
err.close();
}
if (out != originalOut) {
out.close();
}
processAntHome(true);
if (!allowInput) {
System.getProperties().remove("eclipse.ant.noInput");
}
}
}
protected void remapSystemIn() {
if (!isVersionCompatible("1.6")) {
return;
}
DemuxInputStreamSetter setter = new DemuxInputStreamSetter();
setter.remapSystemIn(currentProject);
}
private void processAntHome(boolean finished) {
AntCorePreferences prefs = AntCorePlugin.getPlugin().getPreferences();
String antHome = prefs.getAntHome();
if (buildAntHome != null && !finished) {
antHome = buildAntHome;
}
if (antHome == null || antHome.length() == 0) {
System.getProperties().remove("ant.home");
System.getProperties().remove("ant.library.dir");
} else {
System.setProperty("ant.home", antHome);
File antLibDir = new File(antHome, "lib");
System.setProperty("ant.library.dir", antLibDir.getAbsolutePath());
}
}
public void setAntHome(String antHome) {
this.buildAntHome = antHome;
}
protected BuildLogger createLogger() {
if (loggerClassname == null) {
buildLogger = new DefaultLogger();
} else if (!IAntCoreConstants.EMPTY_STRING.equals(loggerClassname)) {
try {
buildLogger = (BuildLogger) (Class.forName(loggerClassname).newInstance());
}
catch (ClassCastException e) {
String message = MessageFormat.format(InternalAntMessages.InternalAntRunner_not_an_instance_of_apache_ant_BuildLogger, new Object[] {
loggerClassname });
logMessage(null, message, Project.MSG_ERR);
throw new BuildException(message, e);
}
catch (Exception e) {
String message = MessageFormat.format(InternalAntMessages.InternalAntRunner_Unable_to_instantiate_logger, new Object[] {
loggerClassname });
logMessage(null, message, Project.MSG_ERR);
throw new BuildException(message, e);
}
}
if (buildLogger != null) {
buildLogger.setMessageOutputLevel(messageOutputLevel);
buildLogger.setOutputPrintStream(out);
buildLogger.setErrorPrintStream(err);
buildLogger.setEmacsMode(emacsMode);
if (buildLogger instanceof AbstractEclipseBuildLogger) {
((AbstractEclipseBuildLogger) buildLogger).configure(userProperties);
}
}
return buildLogger;
}
protected void fireBuildStarted(Project project) {
if (!isVersionCompatible("1.5")) {
BuildEvent event = new BuildEvent(project);
for (BuildListener listener : project.getBuildListeners()) {
listener.buildStarted(event);
}
} else {
project.fireBuildStarted();
}
}
protected void fireBuildFinished(Project project, Throwable error) {
if (usingXmlLogger()) {
String fileName = project.getProperty("XmlLogger.file");
if (fileName == null) {
fileName = "log.xml";
}
String realPath = new Path(getBuildFileLocation()).toFile().getAbsolutePath();
IPath path = new Path(realPath);
path = path.removeLastSegments(1);
path = path.addTrailingSeparator();
path = path.append(fileName);
project.setProperty("XmlLogger.file", path.toOSString());
}
if (error == null && executed) {
logMessage(project, InternalAntMessages.InternalAntRunner_BUILD_SUCCESSFUL_1, messageOutputLevel);
}
if (!isVersionCompatible("1.5")) {
BuildEvent event = new BuildEvent(project);
event.setException(error);
for (BuildListener listener : project.getBuildListeners()) {
listener.buildFinished(event);
}
} else {
project.fireBuildFinished(error);
}
}
private boolean usingXmlLogger() {
if (buildLogger instanceof XmlLogger) {
return true;
}
if (buildListeners != null) {
for (BuildListener listener : currentProject.getBuildListeners()) {
if (listener instanceof XmlLogger) {
return true;
}
}
}
return false;
}
protected void logMessage(Project project, String message, int priority) {
if (project != null) {
project.log(message, priority);
} else {
if (buildListeners != null) {
Project p = new Project();
addBuildListeners(p, false);
p.log(message, priority);
} else {
IStatus s = new Status(IStatus.ERROR, AntCorePlugin.PI_ANTCORE, AntCorePlugin.INTERNAL_ERROR, message, null);
AntCorePlugin.getPlugin().getLog().log(s);
}
}
}
public void setBuildFileLocation(String buildFileLocation) {
this.buildFileLocation = buildFileLocation;
if (currentProject != null) {
currentProject.setUserProperty("ant.file", buildFileLocation);
}
}
public void setInputHandler(String inputHandlerClassname) {
this.inputHandlerClassname = inputHandlerClassname;
}
protected String getInputHandler() {
return this.inputHandlerClassname;
}
protected String getBuildLogger() {
return this.loggerClassname;
}
protected String getBuildFileLocation() {
if (buildFileLocation == null) {
buildFileLocation = new File("build.xml").getAbsolutePath();
}
return buildFileLocation;
}
public void setMessageOutputLevel(int level) {
messageOutputLevel = level;
if (buildLogger != null) {
buildLogger.setMessageOutputLevel(level);
}
}
public void setArguments(String[] args) {
extraArguments = args;
}
public void setExecutionTargets(String[] executionTargets) {
targets = new Vector<>(executionTargets.length);
for (int i = 0; i < executionTargets.length; i++) {
targets.add(executionTargets[i]);
}
}
protected String getAntVersionNumber() throws BuildException {
if (antVersionNumber == null) {
try (InputStream in = Main.class.getResourceAsStream("/org/apache/tools/ant/version.txt")) {
Properties props = new Properties();
props.load(in);
String versionNumber = props.getProperty("VERSION");
antVersionNumber = versionNumber;
}
catch (IOException ioe) {
throw new BuildException(MessageFormat.format(InternalAntMessages.InternalAntRunner_Could_not_load_the_version_information, new Object[] {
ioe.getMessage() }), ioe);
}
catch (NullPointerException npe) {
throw new BuildException(MessageFormat.format(InternalAntMessages.InternalAntRunner_Could_not_load_the_version_information, new Object[] {
npe.getMessage() }), npe);
}
}
return antVersionNumber;
}
protected boolean isVersionCompatible(String comparison) {
String version = getAntVersionNumber();
Version osgiVersion = new Version(version);
Version osgiComparison = new Version(comparison);
return osgiVersion.compareTo(osgiComparison) >= 0;
}
protected boolean preprocessCommandLine(List<String> commands) {
String arg = AntCoreUtil.getArgument(commands, "-listener");
while (arg != null) {
if (arg.length() == 0) {
throw new BuildException(InternalAntMessages.InternalAntRunner_specify_a_classname_using_the_listener_argument);
}
if (buildListeners == null) {
buildListeners = new ArrayList<>(1);
}
buildListeners.add(arg);
arg = AntCoreUtil.getArgument(commands, "-listener");
}
arg = AntCoreUtil.getArgument(commands, "-logger");
if (arg != null) {
if (arg.length() == 0) {
throw new BuildException(InternalAntMessages.InternalAntRunner_specify_a_classname_using_the_logger_argument);
}
loggerClassname = arg;
}
arg = AntCoreUtil.getArgument(commands, "-logger");
if (arg != null) {
throw new BuildException(InternalAntMessages.InternalAntRunner_Only_one_logger_class_may_be_specified);
}
arg = AntCoreUtil.getArgument(commands, "-inputhandler");
if (arg != null) {
if (!isVersionCompatible("1.5")) {
throw new BuildException(InternalAntMessages.InternalAntRunner_Specifying_an_InputHandler_is_an_Ant_1_5_feature);
}
if (arg.length() == 0) {
throw new BuildException(InternalAntMessages.InternalAntRunner_specify_a_classname_the_inputhandler_argument);
}
inputHandlerClassname = arg;
}
arg = AntCoreUtil.getArgument(commands, "-inputhandler");
if (arg != null) {
throw new BuildException(InternalAntMessages.InternalAntRunner_Only_one_input_handler_class_may_be_specified);
}
return true;
}
private boolean processCommandLine(List<String> commands) {
if (commands.remove("-help") || commands.remove("-h")) {
if (isVersionCompatible("1.7")) {
new EclipseMainHelper().runUsage(getBuildFileLocation(), currentProject);
} else {
logMessage(currentProject, InternalAntMessages.InternalAntRunner_ant_1_7_needed_for_help_message, Project.MSG_WARN);
}
return false;
}
if (commands.remove("-version")) {
printVersion();
return false;
}
if (commands.remove("-verbose") || commands.remove("-v")) {
printVersion();
setMessageOutputLevel(Project.MSG_VERBOSE);
}
if (commands.remove("-debug") || commands.remove("-d")) {
printVersion();
setMessageOutputLevel(Project.MSG_DEBUG);
}
if (commands.remove("-quiet") || commands.remove("-q")) {
setMessageOutputLevel(Project.MSG_WARN);
}
if (commands.remove("-emacs") || commands.remove("-e")) {
emacsMode = true;
if (buildLogger != null) {
buildLogger.setEmacsMode(true);
}
}
if (commands.remove("-diagnostics")) {
if (!isVersionCompatible("1.5")) {
throw new BuildException(InternalAntMessages.InternalAntRunner_The_diagnositics_options_is_an_Ant_1_5_feature);
}
try {
Diagnostics.doReport(System.out);
}
catch (NullPointerException e) {
logMessage(currentProject, InternalAntMessages.InternalAntRunner_anthome_must_be_set_to_use_ant_diagnostics, Project.MSG_ERR);
}
return false;
}
String arg = AntCoreUtil.getArgument(commands, "-logfile");
if (arg == null) {
arg = AntCoreUtil.getArgument(commands, "-l");
}
if (arg != null) {
if (arg.length() == 0) {
String message = InternalAntMessages.InternalAntRunner_specify_a_log_file_using_the_log_argument;
logMessage(currentProject, message, Project.MSG_ERR);
throw new BuildException(message);
}
try {
createLogFile(arg);
}
catch (IOException e) {
logMessage(currentProject, MessageFormat.format(InternalAntMessages.InternalAntRunner_Could_not_write_to_log_file, new Object[] {
arg }), Project.MSG_ERR);
return false;
}
}
arg = AntCoreUtil.getArgument(commands, "-buildfile");
if (arg == null) {
arg = AntCoreUtil.getArgument(commands, "-file");
if (arg == null) {
arg = AntCoreUtil.getArgument(commands, "-f");
}
}
if (arg != null) {
if (arg.length() == 0) {
String message = InternalAntMessages.InternalAntRunner_specify_a_buildfile_using_the_buildfile_argument;
logMessage(currentProject, message, Project.MSG_ERR);
throw new BuildException(message);
}
setBuildFileLocation(arg);
}
if (isVersionCompatible("1.6")) {
if (commands.remove("-k") || commands.remove("-keep-going")) {
keepGoing = true;
}
if (commands.remove("-noinput")) {
allowInput = false;
}
arg = AntCoreUtil.getArgument(commands, "-lib");
if (arg != null) {
logMessage(currentProject, InternalAntMessages.InternalAntRunner_157, Project.MSG_ERR);
return false;
}
}
arg = AntCoreUtil.getArgument(commands, "-find");
if (arg == null) {
arg = AntCoreUtil.getArgument(commands, "-s");
}
if (arg != null) {
logMessage(currentProject, InternalAntMessages.InternalAntRunner_find_not_supported, Project.MSG_ERR);
return false;
}
if (!commands.isEmpty()) {
processUnrecognizedCommands(commands);
}
if (!commands.isEmpty()) {
processUnrecognizedTargets(commands);
}
if (!commands.isEmpty()) {
processTargets(commands);
}
if (unknownTargetsFound && (targets == null || targets.isEmpty())) {
logMessage(currentProject, InternalAntMessages.InternalAntRunner_no_known_target, Project.MSG_ERR);
return false;
}
return true;
}
private void processUnrecognizedTargets(List<String> commands) {
List<String> names = getTargetNames();
ListIterator<String> iterator = commands.listIterator();
while (iterator.hasNext()) {
String target = iterator.next();
if (!names.contains(target)) {
iterator.remove();
String message = MessageFormat.format(InternalAntMessages.InternalAntRunner_unknown_target, new Object[] { target });
logMessage(currentProject, message, Project.MSG_WARN);
unknownTargetsFound = true;
}
}
}
protected void processUnrecognizedCommands(List<String> commands) {
int p = -1;
for (int i = commands.size() - 1; i >= 0; i--) {
if (commands.get(i).startsWith("-")) {
p = i;
break;
}
}
if (p < 0) {
return;
}
String s = IAntCoreConstants.EMPTY_STRING;
for (int i = 0; i <= p; i++) {
s += " " + (commands.get(0));
commands.remove(0);
}
String message = MessageFormat.format(InternalAntMessages.InternalAntRunner_Unknown_argument, new Object[] { s.substring(1) });
logMessage(currentProject, message, Project.MSG_WARN);
}
protected void processTargets(List<String> commands) {
if (targets == null) {
targets = new Vector<>(commands.size());
}
for (Iterator<String> iter = commands.iterator(); iter.hasNext();) {
targets.add(iter.next());
}
}
protected void createLogFile(String fileName) throws FileNotFoundException, IOException {
File logFile = AntCoreUtil.getFileRelativeToBaseDir(fileName, currentProject.getUserProperty("basedir"), getBuildFileLocation());
out = new PrintStream(new FileOutputStream(logFile));
err = out;
logMessage(currentProject, MessageFormat.format(InternalAntMessages.InternalAntRunner_Using_file_as_build_log, new Object[] {
logFile.getCanonicalPath() }), Project.MSG_INFO);
if (buildLogger != null) {
buildLogger.setErrorPrintStream(err);
buildLogger.setOutputPrintStream(out);
}
}
private boolean processProperties(List<String> commands) {
boolean exceptionToBeThrown = false;
String arg = AntCoreUtil.getArgument(commands, "-propertyfile");
while (arg != null) {
if (!isVersionCompatible("1.5")) {
fEarlyErrorMessage = InternalAntMessages.InternalAntRunner_Specifying_property_files_is_a_Ant_1_5_feature;
break;
}
if (arg.length() == 0) {
fEarlyErrorMessage = InternalAntMessages.InternalAntRunner_specify_a_property_filename_when_using_propertyfile_argument;
exceptionToBeThrown = true;
break;
}
propertyFiles.add(arg);
arg = AntCoreUtil.getArgument(commands, "-propertyfile");
}
String[] globalPropertyFiles = AntCorePlugin.getPlugin().getPreferences().getCustomPropertyFiles();
if (globalPropertyFiles.length > 0) {
if (!isVersionCompatible("1.5")) {
fEarlyErrorMessage = InternalAntMessages.InternalAntRunner_Specifying_property_files_is_a_Ant_1_5_feature;
} else {
if (propertyFiles == null) {
propertyFiles = new ArrayList<>(globalPropertyFiles.length);
}
propertyFiles.addAll(Arrays.asList(globalPropertyFiles));
}
}
if (propertyFiles != null && !propertyFiles.isEmpty()) {
loadPropertyFiles();
}
if (commands != null) {
processMinusDProperties(commands);
}
return exceptionToBeThrown;
}
protected void processMinusDProperties(List<String> commands) {
if (!commands.isEmpty() && userProperties == null) {
userProperties = new HashMap<>();
}
AntCoreUtil.processMinusDProperties(commands, userProperties);
}
protected void printVersion() {
logMessage(currentProject, Main.getAntVersion(), Project.MSG_INFO);
}
public void setProgressMonitor(IProgressMonitor monitor) {
this.monitor = monitor;
}
protected Project getCurrentProject() {
return currentProject;
}
protected void setCurrentProject(Project currentProject) {
this.currentProject = currentProject;
}
public String getBuildExceptionErrorMessage(Throwable t) {
if (t instanceof BuildException) {
return t.toString();
}
return null;
}
protected void loadPropertyFiles() {
if (userProperties == null) {
userProperties = new HashMap<>();
}
try {
List<Properties> allProperties = AntCoreUtil.loadPropertyFiles(propertyFiles, currentProject.getUserProperty("basedir"), getBuildFileLocation());
Iterator<Properties> iter = allProperties.iterator();
while (iter.hasNext()) {
Properties props = iter.next();
Enumeration<?> propertyNames = props.propertyNames();
while (propertyNames.hasMoreElements()) {
String name = (String) propertyNames.nextElement();
if (userProperties.get(name) == null) {
userProperties.put(name, props.getProperty(name));
}
}
}
}
catch (IOException e) {
fEarlyErrorMessage = MessageFormat.format(InternalAntMessages.InternalAntRunner_could_not_load_property_file, new Object[] {
e.getMessage() });
}
}
protected void addInputHandler(Project project) {
if (!isVersionCompatible("1.5") || (inputHandlerClassname != null && inputHandlerClassname.length() == 0)) {
return;
}
InputHandlerSetter setter = new InputHandlerSetter();
setter.setInputHandler(project, inputHandlerClassname);
}
private void setJavaClassPath() {
URL[] antClasspath = null;
AntCorePreferences prefs = AntCorePlugin.getPlugin().getPreferences();
if (customClasspath == null) {
antClasspath = prefs.getURLs();
} else {
URL[] extraClasspath = prefs.getExtraClasspathURLs();
antClasspath = new URL[customClasspath.length + extraClasspath.length];
System.arraycopy(customClasspath, 0, antClasspath, 0, customClasspath.length);
System.arraycopy(extraClasspath, 0, antClasspath, customClasspath.length, extraClasspath.length);
}
StringBuilder buff = new StringBuilder();
File file = null;
for (int i = 0; i < antClasspath.length; i++) {
try {
file = new File(FileLocator.toFileURL(antClasspath[i]).getPath());
}
catch (IOException e) {
continue;
}
buff.append(file.getAbsolutePath());
buff.append("; ");
}
org.apache.tools.ant.types.Path systemClasspath = new org.apache.tools.ant.types.Path(null, buff.substring(0, buff.length() - 2));
org.apache.tools.ant.types.Path.systemClasspath = systemClasspath;
}
public void setCustomClasspath(URL[] classpath) {
customClasspath = classpath;
}
}