1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-08-11 10:15:39 +02:00

bug 261976: CommandLauncher to report about $PATH problems and related

clean-up
This commit is contained in:
Andrew Gvozdev 2012-03-16 18:23:55 -04:00
parent b36fe67745
commit 626c0cdaf3
8 changed files with 394 additions and 479 deletions

View file

@ -256,24 +256,12 @@ public class MakeBuilder extends ACBuilder {
getProject().setSessionProperty(qName, !monitor.isCanceled() && !isClean ? new Integer(streamMon.getWorkDone()) : null); getProject().setSessionProperty(qName, !monitor.isCanceled() && !isClean ? new Integer(streamMon.getWorkDone()) : null);
if (errMsg != null) { if (errMsg != null) {
StringBuffer buf = new StringBuffer(buildCommand.toString() + " "); //$NON-NLS-1$ consoleErr.write((errMsg + '\n').getBytes());
for (String buildArgument : buildArguments) {
buf.append(buildArgument);
buf.append(' ');
}
String errorDesc = MakeMessages.getFormattedString("MakeBuilder.buildError", buf.toString()); //$NON-NLS-1$
buf = new StringBuffer(errorDesc);
buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$
buf.append("(").append(errMsg).append(")"); //$NON-NLS-1$ //$NON-NLS-2$
cos.write(buf.toString().getBytes());
cos.flush();
} }
stdout.close(); stdout.close();
stderr.close(); stderr.close();
monitor.subTask(MakeMessages.getString("MakeBuilder.Creating_Markers")); //$NON-NLS-1$
consoleOut.close(); consoleOut.close();
consoleErr.close(); consoleErr.close();
cos.close(); cos.close();

View file

@ -13,7 +13,6 @@
AbstractGCCBOPConsoleParser_EnteringDirectory=Entering directory AbstractGCCBOPConsoleParser_EnteringDirectory=Entering directory
AbstractGCCBOPConsoleParser_LeavingDirectory=Leaving directory AbstractGCCBOPConsoleParser_LeavingDirectory=Leaving directory
MakeBuilder.buildError=Error launching builder ({0})
MakeBuilder.Invoking_Make_Builder=Invoking Make Builder... MakeBuilder.Invoking_Make_Builder=Invoking Make Builder...
MakeBuilder.Invoking_Command=Invoking Command: MakeBuilder.Invoking_Command=Invoking Command:
MakeBuilder.Updating_project=Updating project... MakeBuilder.Updating_project=Updating project...
@ -41,9 +40,7 @@ ExternalScannerInfoProvider.Reading_Specs=Reading specs ...
ExternalScannerInfoProvider.Invoking_Command=Invoking Command: ExternalScannerInfoProvider.Invoking_Command=Invoking Command:
ExternalScannerInfoProvider.Parsing_Output=Parsing output ... ExternalScannerInfoProvider.Parsing_Output=Parsing output ...
ExternalScannerInfoProvider.Creating_Markers=Generating markers ... ExternalScannerInfoProvider.Creating_Markers=Generating markers ...
# Error_Prefix affects generation of markers in the Problems view ExternalScannerInfoProvider.Provider_Error=Warning: Error launching external scanner info generator ({0})
ExternalScannerInfoProvider.Error_Prefix=Warning:
ExternalScannerInfoProvider.Provider_Error=Error launching external scanner info generator ({0})
ExternalScannerInfoProvider.Working_Directory=Working directory: {0} ExternalScannerInfoProvider.Working_Directory=Working directory: {0}
ExternalScannerInfoProvider.Program_Not_In_Path=Program ''{0}'' is not found in $PATH ExternalScannerInfoProvider.Program_Not_In_Path=Program ''{0}'' is not found in $PATH

View file

@ -37,7 +37,6 @@ import org.eclipse.cdt.make.internal.core.StreamMonitor;
import org.eclipse.cdt.make.internal.core.scannerconfig.ScannerConfigUtil; import org.eclipse.cdt.make.internal.core.scannerconfig.ScannerConfigUtil;
import org.eclipse.cdt.make.internal.core.scannerconfig.ScannerInfoConsoleParserFactory; import org.eclipse.cdt.make.internal.core.scannerconfig.ScannerInfoConsoleParserFactory;
import org.eclipse.cdt.utils.EFSExtensionManager; import org.eclipse.cdt.utils.EFSExtensionManager;
import org.eclipse.cdt.utils.PathUtil;
import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IPath;
@ -55,55 +54,53 @@ import org.osgi.service.prefs.BackingStoreException;
* @author vhirsl * @author vhirsl
*/ */
public class DefaultRunSIProvider implements IExternalScannerInfoProvider { public class DefaultRunSIProvider implements IExternalScannerInfoProvider {
private static final String EXTERNAL_SI_PROVIDER_ERROR = "ExternalScannerInfoProvider.Provider_Error"; //$NON-NLS-1$
private static final String GMAKE_ERROR_PARSER_ID = "org.eclipse.cdt.core.GmakeErrorParser"; //$NON-NLS-1$ private static final String GMAKE_ERROR_PARSER_ID = "org.eclipse.cdt.core.GmakeErrorParser"; //$NON-NLS-1$
private static final String PREF_CONSOLE_ENABLED = "org.eclipse.cdt.make.core.scanner.discovery.console.enabled"; //$NON-NLS-1$ private static final String PREF_CONSOLE_ENABLED = "org.eclipse.cdt.make.core.scanner.discovery.console.enabled"; //$NON-NLS-1$
private static final String NEWLINE = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ private static final String NEWLINE = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
private static final String PATH_ENV = "PATH"; //$NON-NLS-1$
protected IResource resource; protected IResource resource;
protected String providerId; protected String providerId;
protected IScannerConfigBuilderInfo2 buildInfo; protected IScannerConfigBuilderInfo2 buildInfo;
protected IScannerInfoCollector collector; protected IScannerInfoCollector collector;
// To be initialized by a subclass // To be initialized by a subclass
protected IPath fWorkingDirectory; protected IPath fWorkingDirectory;
protected IPath fCompileCommand; protected IPath fCompileCommand;
protected String[] fCompileArguments; protected String[] fCompileArguments;
private SCMarkerGenerator markerGenerator = new SCMarkerGenerator(); private SCMarkerGenerator markerGenerator = new SCMarkerGenerator();
@Override @Override
public boolean invokeProvider(IProgressMonitor monitor, IResource resource, public boolean invokeProvider(IProgressMonitor monitor, IResource resource,
String providerId, IScannerConfigBuilderInfo2 buildInfo, String providerId, IScannerConfigBuilderInfo2 buildInfo,
IScannerInfoCollector collector) { IScannerInfoCollector collector) {
return invokeProvider(monitor, resource, new InfoContext(resource.getProject()), providerId, buildInfo, collector, null); return invokeProvider(monitor, resource, new InfoContext(resource.getProject()), providerId, buildInfo, collector, null);
} }
@Override @Override
public boolean invokeProvider(IProgressMonitor monitor, public boolean invokeProvider(IProgressMonitor monitor,
IResource resource, IResource resource,
InfoContext context, InfoContext context,
String providerId, String providerId,
IScannerConfigBuilderInfo2 buildInfo, IScannerConfigBuilderInfo2 buildInfo,
IScannerInfoCollector collector, IScannerInfoCollector collector,
Properties env) { Properties env) {
// initialize fields // initialize fields
this.resource = resource; this.resource = resource;
this.providerId = providerId; this.providerId = providerId;
this.buildInfo = buildInfo; this.buildInfo = buildInfo;
this.collector = collector; this.collector = collector;
IProject currentProject = resource.getProject(); IProject currentProject = resource.getProject();
// call a subclass to initialize protected fields // call a subclass to initialize protected fields
if (!initialize()) { if (!initialize()) {
return false; return false;
} }
if (monitor == null) { if (monitor == null) {
monitor = new NullProgressMonitor(); monitor = new NullProgressMonitor();
} }
monitor.beginTask(MakeMessages.getString("ExternalScannerInfoProvider.Reading_Specs"), 100); //$NON-NLS-1$ monitor.beginTask(MakeMessages.getString("ExternalScannerInfoProvider.Reading_Specs"), 100); //$NON-NLS-1$
try { try {
ILanguage language = context.getLanguage(); ILanguage language = context.getLanguage();
IConsole console; IConsole console;
if (language!=null && isConsoleEnabled()) { if (language!=null && isConsoleEnabled()) {
@ -114,23 +111,24 @@ public class DefaultRunSIProvider implements IExternalScannerInfoProvider {
// that looks in extension points registry and won't find the id // that looks in extension points registry and won't find the id
console = CCorePlugin.getDefault().getConsole(MakeCorePlugin.PLUGIN_ID + ".console.hidden"); //$NON-NLS-1$ console = CCorePlugin.getDefault().getConsole(MakeCorePlugin.PLUGIN_ID + ".console.hidden"); //$NON-NLS-1$
} }
console.start(currentProject); console.start(currentProject);
OutputStream cos = console.getOutputStream(); OutputStream cos = console.getOutputStream();
// Before launching give visual cues via the monitor // Before launching give visual cues via the monitor
monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Reading_Specs")); //$NON-NLS-1$ monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Reading_Specs")); //$NON-NLS-1$
String errMsg = null; String errMsg = null;
ICommandLauncher launcher = new CommandLauncher(); ICommandLauncher launcher = new CommandLauncher();
launcher.setProject(currentProject); launcher.setProject(currentProject);
// Print the command for visual interaction. // Print the command for visual interaction.
launcher.showCommand(true); launcher.showCommand(true);
String[] comandLineOptions = getCommandLineOptions(); String[] comandLineOptions = getCommandLineOptions();
String params = coligate(comandLineOptions); IPath program = getCommandToLaunch();
String params = coligate(comandLineOptions);
monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Invoking_Command") //$NON-NLS-1$ monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Invoking_Command") //$NON-NLS-1$
+ getCommandToLaunch() + params); + program + params);
ErrorParserManager epm = new ErrorParserManager(currentProject, markerGenerator, new String[] {GMAKE_ERROR_PARSER_ID}); ErrorParserManager epm = new ErrorParserManager(currentProject, markerGenerator, new String[] {GMAKE_ERROR_PARSER_ID});
epm.setOutputStream(cos); epm.setOutputStream(cos);
@ -140,90 +138,66 @@ public class DefaultRunSIProvider implements IExternalScannerInfoProvider {
ConsoleOutputSniffer sniffer = ScannerInfoConsoleParserFactory.getESIProviderOutputSniffer( ConsoleOutputSniffer sniffer = ScannerInfoConsoleParserFactory.getESIProviderOutputSniffer(
stdout, stderr, currentProject, context, providerId, buildInfo, collector, markerGenerator); stdout, stderr, currentProject, context, providerId, buildInfo, collector, markerGenerator);
OutputStream consoleOut = (sniffer == null ? cos : sniffer.getOutputStream()); OutputStream consoleOut = (sniffer == null ? cos : sniffer.getOutputStream());
OutputStream consoleErr = (sniffer == null ? cos : sniffer.getErrorStream()); OutputStream consoleErr = (sniffer == null ? cos : sniffer.getErrorStream());
Process p = launcher.execute(getCommandToLaunch(), comandLineOptions, setEnvironment(launcher, env), fWorkingDirectory, monitor); Process p = launcher.execute(program, comandLineOptions, setEnvironment(launcher, env), fWorkingDirectory, monitor);
if (p != null) { if (p != null) {
try { try {
// Close the input of the Process explicitely. // Close the input of the Process explicitly.
// We will never write to it. // We will never write to it.
p.getOutputStream().close(); p.getOutputStream().close();
} catch (IOException e) { } catch (IOException e) {
}
if (launcher.waitAndRead(consoleOut, consoleErr, new SubProgressMonitor(monitor, 0)) != ICommandLauncher.OK) {
errMsg = launcher.getErrorMessage();
}
monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Parsing_Output")); //$NON-NLS-1$
}
else {
errMsg = launcher.getErrorMessage();
}
if (errMsg != null) {
String errorPrefix = MakeMessages.getString("ExternalScannerInfoProvider.Error_Prefix"); //$NON-NLS-1$
String program = fCompileCommand.toString();
String msg = MakeMessages.getFormattedString(EXTERNAL_SI_PROVIDER_ERROR, program+params);
printLine(consoleErr, errorPrefix + msg + NEWLINE);
// Launching failed, trying to figure out possible cause
Properties envMap = getEnvMap(launcher, env);
String envPath = envMap.getProperty(PATH_ENV);
if (envPath == null) {
envPath = System.getenv(PATH_ENV);
} }
if (!fCompileCommand.isAbsolute() && PathUtil.findProgramLocation(program, envPath) == null) { if (launcher.waitAndRead(consoleOut, consoleErr, new SubProgressMonitor(monitor, 0)) != ICommandLauncher.OK) {
printLine(consoleErr, errMsg); errMsg = launcher.getErrorMessage();
msg = MakeMessages.getFormattedString("ExternalScannerInfoProvider.Working_Directory", fWorkingDirectory); //$NON-NLS-1$
msg = MakeMessages.getFormattedString("ExternalScannerInfoProvider.Program_Not_In_Path", program); //$NON-NLS-1$
printLine(consoleErr, errorPrefix + msg + NEWLINE);
printLine(consoleErr, PATH_ENV + "=[" + envPath + "]" + NEWLINE); //$NON-NLS-1$ //$NON-NLS-2$
} else {
printLine(consoleErr, errorPrefix + errMsg);
msg = MakeMessages.getFormattedString("ExternalScannerInfoProvider.Working_Directory", fWorkingDirectory); //$NON-NLS-1$
printLine(consoleErr, PATH_ENV + "=[" + envPath + "]" + NEWLINE); //$NON-NLS-1$ //$NON-NLS-2$
} }
monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Parsing_Output")); //$NON-NLS-1$
monitor.subTask(MakeMessages.getString("ExternalScannerInfoProvider.Creating_Markers")); //$NON-NLS-1$ } else {
errMsg = launcher.getErrorMessage();
} }
consoleOut.close(); if (errMsg != null) {
consoleErr.close(); printLine(consoleErr, errMsg);
cos.close(); printLine(consoleErr, MakeMessages.getFormattedString("ExternalScannerInfoProvider.Provider_Error", program + params) + NEWLINE); //$NON-NLS-1$
} }
catch (Exception e) {
MakeCorePlugin.log(e);
}
finally {
monitor.done();
}
return true;
}
protected IPath getCommandToLaunch() { consoleOut.close();
return fCompileCommand; consoleErr.close();
} cos.close();
}
catch (Exception e) {
MakeCorePlugin.log(e);
}
finally {
monitor.done();
}
return true;
}
protected String[] getCommandLineOptions() { protected IPath getCommandToLaunch() {
// add additional arguments return fCompileCommand;
// subclass can change default behavior }
return prepareArguments(
buildInfo.isUseDefaultProviderCommand(providerId));
}
private void printLine(OutputStream stream, String msg) throws IOException { protected String[] getCommandLineOptions() {
stream.write((msg + NEWLINE).getBytes()); // add additional arguments
stream.flush(); // subclass can change default behavior
} return prepareArguments(
buildInfo.isUseDefaultProviderCommand(providerId));
}
/** private void printLine(OutputStream stream, String msg) throws IOException {
* Initialization of protected fields. stream.write((msg + NEWLINE).getBytes());
* Subclasses are most likely to override default implementation. stream.flush();
*/ }
protected boolean initialize() {
/**
* Initialization of protected fields.
* Subclasses are most likely to override default implementation.
*/
protected boolean initialize() {
IProject currProject = resource.getProject(); IProject currProject = resource.getProject();
//fWorkingDirectory = resource.getProject().getLocation(); //fWorkingDirectory = resource.getProject().getLocation();
URI workingDirURI = MakeBuilderUtil.getBuildDirectoryURI(currProject, MakeBuilder.BUILDER_ID); URI workingDirURI = MakeBuilderUtil.getBuildDirectoryURI(currProject, MakeBuilder.BUILDER_ID);
String pathString = EFSExtensionManager.getDefault().getPathFromURI(workingDirURI); String pathString = EFSExtensionManager.getDefault().getPathFromURI(workingDirURI);
if(pathString != null) { if(pathString != null) {
@ -235,34 +209,34 @@ public class DefaultRunSIProvider implements IExternalScannerInfoProvider {
throw new IllegalStateException(); throw new IllegalStateException();
} }
fCompileCommand = new Path(buildInfo.getProviderRunCommand(providerId)); fCompileCommand = new Path(buildInfo.getProviderRunCommand(providerId));
fCompileArguments = ScannerConfigUtil.tokenizeStringWithQuotes(buildInfo.getProviderRunArguments(providerId), "\"");//$NON-NLS-1$ fCompileArguments = ScannerConfigUtil.tokenizeStringWithQuotes(buildInfo.getProviderRunArguments(providerId), "\"");//$NON-NLS-1$
return (fCompileCommand != null); return (fCompileCommand != null);
} }
/** /**
* Add additional arguments. For example: tso - target specific options * Add additional arguments. For example: tso - target specific options
* Base class implementation returns compileArguments. * Base class implementation returns compileArguments.
* Subclasses are most likely to override default implementation. * Subclasses are most likely to override default implementation.
*/ */
protected String[] prepareArguments(boolean isDefaultCommand) { protected String[] prepareArguments(boolean isDefaultCommand) {
return fCompileArguments; return fCompileArguments;
} }
private String coligate(String[] array) { private String coligate(String[] array) {
StringBuffer sb = new StringBuffer(128); StringBuffer sb = new StringBuffer(128);
for (int i = 0; i < array.length; ++i) { for (int i = 0; i < array.length; ++i) {
sb.append(' '); sb.append(' ');
sb.append(array[i]); sb.append(array[i]);
} }
String ca = sb.toString(); String ca = sb.toString();
return ca; return ca;
} }
private Properties getEnvMap(ICommandLauncher launcher, Properties initialEnv) { private Properties getEnvMap(ICommandLauncher launcher, Properties initialEnv) {
// Set the environmennt, some scripts may need the CWD var to be set. // Set the environmennt, some scripts may need the CWD var to be set.
Properties props = initialEnv != null ? initialEnv : launcher.getEnvironment(); Properties props = initialEnv != null ? initialEnv : launcher.getEnvironment();
if (fWorkingDirectory != null) { if (fWorkingDirectory != null) {
props.put("CWD", fWorkingDirectory.toOSString()); //$NON-NLS-1$ props.put("CWD", fWorkingDirectory.toOSString()); //$NON-NLS-1$
props.put("PWD", fWorkingDirectory.toOSString()); //$NON-NLS-1$ props.put("PWD", fWorkingDirectory.toOSString()); //$NON-NLS-1$
@ -278,20 +252,20 @@ public class DefaultRunSIProvider implements IExternalScannerInfoProvider {
return props; return props;
} }
protected String[] setEnvironment(ICommandLauncher launcher, Properties initialEnv) { protected String[] setEnvironment(ICommandLauncher launcher, Properties initialEnv) {
Properties props = getEnvMap(launcher, initialEnv); Properties props = getEnvMap(launcher, initialEnv);
String[] env = null; String[] env = null;
ArrayList<String> envList = new ArrayList<String>(); ArrayList<String> envList = new ArrayList<String>();
Enumeration<?> names = props.propertyNames(); Enumeration<?> names = props.propertyNames();
if (names != null) { if (names != null) {
while (names.hasMoreElements()) { while (names.hasMoreElements()) {
String key = (String) names.nextElement(); String key = (String) names.nextElement();
envList.add(key + "=" + props.getProperty(key)); //$NON-NLS-1$ envList.add(key + "=" + props.getProperty(key)); //$NON-NLS-1$
} }
env = envList.toArray(new String[envList.size()]); env = envList.toArray(new String[envList.size()]);
} }
return env; return env;
} }
/** /**

View file

@ -47,7 +47,6 @@ import org.eclipse.cdt.managedbuilder.macros.IBuildMacroProvider;
import org.eclipse.cdt.newmake.internal.core.StreamMonitor; import org.eclipse.cdt.newmake.internal.core.StreamMonitor;
import org.eclipse.cdt.utils.CommandLineUtil; import org.eclipse.cdt.utils.CommandLineUtil;
import org.eclipse.cdt.utils.EFSExtensionManager; import org.eclipse.cdt.utils.EFSExtensionManager;
import org.eclipse.cdt.utils.PathUtil;
import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResource;
@ -140,7 +139,7 @@ public class ExternalBuildRunner extends AbstractBuildRunner {
if(pathFromURI == null) { if(pathFromURI == null) {
throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, ManagedMakeMessages.getString("ManagedMakeBuilder.message.error"), null)); //$NON-NLS-1$ throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, ManagedMakeMessages.getString("ManagedMakeBuilder.message.error"), null)); //$NON-NLS-1$
} }
IPath workingDirectory = new Path(pathFromURI); IPath workingDirectory = new Path(pathFromURI);
String[] targets = getTargets(kind, builder); String[] targets = getTargets(kind, builder);
@ -197,10 +196,10 @@ public class ExternalBuildRunner extends AbstractBuildRunner {
// Do not allow the cancel of the refresh, since the builder is external // Do not allow the cancel of the refresh, since the builder is external
// to Eclipse, files may have been created/modified and we will be out-of-sync. // to Eclipse, files may have been created/modified and we will be out-of-sync.
// The caveat is for huge projects, it may take sometimes at every build. // The caveat is for huge projects, it may take sometimes at every build.
// TODO should only refresh output folders // TODO should only refresh output folders
//project.refreshLocal(IResource.DEPTH_INFINITE, null); //project.refreshLocal(IResource.DEPTH_INFINITE, null);
// use the refresh scope manager to refresh // use the refresh scope manager to refresh
RefreshScopeManager refreshManager = RefreshScopeManager.getInstance(); RefreshScopeManager refreshManager = RefreshScopeManager.getInstance();
IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(project); IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(project);
@ -208,32 +207,15 @@ public class ExternalBuildRunner extends AbstractBuildRunner {
} catch (CoreException e) { } catch (CoreException e) {
} }
} else { } else {
buf = new StringBuffer(launcher.getCommandLine()).append(NEWLINE);
errMsg = launcher.getErrorMessage(); errMsg = launcher.getErrorMessage();
} }
project.setSessionProperty(qName, !monitor.isCanceled() && !isClean ? new Integer(streamMon.getWorkDone()) : null); project.setSessionProperty(qName, !monitor.isCanceled() && !isClean ? new Integer(streamMon.getWorkDone()) : null);
if (errMsg != null) { if (errMsg != null) {
// Launching failed, trying to figure out possible cause consoleErr.write(errMsg.getBytes());
String errorPrefix = ManagedMakeMessages.getResourceString("ManagedMakeBuilder.error.prefix"); //$NON-NLS-1$
String buildCommandStr = buildCommand.toString();
String envPath = envMap.get(PATH_ENV);
if (envPath==null) {
envPath = System.getenv(PATH_ENV);
}
if (PathUtil.findProgramLocation(buildCommandStr, envPath)==null) {
buf.append(errMsg).append(NEWLINE);
errMsg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.program.not.in.path", buildCommandStr); //$NON-NLS-1$
buf.append(errorPrefix).append(errMsg).append(NEWLINE);
buf.append(NEWLINE);
buf.append(PATH_ENV+"=["+envPath+"]").append(NEWLINE); //$NON-NLS-1$//$NON-NLS-2$
} else {
buf.append(errorPrefix).append(errMsg).append(NEWLINE);
}
consoleErr.write(buf.toString().getBytes());
consoleErr.flush(); consoleErr.flush();
} }
buf = new StringBuffer(NEWLINE); buf = new StringBuffer(NEWLINE);
buf.append(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.build.finished")).append(NEWLINE); //$NON-NLS-1$ buf.append(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.build.finished")).append(NEWLINE); //$NON-NLS-1$
consoleOut.write(buf.toString().getBytes()); consoleOut.write(buf.toString().getBytes());
@ -310,15 +292,15 @@ public class ExternalBuildRunner extends AbstractBuildRunner {
envMap.put(var.getName(), var.getValue()); envMap.put(var.getName(), var.getValue());
} }
} }
// Add variables from build info // Add variables from build info
Map<String, String> builderEnv = builder.getExpandedEnvironment(); Map<String, String> builderEnv = builder.getExpandedEnvironment();
if (builderEnv != null) if (builderEnv != null)
envMap.putAll(builderEnv); envMap.putAll(builderEnv);
return envMap; return envMap;
} }
protected static String[] getEnvStrings(Map<String, String> env) { protected static String[] getEnvStrings(Map<String, String> env) {
// Convert into env strings // Convert into env strings
List<String> strings= new ArrayList<String>(env.size()); List<String> strings= new ArrayList<String>(env.size());
@ -327,10 +309,10 @@ public class ExternalBuildRunner extends AbstractBuildRunner {
buffer.append('=').append(entry.getValue()); buffer.append('=').append(entry.getValue());
strings.add(buffer.toString()); strings.add(buffer.toString());
} }
return strings.toArray(new String[strings.size()]); return strings.toArray(new String[strings.size()]);
} }
private ConsoleOutputSniffer createBuildOutputSniffer(OutputStream outputStream, private ConsoleOutputSniffer createBuildOutputSniffer(OutputStream outputStream,
OutputStream errorStream, OutputStream errorStream,
IProject project, IProject project,

View file

@ -21,8 +21,6 @@ import java.util.Set;
import org.eclipse.cdt.core.CommandLauncher; import org.eclipse.cdt.core.CommandLauncher;
import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.core.ICommandLauncher;
import org.eclipse.cdt.managedbuilder.buildmodel.IBuildCommand; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildCommand;
import org.eclipse.cdt.managedbuilder.internal.core.ManagedMakeMessages;
import org.eclipse.cdt.utils.PathUtil;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor;
@ -90,9 +88,7 @@ public class CommandBuilder implements IBuildModelBuilder {
* @see org.eclipse.cdt.managedbuilder.internal.builddescription.IBuildDescriptionBuilder#build(java.io.OutputStream, java.io.OutputStream, org.eclipse.core.runtime.IProgressMonitor) * @see org.eclipse.cdt.managedbuilder.internal.builddescription.IBuildDescriptionBuilder#build(java.io.OutputStream, java.io.OutputStream, org.eclipse.core.runtime.IProgressMonitor)
*/ */
@Override @Override
public int build(OutputStream out, OutputStream err, public int build(OutputStream out, OutputStream err, IProgressMonitor monitor){
IProgressMonitor monitor){
//TODO: should we display the command line here? //TODO: should we display the command line here?
monitor.beginTask("", getNumCommands()); //$NON-NLS-1$ monitor.beginTask("", getNumCommands()); //$NON-NLS-1$
monitor.subTask(""/*getCommandLine()*/); //$NON-NLS-1$ monitor.subTask(""/*getCommandLine()*/); //$NON-NLS-1$
@ -112,17 +108,18 @@ public class CommandBuilder implements IBuildModelBuilder {
return STATUS_ERROR_LAUNCH; return STATUS_ERROR_LAUNCH;
} }
int st = ICommandLauncher.ILLEGAL_COMMAND;
if (fProcess != null) { if (fProcess != null) {
try { try {
// Close the input of the process since we will never write to it // Close the input of the process since we will never write to it
fProcess.getOutputStream().close(); fProcess.getOutputStream().close();
} catch (IOException e) { } catch (IOException e) {
} }
//wrapping out and err streams to avoid their closure
st = launcher.waitAndRead(wrap(out), wrap(err),
new SubProgressMonitor(monitor, getNumCommands()));
} }
//wrapping out and err streams to avoid their closure
int st = launcher.waitAndRead(wrap(out), wrap(err),
new SubProgressMonitor(monitor, getNumCommands()));
switch(st){ switch(st){
case ICommandLauncher.OK: case ICommandLauncher.OK:
if(fProcess.exitValue() != 0) if(fProcess.exitValue() != 0)
@ -143,19 +140,7 @@ public class CommandBuilder implements IBuildModelBuilder {
if(DbgUtil.DEBUG) if(DbgUtil.DEBUG)
DbgUtil.trace("error launching the command: " + fErrMsg); //$NON-NLS-1$ DbgUtil.trace("error launching the command: " + fErrMsg); //$NON-NLS-1$
String program = fCmd.getCommand().toOSString(); printMessage(fErrMsg, out);
String envPath = fCmd.getEnvironment().get(PATH_ENV);
if (envPath==null) {
envPath = System.getenv(PATH_ENV);
}
if (PathUtil.findProgramLocation(program, envPath)==null) {
printMessage(fErrMsg, out);
String errMsg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.program.not.in.path", program); //$NON-NLS-1$
printErrorMessage(errMsg + NEWLINE, out);
printMessage(null, PATH_ENV+"=["+envPath+"]", out); //$NON-NLS-1$//$NON-NLS-2$
} else {
printErrorMessage(fErrMsg, out);
}
break; break;
} }
@ -185,14 +170,10 @@ public class CommandBuilder implements IBuildModelBuilder {
return list.toArray(new String[list.size()]); return list.toArray(new String[list.size()]);
} }
private void printMessage(String prefix, String msg, OutputStream os){ protected void printMessage(String msg, OutputStream os){
if (os != null) { if (os != null) {
if (prefix==null) {
prefix=""; //$NON-NLS-1$
}
msg = prefix + msg + NEWLINE;
try { try {
os.write(msg.getBytes()); os.write((msg + NEWLINE).getBytes());
os.flush(); os.flush();
} catch (IOException e) { } catch (IOException e) {
// ignore; // ignore;
@ -201,22 +182,6 @@ public class CommandBuilder implements IBuildModelBuilder {
} }
protected void printMessage(String msg, OutputStream os){
if (os != null) {
msg = ManagedMakeMessages.getFormattedString("InternalBuilder.msg.header", msg); //$NON-NLS-1$
printMessage(null, msg, os);
}
}
private void printErrorMessage(String msg, OutputStream os){
if (os != null) {
String errorPrefix = ManagedMakeMessages.getResourceString("ManagedMakeBuilder.error.prefix"); //$NON-NLS-1$
printMessage(errorPrefix, msg, os);
}
}
public int getNumCommands() { public int getNumCommands() {
return 1; return 1;
} }

View file

@ -35,6 +35,7 @@ public class CommandLauncher implements ICommandLauncher {
public final static int OK = ICommandLauncher.OK; public final static int OK = ICommandLauncher.OK;
private static final String PATH_ENV = "PATH"; //$NON-NLS-1$ private static final String PATH_ENV = "PATH"; //$NON-NLS-1$
private static final String NEWLINE = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
protected Process fProcess; protected Process fProcess;
protected boolean fShowCommand; protected boolean fShowCommand;
@ -42,8 +43,6 @@ public class CommandLauncher implements ICommandLauncher {
private Properties fEnvironment = null; private Properties fEnvironment = null;
protected String fErrorMessage = ""; //$NON-NLS-1$ protected String fErrorMessage = ""; //$NON-NLS-1$
private String lineSeparator;
private IProject fProject; private IProject fProject;
/** /**
@ -59,7 +58,6 @@ public class CommandLauncher implements ICommandLauncher {
public CommandLauncher() { public CommandLauncher() {
fProcess = null; fProcess = null;
fShowCommand = false; fShowCommand = false;
lineSeparator = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
} }
/* (non-Javadoc) /* (non-Javadoc)
@ -161,22 +159,17 @@ public class CommandLauncher implements ICommandLauncher {
* @see org.eclipse.cdt.core.ICommandLauncher#execute(IPath, String[], String[], IPath, IProgressMonitor) * @see org.eclipse.cdt.core.ICommandLauncher#execute(IPath, String[], String[], IPath, IProgressMonitor)
*/ */
@Override @Override
public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, IProgressMonitor monitor) throws CoreException { public Process execute(IPath commandPath, String[] args, String[] env, IPath workingDirectory, IProgressMonitor monitor) throws CoreException {
Boolean isFound = null;
String command = commandPath.toOSString();
String envPathValue = (String) getEnvironment().get(PATH_ENV);
try { try {
String command = commandPath.toOSString();
fCommandArgs = constructCommandArray(command, args); fCommandArgs = constructCommandArray(command, args);
fEnvironment = parseEnv(env);
File file = null;
if(changeToDirectory != null)
file = changeToDirectory.toFile();
if (Platform.getOS().equals(Platform.OS_WIN32)) { if (Platform.getOS().equals(Platform.OS_WIN32)) {
// Handle cygwin link // Handle cygwin link
String envPathValue = (String) getEnvironment().get(PATH_ENV);
IPath location = PathUtil.findProgramLocation(command, envPathValue); IPath location = PathUtil.findProgramLocation(command, envPathValue);
if(location != null) { isFound = location != null;
if (location != null) {
try { try {
fCommandArgs[0] = Cygwin.cygwinToWindowsPath(location.toString(), envPathValue); fCommandArgs[0] = Cygwin.cygwinToWindowsPath(location.toString(), envPathValue);
} catch (Exception e) { } catch (Exception e) {
@ -185,11 +178,33 @@ public class CommandLauncher implements ICommandLauncher {
} }
} }
fProcess = ProcessFactory.getFactory().exec(fCommandArgs, env, file); fEnvironment = parseEnv(env);
File dir = workingDirectory != null ? workingDirectory.toFile() : null;
fProcess = ProcessFactory.getFactory().exec(fCommandArgs, env, dir);
fCommandArgs[0] = command; // to print original command on the console fCommandArgs[0] = command; // to print original command on the console
fErrorMessage = ""; //$NON-NLS-1$ fErrorMessage = ""; //$NON-NLS-1$
} catch (IOException e) { } catch (IOException e) {
setErrorMessage(e.getMessage()); if (isFound == null) {
IPath location = PathUtil.findProgramLocation(command, envPathValue);
isFound = location != null;
}
String errorMessage = getCommandLineQuoted(fCommandArgs, true);
String exMsg = e.getMessage();
if (exMsg != null && !exMsg.isEmpty()) {
errorMessage = errorMessage + exMsg + NEWLINE;
}
if (!isFound) {
if (envPathValue == null) {
envPathValue = System.getenv(PATH_ENV);
}
errorMessage = errorMessage + NEWLINE
+ "Error: Program \"" + command + "\" not found in PATH" + NEWLINE
+ "PATH=[" + envPathValue + "]" + NEWLINE;
}
setErrorMessage(errorMessage);
fProcess = null; fProcess = null;
} }
return fProcess; return fProcess;
@ -254,23 +269,10 @@ public class CommandLauncher implements ICommandLauncher {
return state; return state;
} }
@SuppressWarnings("nls")
protected void printCommandLine(OutputStream os) { protected void printCommandLine(OutputStream os) {
if (os != null) { if (os != null) {
StringBuffer buf = new StringBuffer();
if (fCommandArgs != null) {
for (String commandArg : getCommandArgs()) {
if (commandArg.contains(" ") || commandArg.contains("\"") || commandArg.contains("\\")) {
commandArg = '"' + commandArg.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"") + '"';
}
buf.append(commandArg);
buf.append(' ');
}
buf.append(lineSeparator);
}
try { try {
os.write(buf.toString().getBytes()); os.write(getCommandLineQuoted(getCommandArgs(), true).getBytes());
os.flush(); os.flush();
} catch (IOException e) { } catch (IOException e) {
// ignore; // ignore;
@ -278,18 +280,26 @@ public class CommandLauncher implements ICommandLauncher {
} }
} }
protected String getCommandLine(String[] commandArgs) { @SuppressWarnings("nls")
private String getCommandLineQuoted(String[] commandArgs, boolean quote) {
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
if (fCommandArgs != null) { if (commandArgs != null) {
for (String commandArg : commandArgs) { for (String commandArg : commandArgs) {
if (quote && (commandArg.contains(" ") || commandArg.contains("\"") || commandArg.contains("\\"))) {
commandArg = '"' + commandArg.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"") + '"';
}
buf.append(commandArg); buf.append(commandArg);
buf.append(' '); buf.append(' ');
} }
buf.append(lineSeparator); buf.append(NEWLINE);
} }
return buf.toString(); return buf.toString();
} }
protected String getCommandLine(String[] commandArgs) {
return getCommandLineQuoted(commandArgs, false);
}
/** /**
* @since 5.1 * @since 5.1

View file

@ -55,6 +55,7 @@ public interface ICommandLauncher {
* execution. * execution.
* *
* @return A String corresponding to the error, or <code>null</code> if there has been no error. * @return A String corresponding to the error, or <code>null</code> if there has been no error.
* The message could be multi-line, however it is NOT guaranteed that it ends with end of line.
*/ */
public String getErrorMessage(); public String getErrorMessage();
@ -95,7 +96,7 @@ public interface ICommandLauncher {
* @param env The list of environment variables in variable=value format. * @param env The list of environment variables in variable=value format.
* @throws CoreException if there is an error executing the command. * @throws CoreException if there is an error executing the command.
*/ */
public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, IProgressMonitor monitor) throws CoreException; public Process execute(IPath commandPath, String[] args, String[] env, IPath workingDirectory, IProgressMonitor monitor) throws CoreException;
/** /**
* Reads output form the process to the streams. * Reads output form the process to the streams.