aboutsummaryrefslogtreecommitdiff
path: root/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/BaseBuilder.java
blob: 162591406dc85782ed277b33769f8cd37ee06f0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Eclipse Public License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.eclipse.org/org/documents/epl-v10.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.ide.eclipse.adt.internal.build.builders;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.ide.common.sdk.LoadStatus;
import com.android.ide.eclipse.adt.AdtConstants;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.internal.build.BuildHelper;
import com.android.ide.eclipse.adt.internal.build.Messages;
import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
import com.android.ide.eclipse.adt.internal.project.XmlErrorHandler;
import com.android.ide.eclipse.adt.internal.project.XmlErrorHandler.XmlErrorListener;
import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
import com.android.ide.eclipse.adt.internal.sdk.Sdk;
import com.android.ide.eclipse.adt.io.IFileWrapper;
import com.android.io.IAbstractFile;
import com.android.io.StreamException;
import com.android.sdklib.BuildToolInfo;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.repository.FullRevision;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
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.jobs.Job;
import org.eclipse.jdt.core.IJavaProject;
import org.xml.sax.SAXException;

import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Base builder for XML files. This class allows for basic XML parsing with
 * error checking and marking the files for errors/warnings.
 */
public abstract class BaseBuilder extends IncrementalProjectBuilder {

    protected static final boolean DEBUG_LOG = "1".equals(              //$NON-NLS-1$
            System.getenv("ANDROID_BUILD_DEBUG"));                      //$NON-NLS-1$

    /** SAX Parser factory. */
    private SAXParserFactory mParserFactory;

    /**
     * The build tool to use to build. This is guaranteed to be non null after a call to
     * {@link #abortOnBadSetup(IJavaProject, ProjectState)} since this will throw if it can't be
     * queried.
     */
    protected BuildToolInfo mBuildToolInfo;

    /**
     * Base Resource Delta Visitor to handle XML error
     */
    protected static class BaseDeltaVisitor implements XmlErrorListener {

        /** The Xml builder used to validate XML correctness. */
        protected BaseBuilder mBuilder;

        /**
         * XML error flag. if true, we keep parsing the ResourceDelta but the
         * compilation will not happen (we're putting markers)
         */
        public boolean mXmlError = false;

        public BaseDeltaVisitor(BaseBuilder builder) {
            mBuilder = builder;
        }

        /**
         * Finds a matching Source folder for the current path. This checks if the current path
         * leads to, or is a source folder.
         * @param sourceFolders The list of source folders
         * @param pathSegments The segments of the current path
         * @return The segments of the source folder, or null if no match was found
         */
        protected static String[] findMatchingSourceFolder(ArrayList<IPath> sourceFolders,
                String[] pathSegments) {

            for (IPath p : sourceFolders) {
                // check if we are inside one of those source class path

                // get the segments
                String[] srcSegments = p.segments();

                // compare segments. We want the path of the resource
                // we're visiting to be
                boolean valid = true;
                int segmentCount = pathSegments.length;

                for (int i = 0 ; i < segmentCount; i++) {
                    String s1 = pathSegments[i];
                    String s2 = srcSegments[i];

                    if (s1.equalsIgnoreCase(s2) == false) {
                        valid = false;
                        break;
                    }
                }

                if (valid) {
                    // this folder, or one of this children is a source
                    // folder!
                    // we return its segments
                    return srcSegments;
                }
            }

            return null;
        }

        /**
         * Sent when an XML error is detected.
         * @see XmlErrorListener
         */
        @Override
        public void errorFound() {
            mXmlError = true;
        }
    }

    protected static class AbortBuildException extends Exception {
        private static final long serialVersionUID = 1L;
    }

    public BaseBuilder() {
        super();
        mParserFactory = SAXParserFactory.newInstance();

        // FIXME when the compiled XML support for namespace is in, set this to true.
        mParserFactory.setNamespaceAware(false);
    }

    /**
     * Checks an Xml file for validity. Errors/warnings will be marked on the
     * file
     * @param resource the resource to check
     * @param visitor a valid resource delta visitor
     */
    protected final void checkXML(IResource resource, BaseDeltaVisitor visitor) {

        // first make sure this is an xml file
        if (resource instanceof IFile) {
            IFile file = (IFile)resource;

            // remove previous markers
            removeMarkersFromResource(file, AdtConstants.MARKER_XML);

            // create  the error handler
            XmlErrorHandler reporter = new XmlErrorHandler(file, visitor);
            try {
                // parse
                getParser().parse(file.getContents(), reporter);
            } catch (Exception e1) {
            }
        }
    }

    /**
     * Returns the SAXParserFactory, instantiating it first if it's not already
     * created.
     * @return the SAXParserFactory object
     * @throws ParserConfigurationException
     * @throws SAXException
     */
    protected final SAXParser getParser() throws ParserConfigurationException,
            SAXException {
        return mParserFactory.newSAXParser();
    }

    /**
     * Adds a marker to the current project.  This methods catches thrown {@link CoreException},
     * and returns null instead.
     *
     * @param markerId The id of the marker to add.
     * @param message the message associated with the mark
     * @param severity the severity of the marker.
     * @return the marker that was created (or null if failure)
     * @see IMarker
     */
    protected final IMarker markProject(String markerId, String message, int severity) {
        return BaseProjectHelper.markResource(getProject(), markerId, message, severity);
    }

    /**
     * Removes markers from a resource and only the resource (not its children).
     * @param file The file from which to delete the markers.
     * @param markerId The id of the markers to remove. If null, all marker of
     * type <code>IMarker.PROBLEM</code> will be removed.
     */
    public final void removeMarkersFromResource(IResource resource, String markerId) {
        try {
            if (resource.exists()) {
                resource.deleteMarkers(markerId, true, IResource.DEPTH_ZERO);
            }
        } catch (CoreException ce) {
            String msg = String.format(Messages.Marker_Delete_Error, markerId, resource.toString());
            AdtPlugin.printErrorToConsole(getProject(), msg);
        }
    }

    /**
     * Removes markers from a container and its children.
     * @param folder The container from which to delete the markers.
     * @param markerId The id of the markers to remove. If null, all marker of
     * type <code>IMarker.PROBLEM</code> will be removed.
     */
    protected final void removeMarkersFromContainer(IContainer folder, String markerId) {
        try {
            if (folder.exists()) {
                folder.deleteMarkers(markerId, true, IResource.DEPTH_INFINITE);
            }
        } catch (CoreException ce) {
            String msg = String.format(Messages.Marker_Delete_Error, markerId, folder.toString());
            AdtPlugin.printErrorToConsole(getProject(), msg);
        }
    }

    /**
     * Get the stderr output of a process and return when the process is done.
     * @param process The process to get the ouput from
     * @param stdErr The array to store the stderr output
     * @return the process return code.
     * @throws InterruptedException
     */
    protected final int grabProcessOutput(final Process process,
            final ArrayList<String> stdErr) throws InterruptedException {
        return BuildHelper.grabProcessOutput(getProject(), process, stdErr);
    }



    /**
     * Saves a String property into the persistent storage of the project.
     * @param propertyName the name of the property. The id of the plugin is added to this string.
     * @param value the value to save
     * @return true if the save succeeded.
     */
    protected boolean saveProjectStringProperty(String propertyName, String value) {
        IProject project = getProject();
        return ProjectHelper.saveStringProperty(project, propertyName, value);
    }


    /**
     * Loads a String property from the persistent storage of the project.
     * @param propertyName the name of the property. The id of the plugin is added to this string.
     * @return the property value or null if it was not found.
     */
    protected String loadProjectStringProperty(String propertyName) {
        IProject project = getProject();
        return ProjectHelper.loadStringProperty(project, propertyName);
    }

    /**
     * Saves a property into the persistent storage of the project.
     * @param propertyName the name of the property. The id of the plugin is added to this string.
     * @param value the value to save
     * @return true if the save succeeded.
     */
    protected boolean saveProjectBooleanProperty(String propertyName, boolean value) {
        IProject project = getProject();
        return ProjectHelper.saveStringProperty(project, propertyName, Boolean.toString(value));
    }

    /**
     * Loads a boolean property from the persistent storage of the project.
     * @param propertyName the name of the property. The id of the plugin is added to this string.
     * @param defaultValue The default value to return if the property was not found.
     * @return the property value or the default value if the property was not found.
     */
    protected boolean loadProjectBooleanProperty(String propertyName, boolean defaultValue) {
        IProject project = getProject();
        return ProjectHelper.loadBooleanProperty(project, propertyName, defaultValue);
    }

    /**
     * Aborts the build if the SDK/project setups are broken. This does not
     * display any errors.
     *
     * @param javaProject The {@link IJavaProject} being compiled.
     * @param projectState the project state, optional. will be queried if null.
     * @throws CoreException
     */
    protected void abortOnBadSetup(@NonNull IJavaProject javaProject,
            @Nullable ProjectState projectState) throws AbortBuildException, CoreException {
        IProject iProject = javaProject.getProject();
        // check if we have finished loading the project target.
        Sdk sdk = Sdk.getCurrent();
        if (sdk == null) {
            throw new AbortBuildException();
        }

        if (projectState == null) {
            projectState = Sdk.getProjectState(javaProject.getProject());
        }

        // get the target for the project
        IAndroidTarget target = projectState.getTarget();

        if (target == null) {
            throw new AbortBuildException();
        }

        // check on the target data.
        if (sdk.checkAndLoadTargetData(target, javaProject) != LoadStatus.LOADED) {
            throw new AbortBuildException();
       }

        mBuildToolInfo = projectState.getBuildToolInfo();
        if (mBuildToolInfo == null) {
            mBuildToolInfo = sdk.getLatestBuildTool();

            if (mBuildToolInfo == null) {
                AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, iProject,
                        "No \"Build Tools\" package available; use SDK Manager to install one.");
                throw new AbortBuildException();
            } else {
                AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, iProject,
                        String.format("Using default Build Tools revision %s",
                                mBuildToolInfo.getRevision())
                        );
            }
        }

        // abort if there are TARGET or ADT type markers
        stopOnMarker(iProject, AdtConstants.MARKER_TARGET, IResource.DEPTH_ZERO,
                false /*checkSeverity*/);
        stopOnMarker(iProject, AdtConstants.MARKER_ADT, IResource.DEPTH_ZERO,
                false /*checkSeverity*/);
    }

    protected void stopOnMarker(IProject project, String markerType, int depth,
            boolean checkSeverity)
            throws AbortBuildException {
        try {
            IMarker[] markers = project.findMarkers(markerType, false /*includeSubtypes*/, depth);

            if (markers.length > 0) {
                if (checkSeverity == false) {
                    throw new AbortBuildException();
                } else {
                    for (IMarker marker : markers) {
                        int severity = marker.getAttribute(IMarker.SEVERITY, -1 /*defaultValue*/);
                        if (severity == IMarker.SEVERITY_ERROR) {
                            throw new AbortBuildException();
                        }
                    }
                }
            }
        } catch (CoreException e) {
            // don't stop, something's really screwed up and the build will break later with
            // a better error message.
        }
    }

    /**
     * Handles a {@link StreamException} by logging the info and marking the project.
     * This should generally be followed by exiting the build process.
     *
     * @param e the exception
     */
    protected void handleStreamException(StreamException e) {
        IAbstractFile file = e.getFile();

        String msg;

        IResource target = getProject();
        if (file instanceof IFileWrapper) {
            target = ((IFileWrapper) file).getIFile();

            if (e.getError() == StreamException.Error.OUTOFSYNC) {
                msg = "File is Out of sync";
            } else {
                msg = "Error reading file. Read log for details";
            }

        } else {
            if (e.getError() == StreamException.Error.OUTOFSYNC) {
                msg = String.format("Out of sync file: %s", file.getOsLocation());
            } else {
                msg = String.format("Error reading file %s. Read log for details",
                        file.getOsLocation());
            }
        }

        AdtPlugin.logAndPrintError(e, getProject().getName(), msg);
        BaseProjectHelper.markResource(target, AdtConstants.MARKER_ADT, msg,
                IMarker.SEVERITY_ERROR);
    }

    /**
     * Handles a generic {@link Throwable} by logging the info and marking the project.
     * This should generally be followed by exiting the build process.
     *
     * @param t the {@link Throwable}.
     * @param message the message to log and to associate with the marker.
     */
    protected void handleException(Throwable t, String message) {
        AdtPlugin.logAndPrintError(t, getProject().getName(), message);
        markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);
    }

    /**
     * Recursively delete all the derived resources from a root resource. The root resource is not
     * deleted.
     * @param rootResource the root resource
     * @param monitor a progress monitor.
     * @throws CoreException
     *
     */
    protected void removeDerivedResources(IResource rootResource, IProgressMonitor monitor)
            throws CoreException {
        removeDerivedResources(rootResource, false, monitor);
    }

    /**
     * delete a resource and its children. returns true if the root resource was deleted. All
     * sub-folders *will* be deleted if they were emptied (not if they started empty).
     * @param rootResource the root resource
     * @param deleteRoot whether to delete the root folder.
     * @param monitor a progress monitor.
     * @throws CoreException
     */
    private void removeDerivedResources(IResource rootResource, boolean deleteRoot,
            IProgressMonitor monitor) throws CoreException {
        if (rootResource.exists()) {
            // if it's a folder, delete derived member.
            if (rootResource.getType() == IResource.FOLDER) {
                IFolder folder = (IFolder)rootResource;
                IResource[] members = folder.members();
                boolean wasNotEmpty = members.length > 0;
                for (IResource member : members) {
                    removeDerivedResources(member, true /*deleteRoot*/, monitor);
                }

                // if the folder had content that is now all removed, delete the folder.
                if (deleteRoot && wasNotEmpty && folder.members().length == 0) {
                    rootResource.getLocation().toFile().delete();
                }
            }

            // if the root resource is derived, delete it.
            if (rootResource.isDerived()) {
                rootResource.getLocation().toFile().delete();
            }
        }
    }

    protected void launchJob(Job newJob) {
        newJob.setPriority(Job.BUILD);
        newJob.setRule(ResourcesPlugin.getWorkspace().getRoot());
        newJob.schedule();
    }
}