diff options
Diffstat (limited to 'build/org.eclipse.cdt.managedbuilder.core')
8 files changed, 559 insertions, 889 deletions
diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/AbstractBuildRunner.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/AbstractBuildRunner.java index d387f1ee47b..d3ae5ce2ef8 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/AbstractBuildRunner.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/AbstractBuildRunner.java @@ -20,7 +20,7 @@ import org.eclipse.core.runtime.IProgressMonitor; /** * Interface implemented by toolchain integrators to perform the actual build. - * + * * @author Doug Schaefer * @since 8.0 */ @@ -29,12 +29,13 @@ public abstract class AbstractBuildRunner { /** * Perform the build. * - * @param kind kind from the IncrementalProjectBuilder - * @param project project being built - * @param configuration configuration being built - * @param console console to use for build output - * @param markerGenerator generator to add markers for build problems - * @param monitor progress monitor + * @param kind - kind from the IncrementalProjectBuilder + * @param project - project being built + * @param configuration - configuration being built + * @param console - console to use for build output + * @param markerGenerator - generator to add markers for build problems + * @param monitor - progress monitor in the initial state where {@link IProgressMonitor#beginTask(String, int)} + * has not been called yet. * @throws CoreException standard core exception if something goes wrong */ public abstract boolean invokeBuild(int kind, IProject project, IConfiguration configuration, diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ExternalBuildRunner.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ExternalBuildRunner.java index 5a2c2dafbbf..a20b6bd08f4 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ExternalBuildRunner.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/ExternalBuildRunner.java @@ -1,18 +1,18 @@ /******************************************************************************* - * Copyright (c) 2010, 2011 Wind River Systems and others. + * Copyright (c) 2010, 2012 Wind River Systems and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Wind River Systems - Initial API and implementation - * James Blackburn (Broadcom Corp.) + * Wind River Systems - Initial API and implementation + * James Blackburn (Broadcom Corp.) + * Andrew Gvozdev *******************************************************************************/ package org.eclipse.cdt.managedbuilder.core; import java.io.IOException; -import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; @@ -26,41 +26,29 @@ import org.eclipse.cdt.build.internal.core.scannerconfig2.CfgScannerConfigProfil import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.ErrorParserManager; import org.eclipse.cdt.core.ICommandLauncher; +import org.eclipse.cdt.core.IConsoleParser; import org.eclipse.cdt.core.IMarkerGenerator; import org.eclipse.cdt.core.envvar.IEnvironmentVariable; import org.eclipse.cdt.core.envvar.IEnvironmentVariableManager; -import org.eclipse.cdt.core.model.ICModelMarker; import org.eclipse.cdt.core.resources.IConsole; -import org.eclipse.cdt.core.resources.RefreshScopeManager; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; -import org.eclipse.cdt.internal.core.ConsoleOutputSniffer; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; import org.eclipse.cdt.make.core.scannerconfig.IScannerConfigBuilderInfo2; -import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoCollector; import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoConsoleParser; -import org.eclipse.cdt.make.core.scannerconfig.InfoContext; -import org.eclipse.cdt.make.internal.core.scannerconfig2.SCProfileInstance; -import org.eclipse.cdt.make.internal.core.scannerconfig2.ScannerConfigProfile; -import org.eclipse.cdt.make.internal.core.scannerconfig2.ScannerConfigProfileManager; +import org.eclipse.cdt.make.internal.core.scannerconfig.ScannerInfoConsoleParserFactory; import org.eclipse.cdt.managedbuilder.internal.core.ManagedMakeMessages; import org.eclipse.cdt.managedbuilder.macros.BuildMacroException; import org.eclipse.cdt.managedbuilder.macros.IBuildMacroProvider; -import org.eclipse.cdt.newmake.internal.core.StreamMonitor; import org.eclipse.cdt.utils.CommandLineUtil; import org.eclipse.cdt.utils.EFSExtensionManager; -import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.IncrementalProjectBuilder; -import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; @@ -69,13 +57,7 @@ import org.eclipse.core.runtime.SubProgressMonitor; * @since 8.0 */ public class ExternalBuildRunner extends AbstractBuildRunner { - - private static final String TYPE_CLEAN = "ManagedMakeBuilder.type.clean"; //$NON-NLS-1$ - private static final String TYPE_INC = "ManagedMakeBuider.type.incremental"; //$NON-NLS-1$ - private static final String CONSOLE_HEADER = "ManagedMakeBuilder.message.console.header"; //$NON-NLS-1$ - private static final String WARNING_UNSUPPORTED_CONFIGURATION = "ManagedMakeBuilder.warning.unsupported.configuration"; //$NON-NLS-1$ - 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$ + private static final int MONITOR_SCALE = 100; @Override public boolean invokeBuild(int kind, IProject project, IConfiguration configuration, @@ -88,156 +70,79 @@ public class ExternalBuildRunner extends AbstractBuildRunner { protected boolean invokeExternalBuild(int kind, IProject project, IConfiguration configuration, IBuilder builder, IConsole console, IMarkerGenerator markerGenerator, IncrementalProjectBuilder projectBuilder, IProgressMonitor monitor) throws CoreException { - boolean isClean = false; - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - monitor.beginTask(ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Make_Builder") + project.getName(), 100); //$NON-NLS-1$ + boolean isClean = false; + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask(ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Make_Builder") + project.getName(), 4 * MONITOR_SCALE); //$NON-NLS-1$ + IPath buildCommand = builder.getBuildCommand(); if (buildCommand != null) { - OutputStream cos = console.getOutputStream(); - StringBuffer buf = new StringBuffer(); - - String[] consoleHeader = new String[3]; - switch (kind) { - case IncrementalProjectBuilder.FULL_BUILD: - case IncrementalProjectBuilder.INCREMENTAL_BUILD: - case IncrementalProjectBuilder.AUTO_BUILD: - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_INC); - break; - case IncrementalProjectBuilder.CLEAN_BUILD: - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_CLEAN); - break; - } - - consoleHeader[1] = configuration.getName(); - consoleHeader[2] = project.getName(); - buf.append(NEWLINE); - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)).append(NEWLINE); - buf.append(NEWLINE); - - if(!configuration.isSupported()){ - String unsupportedToolchainMsg = ManagedMakeMessages.getFormattedString(WARNING_UNSUPPORTED_CONFIGURATION, - new String[] { configuration.getName(), configuration.getToolChain().getName() }); - buf.append(unsupportedToolchainMsg).append(NEWLINE); - buf.append(NEWLINE); - } - cos.write(buf.toString().getBytes()); - cos.flush(); - - // remove all markers for this project - IWorkspace workspace = project.getWorkspace(); - IMarker[] markers = project.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE); - if (markers != null) - workspace.deleteMarkers(markers); - - URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); - final String pathFromURI = EFSExtensionManager.getDefault().getPathFromURI(workingDirectoryURI); - if(pathFromURI == null) { - throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, ManagedMakeMessages.getString("ManagedMakeBuilder.message.error"), null)); //$NON-NLS-1$ - } + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isSupported = configuration.isSupported(); - IPath workingDirectory = new Path(pathFromURI); + ICommandLauncher launcher = builder.getCommandLauncher(); String[] targets = getTargets(kind, builder); if (targets.length != 0 && targets[targets.length - 1].equals(builder.getCleanBuildTarget())) isClean = true; - String errMsg = null; - ICommandLauncher launcher = builder.getCommandLauncher(); - launcher.setProject(project); - // Print the command for visual interaction. - launcher.showCommand(true); + String[] args = getCommandArguments(builder, targets); + + URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); - // Set the environment Map<String, String> envMap = getEnvironment(builder); - String[] env = getEnvStrings(envMap); - String[] buildArguments = targets; - - String[] newArgs = CommandLineUtil.argumentsToArray(builder.getBuildArguments()); - buildArguments = new String[targets.length + newArgs.length]; - System.arraycopy(newArgs, 0, buildArguments, 0, newArgs.length); - System.arraycopy(targets, 0, buildArguments, newArgs.length, targets.length); - - QualifiedName qName = new QualifiedName(ManagedBuilderCorePlugin.getUniqueIdentifier(), "progressMonitor"); //$NON-NLS-1$ - Integer last = (Integer)project.getSessionProperty(qName); - if (last == null) { - last = new Integer(100); - } - ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, markerGenerator, builder.getErrorParsers()); - epm.setOutputStream(cos); - StreamMonitor streamMon = new StreamMonitor(new SubProgressMonitor(monitor, 100), epm, last.intValue()); - OutputStream stdout = streamMon; - OutputStream stderr = streamMon; - - // Sniff console output for scanner info - ConsoleOutputSniffer sniffer = createBuildOutputSniffer(stdout, stderr, project, configuration, workingDirectory, markerGenerator, null); - OutputStream consoleOut = (sniffer == null ? stdout : sniffer.getOutputStream()); - OutputStream consoleErr = (sniffer == null ? stderr : sniffer.getErrorStream()); - Process p = launcher.execute(buildCommand, buildArguments, env, workingDirectory, monitor); - if (p != null) { - try { - // Close the input of the Process explicitly. - // We will never write to it. - p.getOutputStream().close(); - } catch (IOException e) { - } - // Before launching give visual cues via the monitor - monitor.subTask(ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Command") + launcher.getCommandLine()); //$NON-NLS-1$ - if (launcher.waitAndRead(consoleOut, consoleErr, new SubProgressMonitor(monitor, 0)) - != ICommandLauncher.OK) - errMsg = launcher.getErrorMessage(); - monitor.subTask(ManagedMakeMessages.getResourceString("MakeBuilder.Updating_project")); //$NON-NLS-1$ - - try { - // 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. - // The caveat is for huge projects, it may take sometimes at every build. - - // TODO should only refresh output folders - //project.refreshLocal(IResource.DEPTH_INFINITE, null); - - // use the refresh scope manager to refresh - RefreshScopeManager refreshManager = RefreshScopeManager.getInstance(); - IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(project); - ResourcesPlugin.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null); - } catch (CoreException e) { - } - } else { - errMsg = launcher.getErrorMessage(); - } - project.setSessionProperty(qName, !monitor.isCanceled() && !isClean ? new Integer(streamMon.getWorkDone()) : null); + String[] envp = BuildRunnerHelper.envMapToEnvp(envMap); - if (errMsg != null) { - consoleErr.write(errMsg.getBytes()); - consoleErr.flush(); - } + String[] errorParsers = builder.getErrorParsers(); + ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, markerGenerator, errorParsers); + + List<IConsoleParser> parsers = new ArrayList<IConsoleParser>(); + collectScannerInfoConsoleParsers(project, configuration, workingDirectoryURI, markerGenerator, parsers); + + buildRunnerHelper.setLaunchParameters(launcher, buildCommand, args, workingDirectoryURI, envp); + buildRunnerHelper.prepareStreams(epm, parsers, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); - buf = new StringBuffer(NEWLINE); - buf.append(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.build.finished")).append(NEWLINE); //$NON-NLS-1$ - consoleOut.write(buf.toString().getBytes()); + buildRunnerHelper.removeOldMarkers(project, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - stdout.close(); - stderr.close(); + buildRunnerHelper.greeting(kind, cfgName, toolchainName, isSupported); + int state = buildRunnerHelper.build(new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); - monitor.subTask(ManagedMakeMessages.getResourceString("MakeBuilder.Creating_Markers")); //$NON-NLS-1$ - consoleOut.close(); - consoleErr.close(); - cos.close(); + if (state != ICommandLauncher.ILLEGAL_COMMAND) { + buildRunnerHelper.refreshProject(new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + } + } else { + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.undefined.build.command", builder.getId()); //$NON-NLS-1$ + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, new Exception())); } } catch (Exception e) { - ManagedBuilderCorePlugin.log(e); - throw new CoreException(new Status(IStatus.ERROR, - ManagedBuilderCorePlugin.getUniqueIdentifier(), - e.getLocalizedMessage(), - e)); + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.error.build", //$NON-NLS-1$ + new String[] { project.getName(), configuration.getName() }); + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, e)); } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(e); + } monitor.done(); } - return (isClean); + return isClean; + } + + private String[] getCommandArguments(IBuilder builder, String[] targets) { + String[] builderArgs = CommandLineUtil.argumentsToArray(builder.getBuildArguments()); + String[] args = new String[targets.length + builderArgs.length]; + System.arraycopy(builderArgs, 0, args, 0, builderArgs.length); + System.arraycopy(targets, 0, args, builderArgs.length, targets.length); + return args; } protected String[] getTargets(int kind, IBuilder builder) { @@ -301,6 +206,7 @@ public class ExternalBuildRunner extends AbstractBuildRunner { return envMap; } + @Deprecated protected static String[] getEnvStrings(Map<String, String> env) { // Convert into env strings List<String> strings= new ArrayList<String>(env.size()); @@ -313,16 +219,19 @@ public class ExternalBuildRunner extends AbstractBuildRunner { return strings.toArray(new String[strings.size()]); } - private ConsoleOutputSniffer createBuildOutputSniffer(OutputStream outputStream, - OutputStream errorStream, - IProject project, - IConfiguration cfg, - IPath workingDirectory, - IMarkerGenerator markerGenerator, - IScannerInfoCollector collector){ + private static void collectScannerInfoConsoleParsers(IProject project, IConfiguration cfg, URI workingDirectoryURI, + IMarkerGenerator markerGenerator, List<IConsoleParser> parsers) { ICfgScannerConfigBuilderInfo2Set container = CfgScannerConfigProfileManager.getCfgScannerConfigBuildInfo(cfg); Map<CfgInfoContext, IScannerConfigBuilderInfo2> map = container.getInfoMap(); - List<IScannerInfoConsoleParser> clParserList = new ArrayList<IScannerInfoConsoleParser>(); + + String pathFromURI = EFSExtensionManager.getDefault().getPathFromURI(workingDirectoryURI); + if(pathFromURI == null) { + // fallback to CWD + pathFromURI = System.getProperty("user.dir"); //$NON-NLS-1$ + } + IPath workingDirectory = new Path(pathFromURI); + + int oldSize = parsers.size(); if(container.isPerRcTypeDiscovery()){ for (IResourceInfo rcInfo : cfg.getResourceInfos()) { @@ -337,66 +246,34 @@ public class ExternalBuildRunner extends AbstractBuildRunner { if(types.length != 0){ for (IInputType type : types) { - CfgInfoContext c = new CfgInfoContext(rcInfo, tool, type); - contributeToConsoleParserList(project, map, c, workingDirectory, markerGenerator, collector, clParserList); + CfgInfoContext context = new CfgInfoContext(rcInfo, tool, type); + IScannerInfoConsoleParser parser = getScannerInfoConsoleParser(project, map, context, workingDirectory, markerGenerator); + if (parser != null) { + parsers.add(parser); + } } } else { - CfgInfoContext c = new CfgInfoContext(rcInfo, tool, null); - contributeToConsoleParserList(project, map, c, workingDirectory, markerGenerator, collector, clParserList); + CfgInfoContext context = new CfgInfoContext(rcInfo, tool, null); + IScannerInfoConsoleParser parser = getScannerInfoConsoleParser(project, map, context, workingDirectory, markerGenerator); + if (parser != null) { + parsers.add(parser); + } } } } } - if(clParserList.size() == 0){ - contributeToConsoleParserList(project, map, new CfgInfoContext(cfg), workingDirectory, markerGenerator, collector, clParserList); - } - - if(clParserList.size() != 0){ - return new ConsoleOutputSniffer(outputStream, errorStream, - clParserList.toArray(new IScannerInfoConsoleParser[clParserList.size()])); - } - - return null; - } - - private boolean contributeToConsoleParserList( - IProject project, - Map<CfgInfoContext, IScannerConfigBuilderInfo2> map, - CfgInfoContext context, - IPath workingDirectory, - IMarkerGenerator markerGenerator, - IScannerInfoCollector collector, - List<IScannerInfoConsoleParser> parserList){ - IScannerConfigBuilderInfo2 info = map.get(context); - InfoContext ic = context.toInfoContext(); - boolean added = false; - if (info != null && - info.isAutoDiscoveryEnabled() && - info.isBuildOutputParserEnabled()) { - - String id = info.getSelectedProfileId(); - ScannerConfigProfile profile = ScannerConfigProfileManager.getInstance().getSCProfileConfiguration(id); - if(profile.getBuildOutputProviderElement() != null){ - // get the make builder console parser - SCProfileInstance profileInstance = ScannerConfigProfileManager.getInstance(). - getSCProfileInstance(project, ic, id); - - IScannerInfoConsoleParser clParser = profileInstance.createBuildOutputParser(); - if (collector == null) { - collector = profileInstance.getScannerInfoCollector(); - } - if(clParser != null){ - clParser.startup(project, workingDirectory, collector, - info.isProblemReportingEnabled() ? markerGenerator : null); - parserList.add(clParser); - added = true; - } - + if(parsers.size() == oldSize){ + CfgInfoContext context = new CfgInfoContext(cfg); + IScannerInfoConsoleParser parser = getScannerInfoConsoleParser(project, map, context, workingDirectory, markerGenerator); + if (parser != null) { + parsers.add(parser); } } - - return added; } + private static IScannerInfoConsoleParser getScannerInfoConsoleParser(IProject project, Map<CfgInfoContext, IScannerConfigBuilderInfo2> map, + CfgInfoContext context, IPath workingDirectory, IMarkerGenerator markerGenerator) { + return ScannerInfoConsoleParserFactory.getScannerInfoConsoleParser(project, context.toInfoContext(), workingDirectory, map.get(context), markerGenerator, null); + } } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/InternalBuildRunner.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/InternalBuildRunner.java index f50ce9993aa..f12791bdc30 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/InternalBuildRunner.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/core/InternalBuildRunner.java @@ -13,74 +13,56 @@ package org.eclipse.cdt.managedbuilder.core; import java.io.IOException; import java.io.OutputStream; +import java.net.URI; -import org.eclipse.cdt.core.ConsoleOutputStream; import org.eclipse.cdt.core.ErrorParserManager; +import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.core.IMarkerGenerator; -import org.eclipse.cdt.core.model.ICModelMarker; import org.eclipse.cdt.core.resources.IConsole; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; import org.eclipse.cdt.managedbuilder.buildmodel.BuildDescriptionManager; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildDescription; import org.eclipse.cdt.managedbuilder.internal.buildmodel.BuildStateManager; import org.eclipse.cdt.managedbuilder.internal.buildmodel.DescriptionBuilder; -import org.eclipse.cdt.managedbuilder.internal.buildmodel.IBuildModelBuilder; import org.eclipse.cdt.managedbuilder.internal.buildmodel.IConfigurationBuildState; import org.eclipse.cdt.managedbuilder.internal.buildmodel.IProjectBuildState; import org.eclipse.cdt.managedbuilder.internal.buildmodel.ParallelBuilder; import org.eclipse.cdt.managedbuilder.internal.core.ManagedMakeMessages; -import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.SubProgressMonitor; /** * The build runner for the internal builder. - * + * * @author dschaefer * @since 8.0 */ public class InternalBuildRunner extends AbstractBuildRunner { - - private static final String INTERNAL_BUILDER = "ManagedMakeBuilder.message.internal.builder"; //$NON-NLS-1$ - private static final String TYPE_INC = "ManagedMakeBuider.type.incremental"; //$NON-NLS-1$ - private static final String TYPE_REBUILD = "ManagedMakeBuider.type.rebuild"; //$NON-NLS-1$ - private static final String CONSOLE_HEADER = "ManagedMakeBuilder.message.console.header"; //$NON-NLS-1$ - private static final String INTERNAL_BUILDER_HEADER_NOTE = "ManagedMakeBuilder.message.internal.builder.header.note"; //$NON-NLS-1$ - private static final String WARNING_UNSUPPORTED_CONFIGURATION = "ManagedMakeBuilder.warning.unsupported.configuration"; //$NON-NLS-1$ - private static final String BUILD_FINISHED = "ManagedMakeBuilder.message.finished"; //$NON-NLS-1$ - private static final String BUILD_CANCELLED = "ManagedMakeBuilder.message.cancelled"; //$NON-NLS-1$ - private static final String BUILD_FINISHED_WITH_ERRS = "ManagedMakeBuilder.message.finished.with.errs"; //$NON-NLS-1$ - private static final String BUILD_STOPPED_ERR = "ManagedMakeBuilder.message.stopped.error"; //$NON-NLS-1$ - private static final String BUILD_FAILED_ERR = "ManagedMakeBuilder.message.internal.builder.error"; //$NON-NLS-1$ - private static final String MARKERS = "ManagedMakeBuilder.message.creating.markers"; //$NON-NLS-1$ - private static final String NOTHING_BUILT = "ManagedMakeBuilder.message.no.build"; //$NON-NLS-1$ - private static final String BUILD_ERROR = "ManagedMakeBuilder.message.error"; //$NON-NLS-1$ + private static final int MONITOR_SCALE = 100; @Override public boolean invokeBuild(int kind, IProject project, IConfiguration configuration, IBuilder builder, IConsole console, IMarkerGenerator markerGenerator, IncrementalProjectBuilder projectBuilder, IProgressMonitor monitor) throws CoreException { - boolean isParallel = builder.getParallelizationNum() > 1; -// boolean buildIncrementaly = true; - boolean resumeOnErr = !builder.isStopOnError(); - - // Get the project and make sure there's a monitor to cancel the build - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - String[] msgs = new String[2]; - msgs[0] = ManagedMakeMessages.getResourceString(INTERNAL_BUILDER); - msgs[1] = project.getName(); + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); - ConsoleOutputStream consoleOutStream = null; - OutputStream epmOutputStream = null; try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask("", 3 * MONITOR_SCALE); //$NON-NLS-1$ + + boolean isParallel = builder.getParallelizationNum() > 1; + boolean resumeOnErr = !builder.isStopOnError(); + int flags = 0; IResourceDelta delta = projectBuilder.getDelta(project); BuildStateManager bsMngr = BuildStateManager.getInstance(); @@ -88,155 +70,78 @@ public class InternalBuildRunner extends AbstractBuildRunner { IConfigurationBuildState cBS = pBS.getConfigurationBuildState(configuration.getId(), true); // if(delta != null){ - flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED | BuildDescriptionManager.DEPS; + flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED | BuildDescriptionManager.DEPS; // delta = getDelta(currentProject); // } boolean buildIncrementaly = delta != null; - // Get a build console for the project - StringBuffer buf = new StringBuffer(); - consoleOutStream = console.getOutputStream(); - String[] consoleHeader = new String[3]; - if(buildIncrementaly) - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_INC); - else - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_REBUILD); - - consoleHeader[1] = configuration.getName(); - consoleHeader[2] = project.getName(); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - - buf.append(ManagedMakeMessages.getResourceString(INTERNAL_BUILDER_HEADER_NOTE)); - buf.append("\n"); //$NON-NLS-1$ - - if(!configuration.isSupported()){ - buf.append(ManagedMakeMessages.getFormattedString(WARNING_UNSUPPORTED_CONFIGURATION, - new String[] { configuration.getName(), configuration.getToolChain().getName()})); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - } - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); + // Prepare launch parameters for BuildRunnerHelper + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isConfigurationSupported = configuration.isSupported(); - IBuildDescription des = BuildDescriptionManager.createBuildDescription(configuration, cBS, delta, flags); + URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); + + String[] errorParsers = builder.getErrorParsers(); + ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, markerGenerator, errorParsers); + buildRunnerHelper.prepareStreams(epm, null, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + + IBuildDescription des = BuildDescriptionManager.createBuildDescription(configuration, cBS, delta, flags); DescriptionBuilder dBuilder = null; - if (!isParallel) + if (!isParallel) { dBuilder = new DescriptionBuilder(des, buildIncrementaly, resumeOnErr, cBS); - - if(isParallel || dBuilder.getNumCommands() > 0) { - // Remove all markers for this project - IWorkspace workspace = project.getWorkspace(); - IMarker[] markers = project.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE); - if (markers != null) - workspace.deleteMarkers(markers); - - // Hook up an error parser manager - String[] errorParsers = builder.getErrorParsers(); - ErrorParserManager epm = new ErrorParserManager(project, des.getDefaultBuildDirLocationURI(), markerGenerator, errorParsers); - epm.setOutputStream(consoleOutStream); - // This variable is necessary to ensure that the EPM stream stay open - // until we explicitly close it. See bug#123302. - epmOutputStream = epm.getOutputStream(); - - int status = 0; - - long t1 = System.currentTimeMillis(); - if (isParallel) - status = ParallelBuilder.build(des, null, null, epmOutputStream, epmOutputStream, monitor, resumeOnErr, buildIncrementaly); - else - status = dBuilder.build(epmOutputStream, epmOutputStream, monitor); - long t2 = System.currentTimeMillis(); - - // Report either the success or failure of our mission - buf = new StringBuffer(); - - switch(status){ - case IBuildModelBuilder.STATUS_OK: - buf.append(ManagedMakeMessages - .getFormattedString(BUILD_FINISHED, - project.getName())); - break; - case IBuildModelBuilder.STATUS_CANCELLED: - buf.append(ManagedMakeMessages - .getResourceString(BUILD_CANCELLED)); - break; - case IBuildModelBuilder.STATUS_ERROR_BUILD: - String msg = resumeOnErr ? - ManagedMakeMessages.getResourceString(BUILD_FINISHED_WITH_ERRS) : - ManagedMakeMessages.getResourceString(BUILD_STOPPED_ERR); - buf.append(msg); - break; - case IBuildModelBuilder.STATUS_ERROR_LAUNCH: - default: - buf.append(ManagedMakeMessages.getResourceString(BUILD_FAILED_ERR)); - break; - } - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - - // Report time and number of threads used - buf.append(ManagedMakeMessages.getFormattedString("CommonBuilder.6", Integer.toString((int)(t2 - t1)))); //$NON-NLS-1$ -// buf.append(t2 - t1); -// buf.append(" ms. "); - if (isParallel) { - buf.append(ManagedMakeMessages.getFormattedString("CommonBuilder.7", Integer.toString(ParallelBuilder.lastThreadsUsed))); //$NON-NLS-1$ -// buf.append(ParallelBuilder.lastThreadsUsed); + if (dBuilder.getNumCommands() <= 0) { + buildRunnerHelper.printLine(ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.no.build", project.getName())); //$NON-NLS-1$ + return false; } - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - // Write message on the console - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - epmOutputStream.close(); - epmOutputStream = null; - // Generate any error markers that the build has discovered - monitor.subTask(ManagedMakeMessages.getResourceString(MARKERS)); - - bsMngr.setProjectBuildState(project, pBS); + } + + buildRunnerHelper.removeOldMarkers(project, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + + if (buildIncrementaly) { + buildRunnerHelper.greeting(IncrementalProjectBuilder.INCREMENTAL_BUILD, cfgName, toolchainName, isConfigurationSupported); } else { - buf = new StringBuffer(); - buf.append(ManagedMakeMessages.getFormattedString(NOTHING_BUILT, project.getName())); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); + buildRunnerHelper.greeting(ManagedMakeMessages.getResourceString("ManagedMakeBuider.type.rebuild"), cfgName, toolchainName, isConfigurationSupported); //$NON-NLS-1$ } + buildRunnerHelper.printLine(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.internal.builder.header.note")); //$NON-NLS-1$ - } catch (Exception e) { - if(consoleOutStream != null){ - StringBuffer buf = new StringBuffer(); - String errorDesc = ManagedMakeMessages - .getResourceString(BUILD_ERROR); - buf.append(errorDesc); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - buf.append(e.getLocalizedMessage()); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - - try { - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - } catch (IOException e1) { - } + OutputStream stdout = buildRunnerHelper.getOutputStream(); + OutputStream stderr = buildRunnerHelper.getErrorStream(); + + int status; + if (dBuilder != null) { + status = dBuilder.build(stdout, stderr, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + } else { + status = ParallelBuilder.build(des, null, null, stdout, stderr, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK), resumeOnErr, buildIncrementaly); + buildRunnerHelper.printLine(ManagedMakeMessages.getFormattedString("CommonBuilder.7", Integer.toString(ParallelBuilder.lastThreadsUsed))); //$NON-NLS-1$ + } + + bsMngr.setProjectBuildState(project, pBS); + + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); + + if (status != ICommandLauncher.ILLEGAL_COMMAND) { + buildRunnerHelper.refreshProject(monitor); } + + } catch (Exception e) { projectBuilder.forgetLastBuiltState(); + + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.error.build", //$NON-NLS-1$ + new String[] { project.getName(), configuration.getName() }); + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, e)); } finally { - if(epmOutputStream != null){ - try { - epmOutputStream.close(); - } catch (IOException e) { - } - } - if(consoleOutStream != null){ - try { - consoleOutStream.close(); - } catch (IOException e) { - } + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(e); } monitor.done(); } + return false; } - } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/buildmodel/CommandBuilder.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/buildmodel/CommandBuilder.java index f4fbfd0244a..712027a2a1d 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/buildmodel/CommandBuilder.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/buildmodel/CommandBuilder.java @@ -21,8 +21,13 @@ import java.util.Set; import org.eclipse.cdt.core.CommandLauncher; import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildCommand; +import org.eclipse.cdt.managedbuilder.core.ManagedBuilderCorePlugin; +import org.eclipse.cdt.managedbuilder.internal.core.ManagedMakeMessages; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; /** @@ -36,7 +41,6 @@ import org.eclipse.core.runtime.SubProgressMonitor; * */ public class CommandBuilder implements IBuildModelBuilder { - 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$ private IBuildCommand fCmd; @@ -84,67 +88,57 @@ public class CommandBuilder implements IBuildModelBuilder { return new OutputStreamWrapper(out); } - /* (non-Javadoc) - * @see org.eclipse.cdt.managedbuilder.internal.builddescription.IBuildDescriptionBuilder#build(java.io.OutputStream, java.io.OutputStream, org.eclipse.core.runtime.IProgressMonitor) - */ @Override - public int build(OutputStream out, OutputStream err, IProgressMonitor monitor){ - //TODO: should we display the command line here? - monitor.beginTask("", getNumCommands()); //$NON-NLS-1$ - monitor.subTask(""/*getCommandLine()*/); //$NON-NLS-1$ + public int build(OutputStream out, OutputStream err, IProgressMonitor monitor) { + int status = STATUS_ERROR_LAUNCH; - ICommandLauncher launcher = createLauncher(); - int status = STATUS_OK; + try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask("", getNumCommands()); //$NON-NLS-1$ + monitor.subTask(ManagedMakeMessages.getResourceString("MakeBuilder.Invoking_Command") + getCommandLine()); //$NON-NLS-1$ - launcher.showCommand(true); + ICommandLauncher launcher = createLauncher(); + launcher.showCommand(true); - try { fProcess = launcher.execute(fCmd.getCommand(), fCmd.getArgs(), mapToStringArray(fCmd.getEnvironment()), fCmd.getCWD(), monitor); - } catch (CoreException e1) { - // TODO Auto-generated catch block - if(DbgUtil.DEBUG) - DbgUtil.trace("Error launching command: " + e1.getMessage()); //$NON-NLS-1$ - monitor.done(); - return STATUS_ERROR_LAUNCH; - } - - int st = ICommandLauncher.ILLEGAL_COMMAND; - if (fProcess != null) { - try { - // Close the input of the process since we will never write to it - fProcess.getOutputStream().close(); - } catch (IOException e) { + if (fProcess != null) { + try { + // Close the input of the process since we will never write to it + fProcess.getOutputStream().close(); + } catch (IOException e) { + } + + // Wrapping out and err streams to avoid their closure + int st = launcher.waitAndRead(wrap(out), wrap(err), new SubProgressMonitor(monitor, getNumCommands())); + switch (st) { + case ICommandLauncher.OK: + // assuming that compiler returns error code after compilation errors + status = fProcess.exitValue() == 0 ? STATUS_OK : STATUS_ERROR_BUILD; + break; + case ICommandLauncher.COMMAND_CANCELED: + status = STATUS_CANCELLED; + break; + case ICommandLauncher.ILLEGAL_COMMAND: + default: + status = STATUS_ERROR_LAUNCH; + break; + } } - //wrapping out and err streams to avoid their closure - st = launcher.waitAndRead(wrap(out), wrap(err), - new SubProgressMonitor(monitor, getNumCommands())); - } - switch(st){ - case ICommandLauncher.OK: - if(fProcess.exitValue() != 0) - status = STATUS_ERROR_BUILD; - break; - case ICommandLauncher.COMMAND_CANCELED: - status = STATUS_CANCELLED; fErrMsg = launcher.getErrorMessage(); - if(DbgUtil.DEBUG) - DbgUtil.trace("command cancelled: " + fErrMsg); //$NON-NLS-1$ - - printMessage(fErrMsg, out); - break; - case ICommandLauncher.ILLEGAL_COMMAND: - default: + if (fErrMsg != null && !fErrMsg.isEmpty()) { + printMessage(fErrMsg, err); + } + } catch (CoreException e) { + ManagedBuilderCorePlugin.log(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, + "Error launching command [" + fCmd.getCommand() + "]", e)); //$NON-NLS-1$ //$NON-NLS-2$ status = STATUS_ERROR_LAUNCH; - fErrMsg = launcher.getErrorMessage(); - if(DbgUtil.DEBUG) - DbgUtil.trace("error launching the command: " + fErrMsg); //$NON-NLS-1$ - - printMessage(fErrMsg, out); - break; + } finally { + monitor.done(); } - monitor.done(); return status; } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/CommonBuilder.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/CommonBuilder.java index e1f9d58adae..8a5565604c1 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/CommonBuilder.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/CommonBuilder.java @@ -15,6 +15,8 @@ package org.eclipse.cdt.managedbuilder.internal.core; import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -25,12 +27,15 @@ import java.util.Set; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.ConsoleOutputStream; +import org.eclipse.cdt.core.ErrorParserManager; +import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.core.ProblemMarkerInfo; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.resources.ACBuilder; import org.eclipse.cdt.core.resources.IConsole; import org.eclipse.cdt.core.settings.model.ICProjectDescription; import org.eclipse.cdt.core.settings.model.util.ListComparator; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; import org.eclipse.cdt.managedbuilder.buildmodel.BuildDescriptionManager; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildDescription; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildStep; @@ -76,14 +81,11 @@ import org.eclipse.core.runtime.jobs.Job; public class CommonBuilder extends ACBuilder { public final static String BUILDER_ID = ManagedBuilderCorePlugin.getUniqueIdentifier() + ".genmakebuilder"; //$NON-NLS-1$ - private static final String BUILD_FINISHED = "ManagedMakeBuilder.message.finished"; //$NON-NLS-1$ - private static final String CONSOLE_HEADER = "ManagedMakeBuilder.message.console.header"; //$NON-NLS-1$ private static final String ERROR_HEADER = "GeneratedmakefileBuilder error ["; //$NON-NLS-1$ private static final String NEWLINE = System.getProperty("line.separator"); //$NON-NLS-1$ private static final String TRACE_FOOTER = "]: "; //$NON-NLS-1$ private static final String TRACE_HEADER = "GeneratedmakefileBuilder trace ["; //$NON-NLS-1$ - private static final String TYPE_CLEAN = "ManagedMakeBuilder.type.clean"; //$NON-NLS-1$ - private static final String TYPE_INC = "ManagedMakeBuider.type.incremental"; //$NON-NLS-1$ + private static final int MONITOR_SCALE = 100; public static boolean VERBOSE = false; private static CfgBuildSet fBuildSet = new CfgBuildSet(); @@ -805,7 +807,7 @@ public class CommonBuilder extends ACBuilder { String configName = bInfo.getConfiguration().getName(); String projName = bInfo.getProject().getName(); if (buildType == FULL_BUILD || buildType == INCREMENTAL_BUILD) { - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_INC); + consoleHeader[0] = ManagedMakeMessages.getResourceString("ManagedMakeBuider.type.incremental"); //$NON-NLS-1$ } else { consoleHeader[0] = new String(); outputError(projName, "The given build type is not supported in this context"); //$NON-NLS-1$ @@ -813,7 +815,7 @@ public class CommonBuilder extends ACBuilder { consoleHeader[1] = configName; consoleHeader[2] = projName; buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)); + buf.append(ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.console.header", consoleHeader)); //$NON-NLS-1$ buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ buf.append(status.getMessage()); @@ -1166,73 +1168,82 @@ public class CommonBuilder extends ACBuilder { protected void cleanWithInternalBuilder(CfgBuildInfo bInfo, IProgressMonitor monitor) throws CoreException { // referencedProjects = getProject().getReferencedProjects(); - IProject curProject = bInfo.getProject(); - outputTrace(curProject.getName(), "Clean build with Internal Builder requested"); //$NON-NLS-1$ - IConfiguration cfg = bInfo.getConfiguration(); + IProject project = bInfo.getProject(); + outputTrace(project.getName(), "Clean build with Internal Builder requested"); //$NON-NLS-1$ + IConfiguration configuration = bInfo.getConfiguration(); int flags = BuildDescriptionManager.DEPFILES; - BuildDescription des = (BuildDescription)BuildDescriptionManager.createBuildDescription(cfg, null, null, flags); + BuildDescription des = (BuildDescription)BuildDescriptionManager.createBuildDescription(configuration, null, null, flags); IBuildStep cleanStep = des.getCleanStep(); StepBuilder sBuilder = new StepBuilder(cleanStep, null, null); + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); try { - // try the brute force approach first - StringBuffer buf = new StringBuffer(); - // write to the console -// -// IConsole console = CCorePlugin.getDefault().getConsole(); -// console.start(getProject()); + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask("", 2 * MONITOR_SCALE); //$NON-NLS-1$ + IConsole console = bInfo.getConsole(); - ConsoleOutputStream consoleOutStream = console.getOutputStream(); - String[] consoleHeader = new String[3]; - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_CLEAN); - consoleHeader[1] = cfg.getName(); - consoleHeader[2] = curProject.getName(); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - buf = new StringBuffer(); - int result = sBuilder.build(consoleOutStream, consoleOutStream, monitor); + + IBuilder builder = bInfo.getBuilder(); + String[] errorParsers = builder.getErrorParsers(); + URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); + ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, this, errorParsers); + + buildRunnerHelper.prepareStreams(epm, null, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + OutputStream stdout = buildRunnerHelper.getOutputStream(); + OutputStream stderr = buildRunnerHelper.getErrorStream(); + + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isConfigurationSupported = configuration.isSupported(); + + buildRunnerHelper.greeting(CLEAN_BUILD, cfgName, toolchainName, isConfigurationSupported); + int status = sBuilder.build(stdout, stderr, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); + + if (status != ICommandLauncher.ILLEGAL_COMMAND) { + buildRunnerHelper.refreshProject(monitor); + } + //Throw a core exception indicating that the clean command failed - if(result == IBuildModelBuilder.STATUS_ERROR_LAUNCH) + if(status == IBuildModelBuilder.STATUS_ERROR_LAUNCH) { - try { - consoleOutStream.close(); - } catch (IOException e) { - } - Status status = new Status(IStatus.INFO, ManagedBuilderCorePlugin.getUniqueIdentifier(), - "Failed to exec delete command"); //$NON-NLS-1$ - throw new CoreException(status); + Status st = new Status(IStatus.INFO, ManagedBuilderCorePlugin.PLUGIN_ID, "Failed to execute delete command"); //$NON-NLS-1$ + throw new CoreException(st); } - // Report a successful clean - String successMsg = ManagedMakeMessages.getFormattedString(BUILD_FINISHED, curProject.getName()); - buf.append(successMsg); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - consoleOutStream.close(); - curProject.refreshLocal(IResource.DEPTH_INFINITE, null); - } catch (IOException io) {} // Ignore console failures... + } catch (Exception e) { + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.error.build", //$NON-NLS-1$ + new String[] { project.getName(), configuration.getName() }); + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, e)); + } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(e); + } + monitor.done(); + } } protected void cleanProgrammatically(CfgBuildInfo bInfo, IProgressMonitor monitor) throws CoreException { // referencedProjects = getProject().getReferencedProjects(); - IProject curProject = bInfo.getProject(); - outputTrace(curProject.getName(), "Clean build requested"); //$NON-NLS-1$ + IProject project = bInfo.getProject(); + outputTrace(project.getName(), "Clean build requested"); //$NON-NLS-1$ IBuilder builder = bInfo.getBuilder(); - IConfiguration cfg = bInfo.getConfiguration(); - IPath buildPath = ManagedBuildManager.getBuildFullPath(cfg, builder); + IConfiguration configuration = bInfo.getConfiguration(); + IPath buildPath = ManagedBuildManager.getBuildFullPath(configuration, builder); if(buildPath == null){ throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.getUniqueIdentifier(), ManagedMakeMessages.getResourceString("CommonBuilder.0"))); //$NON-NLS-1$ } - IPath projectFullPath = curProject.getFullPath(); + IPath projectFullPath = project.getFullPath(); if(!projectFullPath.isPrefixOf(buildPath)){ throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.getUniqueIdentifier(), @@ -1255,37 +1266,47 @@ public class CommonBuilder extends ACBuilder { ManagedBuilderCorePlugin.getUniqueIdentifier(), ManagedMakeMessages.getResourceString("CommonBuilder.13"))); //$NON-NLS-1$ } - String status; - try { - // try the brute force approach first - status = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.clean.deleting.output", buildDir.getName()); //$NON-NLS-1$ - monitor.subTask(status); - workspace.delete(new IResource[]{buildDir}, true, monitor); - StringBuffer buf = new StringBuffer(); - // write to the console -// -// IConsole console = CCorePlugin.getDefault().getConsole(); -// console.start(getProject()); - IConsole console = bInfo.getConsole(); - ConsoleOutputStream consoleOutStream = console.getOutputStream(); - String[] consoleHeader = new String[3]; - consoleHeader[0] = ManagedMakeMessages.getResourceString(TYPE_CLEAN); - consoleHeader[1] = cfg.getName(); - consoleHeader[2] = curProject.getName(); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$ //$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - buf = new StringBuffer(); - // Report a successful clean - String successMsg = ManagedMakeMessages.getFormattedString(BUILD_FINISHED, curProject.getName()); - buf.append(successMsg); - buf.append(System.getProperty("line.separator", "\n")); //$NON-NLS-1$//$NON-NLS-2$ - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - consoleOutStream.close(); - } catch (IOException io) {} // Ignore console failures... + + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); + try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + monitor.beginTask("", 2 * MONITOR_SCALE); //$NON-NLS-1$ + + // try the brute force approach first + String status = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.clean.deleting.output", buildDir.getName()); //$NON-NLS-1$ + monitor.subTask(status); + + IConsole console = bInfo.getConsole(); + + String[] errorParsers = builder.getErrorParsers(); + URI workingDirectoryURI = ManagedBuildManager.getBuildLocationURI(configuration, builder); + ErrorParserManager epm = new ErrorParserManager(project, workingDirectoryURI, this, errorParsers); + + buildRunnerHelper.prepareStreams(epm, null, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isConfigurationSupported = configuration.isSupported(); + + buildRunnerHelper.greeting(CLEAN_BUILD, cfgName, toolchainName, isConfigurationSupported); + workspace.delete(new IResource[]{buildDir}, true, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); + + } catch (Exception e) { + String msg = ManagedMakeMessages.getFormattedString("ManagedMakeBuilder.message.error.build", //$NON-NLS-1$ + new String[] { project.getName(), configuration.getName() }); + throw new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, msg, e)); + } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(e); + } + monitor.done(); + } } } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/GeneratedMakefileBuilder.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/GeneratedMakefileBuilder.java index 1650ca25c24..6c55b220bee 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/GeneratedMakefileBuilder.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/GeneratedMakefileBuilder.java @@ -15,6 +15,7 @@ import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -31,6 +32,7 @@ import org.eclipse.cdt.core.model.ICModelMarker; import org.eclipse.cdt.core.resources.ACBuilder; import org.eclipse.cdt.core.resources.IConsole; import org.eclipse.cdt.core.resources.RefreshScopeManager; +import org.eclipse.cdt.internal.core.BuildRunnerHelper; import org.eclipse.cdt.managedbuilder.buildmodel.BuildDescriptionManager; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildDescription; import org.eclipse.cdt.managedbuilder.buildmodel.IBuildIOType; @@ -307,6 +309,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { private static final String INTERNAL_BUILDER_HEADER_NOTE = "ManagedMakeBuilder.message.internal.builder.header.note"; //$NON-NLS-1$ private static final String TYPE_REBUILD = "ManagedMakeBuider.type.rebuild"; //$NON-NLS-1$ private static final String INTERNAL_BUILDER = "ManagedMakeBuilder.message.internal.builder"; //$NON-NLS-1$ + private static final int MONITOR_SCALE = 100; public static boolean VERBOSE = false; // Local variables @@ -314,7 +317,6 @@ public class GeneratedMakefileBuilder extends ACBuilder { protected IProject[] referencedProjects; protected List<IResource> resourcesToBuild; private IConsole console; - private ConsoleOutputStream consoleOutStream; public static void outputTrace(String resourceName, String message) { if (VERBOSE) { System.out.println(TRACE_HEADER + resourceName + TRACE_FOOTER + message + NEWLINE); @@ -864,7 +866,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { */ protected void invokeMake(int buildType, IPath buildDir, IManagedBuildInfo info, IManagedBuilderMakefileGenerator generator, IProgressMonitor monitor) { // Get the project and make sure there's a monitor to cancel the build - IProject currentProject = getProject(); + IProject project = getProject(); if (monitor == null) { monitor = new NullProgressMonitor(); } @@ -879,7 +881,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { IPath workingDirectory = new Path(pathFromURI); - IWorkspace workspace = currentProject.getWorkspace(); + IWorkspace workspace = project.getWorkspace(); if (workspace == null) { return; } @@ -910,13 +912,13 @@ public class GeneratedMakefileBuilder extends ACBuilder { IPath makeCommand = new Path(makeCmd); String[] msgs = new String[2]; msgs[0] = makeCommand.toString(); - msgs[1] = currentProject.getName(); + msgs[1] = project.getName(); monitor.subTask(ManagedMakeMessages.getFormattedString(MAKE, msgs)); // Get a build console for the project StringBuffer buf = new StringBuffer(); IConsole console = CCorePlugin.getDefault().getConsole(); - console.start(currentProject); + console.start(project); ConsoleOutputStream consoleOutStream = console.getOutputStream(); String[] consoleHeader = new String[3]; switch (buildType) { @@ -930,7 +932,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { } consoleHeader[1] = info.getConfigurationName(); - consoleHeader[2] = currentProject.getName(); + consoleHeader[2] = project.getName(); buf.append(NEWLINE); buf.append(ManagedMakeMessages.getFormattedString(CONSOLE_HEADER, consoleHeader)).append(NEWLINE); buf.append(NEWLINE); @@ -945,24 +947,24 @@ public class GeneratedMakefileBuilder extends ACBuilder { consoleOutStream.flush(); // Remove all markers for this project - removeAllMarkers(currentProject); + removeAllMarkers(project); // Get a launcher for the make command String errMsg = null; IBuilder builder = info.getDefaultConfiguration().getBuilder(); ICommandLauncher launcher = builder.getCommandLauncher(); - launcher.setProject(currentProject); + launcher.setProject(project); launcher.showCommand(true); // Set the environmennt IBuildEnvironmentVariable variables[] = ManagedBuildManager.getEnvironmentVariableProvider().getVariables(cfg,true,true); - String[] env = null; + String[] envp = null; ArrayList<String> envList = new ArrayList<String>(); if (variables != null) { for(int i = 0; i < variables.length; i++){ envList.add(variables[i].getName() + "=" + variables[i].getValue()); //$NON-NLS-1$ } - env = envList.toArray(new String[envList.size()]); + envp = envList.toArray(new String[envList.size()]); } // Hook up an error parser manager @@ -1014,7 +1016,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { premakeArgs.add("-q"); //$NON-NLS-1$ premakeArgs.add("main-build"); //$NON-NLS-1$ premakeTargets = premakeArgs.toArray(new String[premakeArgs.size()]); - proc = launcher.execute(makeCommand, premakeTargets, env, workingDirectory, monitor); + proc = launcher.execute(makeCommand, premakeTargets, envp, workingDirectory, monitor); if (proc != null) { try { // Close the input of the process since we will never write to it @@ -1041,7 +1043,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { // If the status value returned from "make -q" is 0, then the build state is up-to-date isuptodate = true; // Report that the build was up to date, and thus nothing needs to be built - String uptodateMsg = ManagedMakeMessages.getFormattedString(NOTHING_BUILT, currentProject.getName()); + String uptodateMsg = ManagedMakeMessages.getFormattedString(NOTHING_BUILT, project.getName()); buf = new StringBuffer(); buf.append(NEWLINE); buf.append(uptodateMsg).append(NEWLINE); @@ -1080,7 +1082,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { // Launch make - main invocation if (!isuptodate) { - proc = launcher.execute(makeCommand, makeTargets, env, workingDirectory, monitor); + proc = launcher.execute(makeCommand, makeTargets, envp, workingDirectory, monitor); if (proc != null) { try { // Close the input of the process since we will never write to it @@ -1112,7 +1114,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { // use the refresh scope manager to refresh RefreshScopeManager refreshManager = RefreshScopeManager.getInstance(); - IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(currentProject); + IWorkspaceRunnable runnable = refreshManager.getRefreshRunnable(project); ResourcesPlugin.getWorkspace().run(runnable, null, IWorkspace.AVOID_UPDATE, null); } catch (CoreException e) { monitor.subTask(ManagedMakeMessages @@ -1129,7 +1131,7 @@ public class GeneratedMakefileBuilder extends ACBuilder { } else { // Report a successful build String successMsg = ManagedMakeMessages.getFormattedString(BUILD_FINISHED, - currentProject.getName()); + project.getName()); buf.append(successMsg).append(NEWLINE); } @@ -1367,330 +1369,280 @@ public class GeneratedMakefileBuilder extends ACBuilder { } } + private Map<IProject, List<IFile>> arrangeFilesByProject(List<IFile> files) { + Map<IProject, List<IFile>> projectMap = new HashMap<IProject, List<IFile>>(); + for (IFile file : files) { + IProject project = file.getProject(); + List<IFile> filesInProject = projectMap.get(project); + if (filesInProject == null) { + filesInProject = new ArrayList<IFile>(); + projectMap.put(project, filesInProject); + } + filesInProject.add(file); + } + return projectMap; + } + /** - * Called to invoke the MBS Internal Builder for building the given resources in - * the given configuration + * Called to invoke the MBS Internal Builder for building the given resources * - * This method is considered experimental. Clients implementing this API should expect - * possible changes in the API. - * - * @param resourcesToBuild resources to be built - * @param cfg configuration to be built - * @param buildIncrementaly if true, incremental build will be performed, - * only files that need rebuild will be built. - * If false, full rebuild will be performed - * @param resumeOnErr if true, build will continue in case of error while building. - * If false the build will stop on the first error - * @param monitor Progress monitor. For every resource built this monitor will consume one unit of work. + * @param files - list of files to build. + * @param monitor - progress monitor to report progress to user. + * @return status of the operation. Can be {@link Status#OK_STATUS} or + * {@link Status#CANCEL_STATUS}. */ - public void invokeInternalBuilder(IResource[] resourcesToBuild, IConfiguration cfg, - boolean buildIncrementaly, - boolean resumeOnErr, - boolean initNewConsole, - boolean printFinishedMessage, - IProgressMonitor monitor) { - - OutputStream epmOutputStream = null; - // Get the project and make sure there's a monitor to cancel the build - IProject currentProject = cfg.getOwner().getProject(); + public IStatus invokeInternalBuilder(List<IFile> files, IProgressMonitor monitor) { + // Make sure there's a monitor to cancel the build if (monitor == null) { monitor = new NullProgressMonitor(); } try { - int flags = 0; - IResourceDelta delta = null; - - if(buildIncrementaly){ - flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED | BuildDescriptionManager.DEPS; - delta = getDelta(currentProject); - } - - - String[] msgs = new String[2]; - msgs[0] = ManagedMakeMessages.getResourceString(INTERNAL_BUILDER); - msgs[1] = currentProject.getName(); - - if(initNewConsole) - initNewBuildConsole(currentProject); + Map<IProject, List<IFile>> projectMap = arrangeFilesByProject(files); + monitor.beginTask("", projectMap.size() * MONITOR_SCALE); //$NON-NLS-1$ - StringBuffer buf = new StringBuffer(); - - if (initNewConsole) { - String msg; - if (buildIncrementaly) { - msg = ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.buildSelectedIncremental"); //$NON-NLS-1$ - } else { - msg = ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.buildSelectedRebuild"); //$NON-NLS-1$ - } - - buf.append(msg).append(NEWLINE); - buf.append(NEWLINE); - - buf.append(ManagedMakeMessages.getResourceString(INTERNAL_BUILDER_HEADER_NOTE)).append(NEWLINE); + for (List<IFile> filesInProject : projectMap.values()) { + IProject project = filesInProject.get(0).getProject(); + monitor.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.buildingProject", project.getName())); //$NON-NLS-1$ + invokeInternalBuilderForOneProject(filesInProject, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); } - - if(!cfg.isSupported()){ - String msg = ManagedMakeMessages.getFormattedString(WARNING_UNSUPPORTED_CONFIGURATION,new String[] {cfg.getName(),cfg.getToolChain().getName()}); - buf.append(msg).append(NEWLINE); - buf.append(NEWLINE); + } finally { + if (monitor.isCanceled()) { + return Status.CANCEL_STATUS; } - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); + monitor.done(); + } + return Status.OK_STATUS; + } - // Remove all markers for this project - // TODO remove only necessary markers - removeAllMarkers(currentProject); + private void invokeInternalBuilderForOneProject(List<IFile> files, IProgressMonitor monitor) { + IProject project = files.get(0).getProject(); + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); - IBuildDescription des = BuildDescriptionManager.createBuildDescription(cfg, delta, flags); + try { + monitor.beginTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.buildingProject", project.getName()) + ':', files.size() * MONITOR_SCALE); //$NON-NLS-1$ - // Hook up an error parser manager - String[] errorParsers = cfg.getErrorParserList(); - ErrorParserManager epm = new ErrorParserManager(currentProject, des.getDefaultBuildDirLocationURI(), this, errorParsers); - epm.setOutputStream(consoleOutStream); - // This variable is necessary to ensure that the EPM stream stay open - // until we explicitly close it. See bug#123302. - epmOutputStream = epm.getOutputStream(); + // Get a build console for the project + console = CCorePlugin.getDefault().getConsole(); + console.start(project); - boolean errorsFound = false; + IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project); + IConfiguration configuration = buildInfo.getDefaultConfiguration(); - doneBuild: for (int k = 0; k < resourcesToBuild.length; k++) { - IBuildResource buildResource = des - .getBuildResource(resourcesToBuild[k]); + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isSupported = configuration.isSupported(); -// step collector - Set<IBuildStep> dependentSteps = new HashSet<IBuildStep>(); + IBuildDescription des = BuildDescriptionManager.createBuildDescription(configuration, null, 0); -// get dependent IO types - IBuildIOType depTypes[] = buildResource.getDependentIOTypes(); + String[] errorParsers = configuration.getErrorParserList(); + ErrorParserManager epm = new ErrorParserManager(project, des.getDefaultBuildDirLocationURI(), this, errorParsers); -// iterate through each type and add the step the type belongs to to the collector - for(int j = 0; j < depTypes.length; j++){ - IBuildIOType type = depTypes[j]; - if(type != null && type.getStep() != null) - dependentSteps.add(type.getStep()); - } + buildRunnerHelper.prepareStreams(epm, null, console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); + OutputStream stdout = buildRunnerHelper.getOutputStream(); + OutputStream stderr = buildRunnerHelper.getErrorStream(); - monitor.subTask(ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.buildingFile") + resourcesToBuild[k].getProjectRelativePath()); //$NON-NLS-1$ + buildRunnerHelper.greeting(ManagedMakeMessages.getResourceString("BuildFilesAction.buildingSelectedFiles"), cfgName, toolchainName, isSupported); //$NON-NLS-1$ + buildRunnerHelper.printLine(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.internal.builder.header.note")); //$NON-NLS-1$ - // iterate through all build steps - Iterator<IBuildStep> stepIter = dependentSteps.iterator(); + // Build artifacts for each file in the project + for (IFile file : files) { + if (monitor.isCanceled()) { + break; + } + String filePath = file.getProjectRelativePath().toString(); - while(stepIter.hasNext()) - { - IBuildStep step = stepIter.next(); + try { + IBuildResource buildResource = des.getBuildResource(file); - StepBuilder stepBuilder = new StepBuilder(step, null); + Set<IBuildStep> dependentSteps = new HashSet<IBuildStep>(); + IBuildIOType depTypes[] = buildResource.getDependentIOTypes(); + for (IBuildIOType btype : depTypes) { + if(btype != null && btype.getStep() != null) + dependentSteps.add(btype.getStep()); + } - int status = stepBuilder.build(epmOutputStream, epmOutputStream, new SubProgressMonitor(monitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + SubProgressMonitor monitor2 = new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); + try { + monitor2.beginTask("", (1 + dependentSteps.size()) * MONITOR_SCALE); //$NON-NLS-1$ - // Refresh the output resource without allowing the user to cancel. - // This is probably unkind, but short of this there is no way to ensure - // the UI is up-to-date with the build results - IBuildIOType[] outputIOTypes = step.getOutputIOTypes(); + // Remove problem markers for the file + monitor2.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.removingResourceMarkers", filePath)); //$NON-NLS-1$ + buildRunnerHelper.removeOldMarkers(file, new SubProgressMonitor(monitor2, 1 * MONITOR_SCALE, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); - for(int j = 0; j < outputIOTypes.length; j++ ) - { - IBuildResource[] resources = outputIOTypes[j].getResources(); + // Build dependent steps + for (IBuildStep step : dependentSteps) { + if (monitor2.isCanceled()) { + break; + } - for(int i = 0; i < resources.length; i++) - { - IFile file = currentProject.getFile(resources[i].getLocation()); - file.refreshLocal(IResource.DEPTH_INFINITE, null); + monitor2.subTask(filePath); + StepBuilder stepBuilder = new StepBuilder(step, null); + stepBuilder.build(stdout, stderr, new SubProgressMonitor(monitor2, 1 * MONITOR_SCALE, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); + + monitor2.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.refreshingArtifacts", filePath)); //$NON-NLS-1$ + IBuildIOType[] outputIOTypes = step.getOutputIOTypes(); + for (IBuildIOType type : outputIOTypes) { + for (IBuildResource outResource : type.getResources()) { + IFile outFile = project.getFile(outResource.getLocation()); + // Refresh the output resource without allowing the user to cancel. + outFile.refreshLocal(IResource.DEPTH_INFINITE, null); + } + } } + } finally { + monitor2.done(); } - // check status - - switch (status) { - case IBuildModelBuilder.STATUS_OK: - // don't print anything if the step was successful, - // since the build might not be done as a whole - break; - case IBuildModelBuilder.STATUS_CANCELLED: - buf.append(ManagedMakeMessages - .getResourceString(BUILD_CANCELLED)); - break doneBuild; - case IBuildModelBuilder.STATUS_ERROR_BUILD: - errorsFound = true; - if (!resumeOnErr) { - buf.append(ManagedMakeMessages - .getResourceString(BUILD_STOPPED_ERR)); - break doneBuild; - } - break; - case IBuildModelBuilder.STATUS_ERROR_LAUNCH: - default: - buf.append(ManagedMakeMessages - .getResourceString(BUILD_FAILED_ERR)); - break doneBuild; - } + } catch (Exception e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ } - - } - - // check status - // Report either the success or failure of our mission - buf = new StringBuffer(); - - buf.append(NEWLINE); - - if (printFinishedMessage) { - if (errorsFound) { - buf.append(ManagedMakeMessages.getResourceString(BUILD_FAILED_ERR)); - } else { - buf.append(ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.buildResourcesFinished")); //$NON-NLS-1$ - } } + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); - // Write message on the console - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - - // Generate any error markers that the build has discovered - addBuilderMarkers(epm); } catch (Exception e) { - if(consoleOutStream != null){ - StringBuffer buf = new StringBuffer(); - String errorDesc = ManagedMakeMessages.getResourceString(BUILD_ERROR); - buf.append(errorDesc).append(NEWLINE); - buf.append("(").append(e.getLocalizedMessage()).append(")").append(NEWLINE); //$NON-NLS-1$ //$NON-NLS-2$ - - try { - consoleOutStream.write(buf.toString().getBytes()); - consoleOutStream.flush(); - } catch (IOException e1) { - } - } + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ forgetLastBuiltState(); } finally { - if(epmOutputStream != null){ - try { - epmOutputStream.close(); - } catch (IOException e) { - } - } - if(consoleOutStream != null){ - try { - consoleOutStream.close(); - } catch (IOException e) { - } - } getGenerationProblems().clear(); - monitor.done(); - } - } - - private void removeAllMarkers(IFile file) { - IMarker[] markers; - try { - markers = file.findMarkers( - ICModelMarker.C_MODEL_PROBLEM_MARKER, true, - IResource.DEPTH_INFINITE); - } catch (CoreException e) { - // Handled just about every case in the sanity check - return; - } - if (markers != null) { try { - file.getWorkspace().deleteMarkers(markers); - } catch (CoreException e) { - // The only situation that might cause this is some sort of - // resource change event - return; + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ } + monitor.done(); } } - public void cleanFile(IFile file, IProgressMonitor monitor) { - - monitor.subTask(ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.0") //$NON-NLS-1$ - + file.getProjectRelativePath()); - - // remove all markers on the file - removeAllMarkers(file); - - IProject currentProject = file.getProject(); - - IManagedBuildInfo info = ManagedBuildManager - .getBuildInfo(currentProject); + public IStatus cleanFiles(List<IFile> files, IProgressMonitor monitor) { + // Make sure there's a monitor to cancel the build + if (monitor == null) { + monitor = new NullProgressMonitor(); + } - // if we have no info then don't do anything - if (info == null) { - // monitor.worked(1); - return; + try { + Map<IProject, List<IFile>> projectMap = arrangeFilesByProject(files); + monitor.beginTask("", projectMap.size() * MONITOR_SCALE); //$NON-NLS-1$ + for (List<IFile> filesInProject : projectMap.values()) { + IProject project = filesInProject.get(0).getProject(); + monitor.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.cleaningProject", project.getName())); //$NON-NLS-1$ + cleanFilesForOneProject(filesInProject, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); + } + } finally { + if (monitor.isCanceled()) { + return Status.CANCEL_STATUS; + } + monitor.done(); } + return Status.OK_STATUS; + } - IConfiguration cfg = info.getDefaultConfiguration(); + public void cleanFilesForOneProject(List<IFile> files, IProgressMonitor monitor) { + IProject project = files.get(0).getProject(); + BuildRunnerHelper buildRunnerHelper = new BuildRunnerHelper(project); + int countDeleted = 0; - // figure out the output file for this file -// IPath sourcePath = file.getProjectRelativePath(); + try { + monitor.beginTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.cleaningProject", project.getName()) + ':', files.size() * MONITOR_SCALE); //$NON-NLS-1$ - int flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED; - IResourceDelta delta = getDelta(currentProject); + // Get a build console for the project + console = CCorePlugin.getDefault().getConsole(); + console.start(project); - try { - IBuildDescription des = BuildDescriptionManager - .createBuildDescription(cfg, delta, flags); + IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project); + IConfiguration configuration = buildInfo.getDefaultConfiguration(); - IBuildResource buildResource = des.getBuildResource(file); + String cfgName = configuration.getName(); + String toolchainName = configuration.getToolChain().getName(); + boolean isSupported = configuration.isSupported(); + int flags = BuildDescriptionManager.REBUILD | BuildDescriptionManager.REMOVED; + IResourceDelta delta = getDelta(project); - if (buildResource != null) { + IBuildDescription des = BuildDescriptionManager.createBuildDescription(configuration, delta, flags); - // step collector - Set<IBuildStep> dependentSteps = new HashSet<IBuildStep>(); + String[] errorParsers = configuration.getErrorParserList(); + ErrorParserManager epm = new ErrorParserManager(project, des.getDefaultBuildDirLocationURI(), this, errorParsers); + buildRunnerHelper.prepareStreams(epm, null , console, new SubProgressMonitor(monitor, 1 * MONITOR_SCALE)); - // get dependent IO types - IBuildIOType depTypes[] = buildResource.getDependentIOTypes(); + buildRunnerHelper.greeting(ManagedMakeMessages.getResourceString("CleanFilesAction.cleanSelectedFiles"), cfgName, toolchainName, isSupported); //$NON-NLS-1$ + buildRunnerHelper.printLine(ManagedMakeMessages.getResourceString("ManagedMakeBuilder.message.internal.builder.header.note")); //$NON-NLS-1$ - // iterate through each type and add the step the type belongs - // to to - // the collector - for (int j = 0; j < depTypes.length; j++) { - IBuildIOType type = depTypes[j]; - if (type != null && type.getStep() != null) - dependentSteps.add(type.getStep()); + for (IFile file : files) { + if (monitor.isCanceled()) { + break; } + String filePath = file.getProjectRelativePath().toString(); - // iterate through all build steps - Iterator<IBuildStep> stepIter = dependentSteps.iterator(); + try { + IBuildResource buildResource = des.getBuildResource(file); + if (buildResource != null) { + Set<IBuildStep> dependentSteps = new HashSet<IBuildStep>(); + IBuildIOType depTypes[] = buildResource.getDependentIOTypes(); + for (IBuildIOType btype : depTypes) { + if (btype != null && btype.getStep() != null) + dependentSteps.add(btype.getStep()); + } - while (stepIter.hasNext()) { - IBuildStep step = stepIter.next(); + SubProgressMonitor monitor2 = new SubProgressMonitor(monitor, 1 * MONITOR_SCALE, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); + try { + monitor2.beginTask("", (1 + dependentSteps.size()) * MONITOR_SCALE); //$NON-NLS-1$ - // Delete the output resources - IBuildIOType[] outputIOTypes = step.getOutputIOTypes(); + // Remove problem markers for the file + monitor2.subTask(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.removingResourceMarkers", filePath)); //$NON-NLS-1$ + buildRunnerHelper.removeOldMarkers(file, new SubProgressMonitor(monitor2, 1 * MONITOR_SCALE, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); - for (int j = 0; j < outputIOTypes.length; j++) { - IBuildResource[] resources = outputIOTypes[j].getResources(); + // iterate through all build steps + for (IBuildStep step : dependentSteps) { + if (monitor2.isCanceled()) { + break; + } - for (int i = 0; i < resources.length; i++) { - IResource outputFile = currentProject.findMember(resources[i] - .getFullPath().removeFirstSegments(1)); // strip project name + monitor2.subTask(filePath); + // Delete the output resources + IBuildIOType[] outputIOTypes = step.getOutputIOTypes(); + + for (IBuildIOType ioType : outputIOTypes) { + for (IBuildResource rc : ioType.getResources()) { + IResource outputFile = project.findMember(rc.getFullPath().removeFirstSegments(1)); // strip project name + if (outputFile != null) { + outputFile.delete(true, null); + countDeleted++; + buildRunnerHelper.printLine(ManagedMakeMessages.getFormattedString("GeneratedMakefileBuilder.fileDeleted", //$NON-NLS-1$ + outputFile.getProjectRelativePath().toString())); + } + } + } - if (outputFile != null) - outputFile.delete(true, new SubProgressMonitor(monitor, 1)); + monitor2.worked(1 * MONITOR_SCALE); + } + } finally { + monitor2.done(); } } - + } catch (Exception e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ } + + } + if (countDeleted == 0) { + buildRunnerHelper.printLine(ManagedMakeMessages.getResourceString("GeneratedMakefileBuilder.nothingToClean")); //$NON-NLS-1$ } + buildRunnerHelper.close(); + buildRunnerHelper.goodbye(); - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (Exception e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ + } finally { + try { + buildRunnerHelper.close(); + } catch (IOException e) { + ManagedBuilderCorePlugin.log(new CoreException(new Status(IStatus.ERROR, ManagedBuilderCorePlugin.PLUGIN_ID, "CDT Build Error", e))); //$NON-NLS-1$ + } + monitor.done(); } - - } - - - private void initNewBuildConsole(IProject currentProject) throws CoreException { - // Get a build console for the project - console = CCorePlugin.getDefault().getConsole(); - console.start(currentProject); - consoleOutStream = console.getOutputStream(); } } diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/PluginResources.properties b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/PluginResources.properties index abadc94b1c7..83ee8b40fa1 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/PluginResources.properties +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/internal/core/PluginResources.properties @@ -21,10 +21,11 @@ ManagedMakeBuilder.message.regen.deps = Regenerating dependency files for {0} ManagedMakeBuilder.message.updating.deps = Updating dependency files for {0} ManagedMakeBuilder.message.creating.markers = Generating markers... ManagedMakeBuilder.message.console.header = **** {0} of configuration {1} for project {2} **** -ManagedMakeBuilder.message.internal.builder.header.note = **** Internal Builder is used for build **** -ManagedMakeBuilder.message.no.build = Nothing to build for {0} -ManagedMakeBuilder.message.error = Build error -ManagedMakeBuilder.message.error.refresh = Error refreshing project +ManagedMakeBuilder.message.internal.builder.header.note = Info: Internal Builder is used for build +ManagedMakeBuilder.message.no.build = Info: Nothing to build for {0} +ManagedMakeBuilder.message.error = Internal error during build, see eclipse error log. +ManagedMakeBuilder.message.error.build = Internal error building project {0} configuration {1} +ManagedMakeBuilder.message.undefined.build.command = Build command is null for builder {0} ManagedMakeBuilder.message.finished = Build complete for project {0} ManagedMakeBuilder.message.cancelled = Build cancelled ManagedMakeBuilder.message.finished.with.errs = Build completed with errors @@ -117,7 +118,6 @@ BuildMacroStatus.status.macro.undefined=Macro {0} is undefined BuildFilesAction.buildingSelectedFiles=Building Selected Files BuildDescriptionGnuMakefileGenerator.0=IO exception occurred: BuildDescriptionGnuMakefileGenerator.1=IO exception occurred: -BuildFilesAction.buildSelectedFile=Build the selected file. BuildMacroStatus.status.reference.eachother=Macros {0} and {1} reference each other BuildMacroStatus.status.reference.incorrect=Macro {0} reference is incorrect BuildMacroStatus.status.macro.not.string=Macro {0} is not of String type @@ -130,15 +130,14 @@ BuildInfoFactory.Missing_Builder=Missing Builder: ResourceChangeHandler.buildInfoSerializationJob=Build Info Serialization #ManagedBuilderCorePlugin messages -GeneratedMakefileBuilder.buildResourcesFinished=Build of selected resources is complete. -GeneratedMakefileBuilder.buildSelectedIncremental=Building selected file(s) incrementally -GeneratedMakefileBuilder.buildSelectedRebuild=Rebuilding selected file(s) -GeneratedMakefileBuilder.buildingFile=Building file +GeneratedMakefileBuilder.buildingProject=Building project {0} +GeneratedMakefileBuilder.cleaningProject=Cleaning project {0} +GeneratedMakefileBuilder.removingResourceMarkers=Removing problem markers for {0} +GeneratedMakefileBuilder.refreshingArtifacts=Refreshing build artefacts for {0} +GeneratedMakefileBuilder.fileDeleted={0} deleted. +GeneratedMakefileBuilder.nothingToClean=Nothing to clean. GenerateMakefileWithBuildDescription.0=info is null GenerateMakefileWithBuildDescription.1=cfg is null -GeneratedMakefileBuilder.0=Cleaning output file(s) for -BuildFilesAction.building=Building -BuildFilesAction.buildFiles=Build File(s) ManagedBuilderCorePlugin.resourceChangeHandlingInitializationJob=Initializing Resource Change Handling #Internal Builder messages @@ -146,7 +145,7 @@ InternalBuilder.msg.header=Internal Builder: {0} InternalBuilder.nothing.todo=Nothing to be done for project {0} CfgScannerConfigUtil_ErrorNotSupported=Only type {0} is supported in this method. CleanFilesAction.cleanFiles=Clean File(s) -CleanFilesAction.cleanSelectedFiles=Clean the selected file(s). +CleanFilesAction.cleanSelectedFiles=Cleaning Selected Files CleanFilesAction.cleaningFiles=Cleaning files BuilderFactory.1=can not find builder with the specified id FolderInfo.4=converter invocation failed @@ -156,7 +155,7 @@ GnuLinkOutputNameProvider.0=tool parent must be one of configuration, toolchain, CommonBuilder.1=customized builder created for builder that does not support customization CommonBuilder.2=request for building non active configuration for the builder that does not support this CommonBuilder.6=Time consumed: {0} ms. -CommonBuilder.7=Parallel threads used: {0} +CommonBuilder.7=Info: Parallel threads used: {0} CommonBuilder.0=can not clean programmatically: build workspace path is not specified CommonBuilder.16=can not clean programmatically: build workspace path is not the project path CommonBuilder.12=can not clean programmatically: build workspace path is not folder diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/newmake/internal/core/StreamMonitor.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/newmake/internal/core/StreamMonitor.java index ed578a8a63c..f139d67f758 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/newmake/internal/core/StreamMonitor.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/newmake/internal/core/StreamMonitor.java @@ -10,97 +10,18 @@ *******************************************************************************/ package org.eclipse.cdt.newmake.internal.core; -import java.io.IOException; import java.io.OutputStream; import org.eclipse.core.runtime.IProgressMonitor; -public class StreamMonitor extends OutputStream { - - IProgressMonitor monitor; - OutputStream console; - public final int fTotalWork; - private int halfWay; - private int currentIncrement = 2; - private int nextProgress = currentIncrement; - private int worked = 0; - +/** +* +* @deprecated as of CDT 8.1. Use org.eclipse.cdt.internal.core.StreamMonitor +* +*/ +@Deprecated +public class StreamMonitor extends org.eclipse.cdt.internal.core.StreamMonitor { public StreamMonitor(IProgressMonitor mon, OutputStream cos, int totalWork) { - monitor = mon; - console = cos; - fTotalWork = totalWork; - halfWay = fTotalWork / 2; - monitor.beginTask("", fTotalWork); //$NON-NLS-1$ - } - - private void progressUpdate() { - if (--nextProgress <= 0) { - //we have exhausted the current increment, so report progress - if (fTotalWork > worked) { - monitor.worked(1); - } - worked++; - if (worked >= halfWay) { - //we have passed the current halfway point, so double the - //increment and reset the halfway point. - currentIncrement *= 2; - halfWay += (fTotalWork - halfWay) / 2; - } - //reset the progress counter to another full increment - nextProgress = currentIncrement; - } - } - /** - * @see java.io.OutputStream#close() - */ - @Override - public void close() throws IOException { - if (console != null) { - console.close(); - } - monitor.done(); - } - - /** - * @see java.io.OutputStream#flush() - */ - @Override - public void flush() throws IOException { - if (console != null) { - console.flush(); - } - } - - /** - * @see java.io.OutputStream#write(int) - */ - @Override - public synchronized void write(int b) throws IOException { - if (console != null) { - console.write(b); - } - progressUpdate(); - } - - /** - * @see java.io.OutputStream#write(byte[], int, int) - */ - @Override - public synchronized void write(byte[] b, int off, int len) throws IOException { - if (b == null) { - throw new NullPointerException(); - } else if (off != 0 || (len < 0) || (len > b.length)) { - throw new IndexOutOfBoundsException(); - } else if (len == 0) { - return; - } - if (console != null) { - console.write(b, off, len); - } - progressUpdate(); - } - - public int getWorkDone() { - return worked; + super(mon, cos, totalWork); } } |