AbstractProject.java 68.2 KB
Newer Older
K
kohsuke 已提交
1 2 3
/*
 * The MIT License
 * 
4 5
 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
 * Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot,
6 7
 * Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts,
 * id:cactusman, Yahoo! Inc.
K
kohsuke 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
27 28
package hudson.model;

29
import java.util.regex.Pattern;
30
import antlr.ANTLRException;
K
kohsuke 已提交
31
import hudson.AbortException;
32
import hudson.CopyOnWrite;
33
import hudson.FeedAdapter;
34
import hudson.FilePath;
35
import hudson.Launcher;
36
import hudson.Util;
37
import hudson.cli.declarative.CLIMethod;
38
import hudson.cli.declarative.CLIResolver;
39
import hudson.diagnosis.OldDataMonitor;
M
mdonohue 已提交
40
import hudson.model.Cause.LegacyCodeCause;
41
import hudson.model.Cause.RemoteCause;
42
import hudson.model.Cause.UserCause;
43 44
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
K
kohsuke 已提交
45
import hudson.model.Queue.Executable;
46
import hudson.model.Queue.Task;
47
import hudson.model.queue.SubTask;
48 49
import hudson.model.Queue.WaitingItem;
import hudson.model.RunMap.Constructor;
50 51
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
52
import hudson.model.queue.CauseOfBlockage;
53
import hudson.model.queue.SubTaskContributor;
K
kohsuke 已提交
54
import hudson.scm.ChangeLogSet;
K
kohsuke 已提交
55
import hudson.scm.ChangeLogSet.Entry;
56
import hudson.scm.NullSCM;
57
import hudson.scm.PollingResult;
58
import hudson.scm.SCM;
59
import hudson.scm.SCMRevisionState;
60
import hudson.scm.SCMS;
J
jbq 已提交
61
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
62
import hudson.security.Permission;
63
import hudson.slaves.WorkspaceList;
64
import hudson.tasks.BuildStep;
65
import hudson.tasks.BuildStepDescriptor;
J
jbq 已提交
66
import hudson.tasks.BuildTrigger;
67
import hudson.tasks.BuildWrapperDescriptor;
68
import hudson.tasks.Mailer;
69
import hudson.tasks.Publisher;
K
kohsuke 已提交
70
import hudson.triggers.SCMTrigger;
71
import hudson.triggers.Trigger;
72
import hudson.triggers.TriggerDescriptor;
73 74
import hudson.util.AlternativeUiTextProvider;
import hudson.util.AlternativeUiTextProvider.Message;
75
import hudson.util.DescribableList;
76
import hudson.util.EditDistance;
S
 
shinodkm 已提交
77
import hudson.util.FormValidation;
K
kohsuke 已提交
78 79 80
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import net.sf.json.JSONObject;
81 82
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
83 84 85
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
86
import org.kohsuke.stapler.HttpResponses;
87
import org.kohsuke.stapler.QueryParameter;
K
kohsuke 已提交
88 89 90
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
91

K
kohsuke 已提交
92
import javax.servlet.ServletException;
93
import java.io.File;
94
import java.io.IOException;
K
kohsuke 已提交
95
import java.lang.reflect.InvocationTargetException;
K
kohsuke 已提交
96
import java.util.ArrayList;
97
import java.util.Arrays;
98
import java.util.Calendar;
99
import java.util.Collection;
J
jbq 已提交
100
import java.util.Collections;
101
import java.util.Comparator;
J
jbq 已提交
102
import java.util.HashSet;
103
import java.util.LinkedList;
104 105
import java.util.List;
import java.util.Map;
J
jbq 已提交
106
import java.util.Set;
107 108 109
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
K
kohsuke 已提交
110
import java.util.concurrent.Future;
111 112
import java.util.logging.Level;
import java.util.logging.Logger;
113

114 115 116
import static hudson.scm.PollingResult.*;
import static javax.servlet.http.HttpServletResponse.*;

117 118
/**
 * Base implementation of {@link Job}s that build software.
119
 *
120
 * For now this is primarily the common part of {@link Project} and MavenModule.
121
 *
122 123 124
 * @author Kohsuke Kawaguchi
 * @see AbstractBuild
 */
125
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
126

127
    /**
128 129 130
     * {@link SCM} associated with the project.
     * To allow derived classes to link {@link SCM} config to elsewhere,
     * access to this variable should always go through {@link #getScm()}.
131
     */
K
kohsuke 已提交
132
    private volatile SCM scm = new NullSCM();
133

134 135 136 137 138
    /**
     * State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.
     */
    private volatile transient SCMRevisionState pollingBaseline = null;

139 140 141
    /**
     * All the builds keyed by their build number.
     */
142
    protected transient /*almost final*/ RunMap<R> builds = new RunMap<R>();
143 144 145 146

    /**
     * The quiet period. Null to delegate to the system default.
     */
K
kohsuke 已提交
147
    private volatile Integer quietPeriod = null;
S
 
shinodkm 已提交
148 149
    
    /**
150
     * The retry count. Null to delegate to the system default.
S
 
shinodkm 已提交
151
     */
152
    private volatile Integer scmCheckoutRetryCount = null;
153 154

    /**
155 156 157 158 159 160 161
     * If this project is configured to be only built on a certain label,
     * this value will be set to that label.
     *
     * For historical reasons, this is called 'assignedNode'. Also for
     * a historical reason, null to indicate the affinity
     * with the master node.
     *
162
     * @see #canRoam
163 164 165 166 167
     */
    private String assignedNode;

    /**
     * True if this project can be built on any node.
168
     *
169
     * <p>
170 171
     * This somewhat ugly flag combination is so that we can migrate
     * existing Hudson installations nicely.
172
     */
K
kohsuke 已提交
173
    private volatile boolean canRoam;
174 175 176 177

    /**
     * True to suspend new builds.
     */
K
kohsuke 已提交
178
    protected volatile boolean disabled;
179

180 181 182 183 184 185
    /**
     * True to keep builds of this project in queue when downstream projects are
     * building. False by default to keep from breaking existing behavior.
     */
    protected volatile boolean blockBuildWhenDownstreamBuilding = false;

186 187 188 189 190 191
    /**
     * True to keep builds of this project in queue when upstream projects are
     * building. False by default to keep from breaking existing behavior.
     */
    protected volatile boolean blockBuildWhenUpstreamBuilding = false;

192
    /**
193 194 195
     * Identifies {@link JDK} to be used.
     * Null if no explicit configuration is required.
     *
196
     * <p>
197 198 199
     * Can't store {@link JDK} directly because {@link Hudson} and {@link Project}
     * are saved independently.
     *
200 201
     * @see Hudson#getJDK(String)
     */
K
kohsuke 已提交
202
    private volatile String jdk;
203

204
    /**
M
mindless 已提交
205
     * @deprecated since 2007-01-29.
206 207
     */
    private transient boolean enableRemoteTrigger;
208

K
kohsuke 已提交
209
    private volatile BuildAuthorizationToken authToken = null;
210

211 212 213
    /**
     * List of all {@link Trigger}s for this project.
     */
214
    protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
215

216 217
    /**
     * {@link Action}s contributed from subsidiary objects associated with
218 219 220 221
     * {@link AbstractProject}, such as from triggers, builders, publishers, etc.
     *
     * We don't want to persist them separately, and these actions
     * come and go as configuration change, so it's kept separate.
222
     */
223 224
    @CopyOnWrite
    protected transient volatile List<Action> transientActions = new Vector<Action>();
225

K
kohsuke 已提交
226 227
    private boolean concurrentBuild;

228
    protected AbstractProject(ItemGroup parent, String name) {
229
        super(parent,name);
230

K
kohsuke 已提交
231
        if(!Hudson.getInstance().getNodes().isEmpty()) {
232
            // if a new job is configured with Hudson that already has slave nodes
233 234 235
            // make it roamable by default
            canRoam = true;
        }
236 237 238 239 240 241 242
    }

    @Override
    public void onCreatedFromScratch() {
        super.onCreatedFromScratch();
        // solicit initial contributions, especially from TransientProjectActionFactory
        updateTransientActions();
243 244
    }

245
    @Override
246
    public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
247
        super.onLoad(parent, name);
248 249

        this.builds = new RunMap<R>();
250
        this.builds.load(this,new Constructor<R>() {
251 252 253 254 255
            public R create(File dir) throws IOException {
                return loadBuild(dir);
            }
        });

256 257 258
        // boolean! Can't tell if xml file contained false..
        if (enableRemoteTrigger) OldDataMonitor.report(this, "1.77");
        if(triggers==null) {
259
            // it didn't exist in < 1.28
260
            triggers = new Vector<Trigger<?>>();
261 262
            OldDataMonitor.report(this, "1.28");
        }
263
        for (Trigger t : triggers)
264
            t.start(this,false);
265 266
        if(scm==null)
            scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
267

268 269
        if(transientActions==null)
            transientActions = new Vector<Action>();    // happens when loaded from disk
270
        updateTransientActions();
271 272
    }

273
    @Override
274
    protected void performDelete() throws IOException, InterruptedException {
K
kohsuke 已提交
275 276
        // prevent a new build while a delete operation is in progress
        makeDisabled(true);
277
        FilePath ws = getWorkspace();
278
        if(ws!=null) {
K
NPE fix  
kohsuke 已提交
279 280 281 282
            Node on = getLastBuiltOn();
            getScm().processWorkspaceBeforeDeletion(this, ws, on);
            if(on!=null)
                on.getFileSystemProvisioner().discardWorkspace(this,ws);
283
        }
K
kohsuke 已提交
284 285 286
        super.performDelete();
    }

K
kohsuke 已提交
287 288
    /**
     * Does this project perform concurrent builds?
K
kohsuke 已提交
289
     * @since 1.319
K
kohsuke 已提交
290
     */
K
kohsuke 已提交
291
    @Exported
K
kohsuke 已提交
292 293 294 295 296 297 298 299 300
    public boolean isConcurrentBuild() {
        return Hudson.CONCURRENT_BUILD && concurrentBuild;
    }

    public void setConcurrentBuild(boolean b) throws IOException {
        concurrentBuild = b;
        save();
    }

301
    /**
302 303
     * If this project is configured to be always built on this node,
     * return that {@link Node}. Otherwise null.
304
     */
305
    public Label getAssignedLabel() {
306
        if(canRoam)
307 308
            return null;

309
        if(assignedNode==null)
310 311
            return Hudson.getInstance().getSelfLabel();
        return Hudson.getInstance().getLabel(assignedNode);
312 313
    }

314 315 316 317
    /**
     * Gets the textual representation of the assigned label as it was entered by the user.
     */
    public String getAssignedLabelString() {
318 319 320 321 322 323 324 325
        if (canRoam || assignedNode==null)    return null;
        try {
            LabelExpression.parseExpression(assignedNode);
            return assignedNode;
        } catch (ANTLRException e) {
            // must be old label or host name that includes whitespace or other unsafe chars
            return LabelAtom.escape(assignedNode);
        }
326 327
    }

K
kohsuke 已提交
328 329 330 331 332 333 334 335 336 337
    /**
     * Sets the assigned label.
     */
    public void setAssignedLabel(Label l) throws IOException {
        if(l==null) {
            canRoam = true;
            assignedNode = null;
        } else {
            canRoam = false;
            if(l==Hudson.getInstance().getSelfLabel())  assignedNode = null;
338
            else                                        assignedNode = l.getExpression();
K
kohsuke 已提交
339 340 341 342
        }
        save();
    }

343 344 345 346 347 348 349
    /**
     * Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.
     */
    public void setAssignedNode(Node l) throws IOException {
        setAssignedLabel(l.getSelfLabel());
    }

350
    /**
351 352
     * Get the term used in the UI to represent this kind of {@link AbstractProject}.
     * Must start with a capital letter.
353 354 355
     */
    @Override
    public String getPronoun() {
K
Kohsuke Kawaguchi 已提交
356
        return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun());
357 358
    }

359 360 361 362 363 364 365 366 367
    /**
     * Gets the human readable display name to be rendered in the "Build Now" link.
     *
     * @since 1.401
     */
    public String getBuildNowText() {
        return AlternativeUiTextProvider.get(BUILD_NOW_TEXT,this,Messages.AbstractProject_BuildNow());
    }

368 369 370 371 372
    /**
     * Returns the root project value.
     *
     * @return the root project value.
     */
373
    public AbstractProject getRootProject() {
374 375 376 377 378 379 380
        if (this.getParent() instanceof Hudson) {
            return this;
        } else {
            return ((AbstractProject) this.getParent()).getRootProject();
        }
    }

381 382
    /**
     * Gets the directory where the module is checked out.
383 384 385
     *
     * @return
     *      null if the workspace is on a slave that's not connected.
K
kohsuke 已提交
386
     * @deprecated as of 1.319
K
kohsuke 已提交
387 388 389 390 391
     *      To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.
     *      For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called
     *      from {@link Executor}, and otherwise the workspace of the last build.
     *
     *      <p>
392
     *      If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
K
kohsuke 已提交
393 394 395 396
     *      If you are calling this method to serve a file from the workspace, doing a form validation, etc., then
     *      use {@link #getSomeWorkspace()}
     */
    public final FilePath getWorkspace() {
397 398 399 400 401 402 403 404 405 406 407 408
        AbstractBuild b = getBuildForDeprecatedMethods();
        return b != null ? b.getWorkspace() : null;

    }
    
    /**
     * Various deprecated methods in this class all need the 'current' build.  This method returns
     * the build suitable for that purpose.
     * 
     * @return An AbstractBuild for deprecated methods to use.
     */
    private AbstractBuild getBuildForDeprecatedMethods() {
K
kohsuke 已提交
409 410 411 412 413 414
        Executor e = Executor.currentExecutor();
        if(e!=null) {
            Executable exe = e.getCurrentExecutable();
            if (exe instanceof AbstractBuild) {
                AbstractBuild b = (AbstractBuild) exe;
                if(b.getProject()==this)
415
                    return b;
K
kohsuke 已提交
416 417 418
            }
        }
        R lb = getLastBuild();
419
        if(lb!=null)    return lb;
K
kohsuke 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432
        return null;
    }

    /**
     * Gets a workspace for some build of this project.
     *
     * <p>
     * This is useful for obtaining a workspace for the purpose of form field validation, where exactly
     * which build the workspace belonged is less important. The implementation makes a cursory effort
     * to find some workspace.
     *
     * @return
     *      null if there's no available workspace.
K
kohsuke 已提交
433
     * @since 1.319
434
     */
K
kohsuke 已提交
435
    public final FilePath getSomeWorkspace() {
436 437 438 439 440 441 442 443 444 445
        R b = getSomeBuildWithWorkspace();
        return b!=null ? b.getWorkspace() : null;
    }

    /**
     * Gets some build that has a live workspace.
     *
     * @return null if no such build exists.
     */
    public final R getSomeBuildWithWorkspace() {
K
kohsuke 已提交
446 447 448
        int cnt=0;
        for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
            FilePath ws = b.getWorkspace();
449
            if (ws!=null)   return b;
K
kohsuke 已提交
450 451 452
        }
        return null;
    }
453

454 455 456
    /**
     * Returns the root directory of the checked-out module.
     * <p>
457 458
     * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
     * and so on exists.
K
kohsuke 已提交
459
     *
K
kohsuke 已提交
460
     * @deprecated as of 1.319
K
kohsuke 已提交
461
     *      See {@link #getWorkspace()} for a migration strategy.
462 463
     */
    public FilePath getModuleRoot() {
464 465
        AbstractBuild b = getBuildForDeprecatedMethods();
        return b != null ? b.getModuleRoot() : null;
466 467
    }

S
stephenconnolly 已提交
468 469 470 471 472 473
    /**
     * Returns the root directories of all checked-out modules.
     * <p>
     * Some SCMs support checking out multiple modules into the same workspace.
     * In these cases, the returned array will have a length greater than one.
     * @return The roots of all modules checked out from the SCM.
K
kohsuke 已提交
474
     *
K
kohsuke 已提交
475
     * @deprecated as of 1.319
K
kohsuke 已提交
476
     *      See {@link #getWorkspace()} for a migration strategy.
S
stephenconnolly 已提交
477 478
     */
    public FilePath[] getModuleRoots() {
479 480
        AbstractBuild b = getBuildForDeprecatedMethods();
        return b != null ? b.getModuleRoots() : null;
S
stephenconnolly 已提交
481 482
    }

483
    public int getQuietPeriod() {
484
        return quietPeriod!=null ? quietPeriod : Hudson.getInstance().getQuietPeriod();
485
    }
S
 
shinodkm 已提交
486
    
487 488
    public int getScmCheckoutRetryCount() {
        return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Hudson.getInstance().getScmCheckoutRetryCount();
S
 
shinodkm 已提交
489
    }
490 491 492

    // ugly name because of EL
    public boolean getHasCustomQuietPeriod() {
493
        return quietPeriod!=null;
494
    }
K
kohsuke 已提交
495 496 497 498

    /**
     * Sets the custom quiet period of this project, or revert to the global default if null is given. 
     */
499
    public void setQuietPeriod(Integer seconds) throws IOException {
K
kohsuke 已提交
500 501 502
        this.quietPeriod = seconds;
        save();
    }
S
 
shinodkm 已提交
503
    
504
    public boolean hasCustomScmCheckoutRetryCount(){
505
        return scmCheckoutRetryCount != null;
S
 
shinodkm 已提交
506
    }
507

508
    @Override
509
    public boolean isBuildable() {
J
jpederzolli 已提交
510
        return !isDisabled() && !isHoldOffBuildUntilSave();
511 512
    }

513
    /**
514 515
     * Used in <tt>sidepanel.jelly</tt> to decide whether to display
     * the config/delete/build links.
516 517 518 519 520
     */
    public boolean isConfigurable() {
        return true;
    }

521 522 523 524 525 526 527 528 529
    public boolean blockBuildWhenDownstreamBuilding() {
        return blockBuildWhenDownstreamBuilding;
    }

    public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException {
        blockBuildWhenDownstreamBuilding = b;
        save();
    }

530
    public boolean blockBuildWhenUpstreamBuilding() {
531
        return blockBuildWhenUpstreamBuilding;
532 533
    }

534
    public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
535 536
        blockBuildWhenUpstreamBuilding = b;
        save();
537 538
    }

539 540 541
    public boolean isDisabled() {
        return disabled;
    }
S
 
shinodkm 已提交
542 543 544 545 546
    
    /**
     * Validates the retry count Regex
     */
    public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
547 548 549 550 551 552 553
        // retry count is optional so this is ok
        if(value == null || value.trim().equals(""))
            return FormValidation.ok();
        if (!value.matches("[0-9]*")) {
            return FormValidation.error("Invalid retry count");
        } 
        return FormValidation.ok();
S
 
shinodkm 已提交
554
    }
555

556 557 558 559
    /**
     * Marks the build as disabled.
     */
    public void makeDisabled(boolean b) throws IOException {
560
        if(disabled==b)     return; // noop
561
        this.disabled = b;
K
bug fix  
kohsuke 已提交
562 563
        if(b)
            Hudson.getInstance().getQueue().cancel(this);
564 565 566
        save();
    }

567 568 569 570 571 572 573 574
    public void disable() throws IOException {
        makeDisabled(true);
    }

    public void enable() throws IOException {
        makeDisabled(false);
    }

K
kohsuke 已提交
575 576
    @Override
    public BallColor getIconColor() {
577
        if(isDisabled())
578
            return BallColor.DISABLED;
K
kohsuke 已提交
579 580 581
        else
            return super.getIconColor();
    }
582

583 584 585 586 587 588 589
    /**
     * effectively deprecated. Since using updateTransientActions correctly
     * under concurrent environment requires a lock that can too easily cause deadlocks.
     *
     * <p>
     * Override {@link #createTransientActions()} instead.
     */
590
    protected void updateTransientActions() {
591 592 593 594
        transientActions = createTransientActions();
    }

    protected List<Action> createTransientActions() {
595
        Vector<Action> ta = new Vector<Action>();
596

597 598
        for (JobProperty<? super P> p : properties)
            ta.addAll(p.getJobActions((P)this));
599

600 601
        for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
            ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
602
        return ta;
603 604
    }

605
    /**
606 607
     * Returns the live list of all {@link Publisher}s configured for this project.
     *
608
     * <p>
609 610
     * This method couldn't be called <tt>getPublishers()</tt> because existing methods
     * in sub-classes return different inconsistent types.
611
     */
612
    public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
613

K
kohsuke 已提交
614 615 616 617 618 619
    @Override
    public void addProperty(JobProperty<? super P> jobProp) throws IOException {
        super.addProperty(jobProp);
        updateTransientActions();
    }

620 621 622 623
    public List<ProminentProjectAction> getProminentActions() {
        List<Action> a = getActions();
        List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
        for (Action action : a) {
624
            if(action instanceof ProminentProjectAction)
625 626 627 628 629
                pa.add((ProminentProjectAction) action);
        }
        return pa;
    }

630
    @Override
631
    public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
632
        super.doConfigSubmit(req,rsp);
633

634 635
        updateTransientActions();

636
        Set<AbstractProject> upstream = Collections.emptySet();
637 638
        if(req.getParameter("pseudoUpstreamTrigger")!=null) {
            upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class));
639 640 641 642 643 644 645 646 647
        }

        // dependency setting might have been changed by the user, so rebuild.
        Hudson.getInstance().rebuildDependencyGraph();

        // reflect the submission of the pseudo 'upstream build trriger'.
        // this needs to be done after we release the lock on 'this',
        // or otherwise we could dead-lock

648
        for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
649 650
            // Don't consider child projects such as MatrixConfiguration:
            if (!p.isConfigurable()) continue;
651
            boolean isUpstream = upstream.contains(p);
652 653 654
            synchronized(p) {
                // does 'p' include us in its BuildTrigger? 
                DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
655
                BuildTrigger trigger = pl.get(BuildTrigger.class);
656 657 658
                List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects();
                if(isUpstream) {
                    if(!newChildProjects.contains(this))
659 660 661 662 663
                        newChildProjects.add(this);
                } else {
                    newChildProjects.remove(this);
                }

664
                if(newChildProjects.isEmpty()) {
665
                    pl.remove(BuildTrigger.class);
666
                } else {
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
                    // here, we just need to replace the old one with the new one,
                    // but there was a regression (we don't know when it started) that put multiple BuildTriggers
                    // into the list.
                    // for us not to lose the data, we need to merge them all.
                    List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
                    BuildTrigger existing;
                    switch (existingList.size()) {
                    case 0:
                        existing = null;
                        break;
                    case 1:
                        existing = existingList.get(0);
                        break;
                    default:
                        pl.removeAll(BuildTrigger.class);
                        Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
                        for (BuildTrigger bt : existingList)
                            combinedChildren.addAll(bt.getChildProjects());
                        existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
                        pl.add(existing);
                        break;
                    }

690 691
                    if(existing!=null && existing.hasSame(newChildProjects))
                        continue;   // no need to touch
692
                    pl.replace(new BuildTrigger(newChildProjects,
693
                        existing==null?Result.SUCCESS:existing.getThreshold()));
694 695 696 697 698 699 700 701 702 703 704
                }
            }
        }

        // notify the queue as the project might be now tied to different node
        Hudson.getInstance().getQueue().scheduleMaintenance();

        // this is to reflect the upstream build adjustments done above
        Hudson.getInstance().rebuildDependencyGraph();
    }

M
mdonohue 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild(Cause)}.  Since 1.283
	 */
    public boolean scheduleBuild() {
    	return scheduleBuild(new LegacyCodeCause());
    }
    
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild(int, Cause)}.  Since 1.283
	 */
    public boolean scheduleBuild(int quietPeriod) {
    	return scheduleBuild(quietPeriod, new LegacyCodeCause());
    }
    
721 722
    /**
     * Schedules a build of this project.
723 724 725 726 727
     *
     * @return
     *      true if the project is actually added to the queue.
     *      false if the queue contained it and therefore the add()
     *      was noop
728
     */
M
mdonohue 已提交
729 730
    public boolean scheduleBuild(Cause c) {
        return scheduleBuild(getQuietPeriod(), c);
K
kohsuke 已提交
731 732
    }

M
mdonohue 已提交
733
    public boolean scheduleBuild(int quietPeriod, Cause c) {
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        return scheduleBuild(quietPeriod, c, new Action[0]);
    }

    /**
     * Schedules a build.
     *
     * Important: the actions should be persistable without outside references (e.g. don't store
     * references to this project). To provide parameters for a parameterized project, add a ParametersAction. If
     * no ParametersAction is provided for such a project, one will be created with the default parameter values.
     *
     * @param quietPeriod the quiet period to observer
     * @param c the cause for this build which should be recorded
     * @param actions a list of Actions that will be added to the build
     * @return whether the build was actually scheduled
     */
    public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {
750 751 752 753 754 755
        return scheduleBuild2(quietPeriod,c,actions)!=null;
    }

    /**
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
756 757 758
     *
     * @param actions
     *      For the convenience of the caller, this array can contain null, and those will be silently ignored.
759 760
     */
    public Future<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
K
kohsuke 已提交
761 762 763 764 765 766 767 768 769 770 771 772
        return scheduleBuild2(quietPeriod,c,Arrays.asList(actions));
    }

    /**
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
     *
     * @param actions
     *      For the convenience of the caller, this collection can contain null, and those will be silently ignored.
     * @since 1.383
     */
    public Future<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {
773
        if (!isBuildable())
774
            return null;
775

K
kohsuke 已提交
776
        List<Action> queueActions = new ArrayList<Action>(actions);
777 778 779 780
        if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
            queueActions.add(new ParametersAction(getDefaultParametersValues()));
        }

S
sogabe 已提交
781 782 783 784
        if (c != null) {
            queueActions.add(new CauseAction(c));
        }

785 786 787 788
        WaitingItem i = Hudson.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
        if(i!=null)
            return (Future)i.getFuture();
        return null;
789 790 791 792 793 794
    }

    private List<ParameterValue> getDefaultParametersValues() {
        ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
        ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
        
M
mindless 已提交
795 796 797
        /*
         * This check is made ONLY if someone will call this method even if isParametrized() is false.
         */
798 799 800 801 802 803 804 805 806 807 808 809 810
        if(paramDefProp == null)
            return defValues;
        
        /* Scan for all parameter with an associated default values */
        for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
        {
           ParameterValue defaultValue  = paramDefinition.getDefaultParameterValue();
            
            if(defaultValue != null)
                defValues.add(defaultValue);           
        }
        
        return defValues;
K
kohsuke 已提交
811 812
    }

813
    /**
814 815 816 817
     * Schedules a build, and returns a {@link Future} object
     * to wait for the completion of the build.
     *
     * <p>
818
     * Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
819
     * as deprecated.
820
     */
M
mdonohue 已提交
821
    public Future<R> scheduleBuild2(int quietPeriod) {
822
        return scheduleBuild2(quietPeriod, new LegacyCodeCause());
M
mdonohue 已提交
823 824
    }
    
K
kohsuke 已提交
825
    /**
826 827
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
K
kohsuke 已提交
828
     */
K
kohsuke 已提交
829
    public Future<R> scheduleBuild2(int quietPeriod, Cause c) {
830 831 832
        return scheduleBuild2(quietPeriod, c, new Action[0]);
    }

833 834 835 836
    /**
     * Schedules a polling of this project.
     */
    public boolean schedulePolling() {
837
        if(isDisabled())    return false;
838
        SCMTrigger scmt = getTrigger(SCMTrigger.class);
839
        if(scmt==null)      return false;
840 841 842 843
        scmt.run();
        return true;
    }

844 845 846 847 848
    /**
     * Returns true if the build is in the queue.
     */
    @Override
    public boolean isInQueue() {
849
        return Hudson.getInstance().getQueue().contains(this);
850 851
    }

K
kohsuke 已提交
852 853 854 855 856
    @Override
    public Queue.Item getQueueItem() {
        return Hudson.getInstance().getQueue().getItem(this);
    }

K
kohsuke 已提交
857 858 859
    /**
     * Gets the JDK that this project is configured with, or null.
     */
860
    public JDK getJDK() {
861
        return Hudson.getInstance().getJDK(jdk);
862 863 864 865 866
    }

    /**
     * Overwrites the JDK setting.
     */
K
kohsuke 已提交
867
    public void setJDK(JDK jdk) throws IOException {
868 869 870 871
        this.jdk = jdk.getName();
        save();
    }

872 873
    public BuildAuthorizationToken getAuthToken() {
        return authToken;
874 875
    }

876
    @Override
877 878 879 880
    public SortedMap<Integer, ? extends R> _getRuns() {
        return builds.getView();
    }

881
    @Override
882 883 884 885
    public void removeRun(R run) {
        this.builds.remove(run);
    }

886 887 888 889 890
    /**
     * Determines Class&lt;R>.
     */
    protected abstract Class<R> getBuildClass();

H
huybrechts 已提交
891
    // keep track of the previous time we started a build
892
    private transient long lastBuildStartTime;
H
huybrechts 已提交
893
    
894 895 896
    /**
     * Creates a new build of this project for immediate execution.
     */
H
huybrechts 已提交
897 898 899 900 901 902 903 904 905 906 907
    protected synchronized R newBuild() throws IOException {
    	// make sure we don't start two builds in the same second
    	// so the build directories will be different too
    	long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
    	if (timeSinceLast < 1000) {
    		try {
				Thread.sleep(1000 - timeSinceLast);
			} catch (InterruptedException e) {
			}
    	}
    	lastBuildStartTime = System.currentTimeMillis();
908
        try {
909
            R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
910 911 912 913 914 915 916
            builds.put(lastBuild);
            return lastBuild;
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
917
            throw handleInvocationTargetException(e);
918 919 920 921
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
922

923
    private IOException handleInvocationTargetException(InvocationTargetException e) {
924
        Throwable t = e.getTargetException();
925 926 927
        if(t instanceof Error)  throw (Error)t;
        if(t instanceof RuntimeException)   throw (RuntimeException)t;
        if(t instanceof IOException)    return (IOException)t;
928 929 930
        throw new Error(t);
    }

931 932 933
    /**
     * Loads an existing build record from disk.
     */
934 935
    protected R loadBuild(File dir) throws IOException {
        try {
936
            return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
937 938 939 940 941
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
942
            throw handleInvocationTargetException(e);
943 944 945 946
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
947

K
kohsuke 已提交
948 949
    /**
     * {@inheritDoc}
950
     *
K
kohsuke 已提交
951 952
     * <p>
     * Note that this method returns a read-only view of {@link Action}s.
953
     * {@link BuildStep}s and others who want to add a project action
954
     * should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.
955 956
     *
     * @see TransientProjectActionFactory
K
kohsuke 已提交
957
     */
958
    @Override
959 960 961 962
    public synchronized List<Action> getActions() {
        // add all the transient actions, too
        List<Action> actions = new Vector<Action>(super.getActions());
        actions.addAll(transientActions);
963
        // return the read only list to cause a failure on plugins who try to add an action here
K
kohsuke 已提交
964
        return Collections.unmodifiableList(actions);
965 966
    }

967 968
    /**
     * Gets the {@link Node} where this project was last built on.
969 970 971 972
     *
     * @return
     *      null if no information is available (for example,
     *      if no build was done yet.)
973 974 975 976
     */
    public Node getLastBuiltOn() {
        // where was it built on?
        AbstractBuild b = getLastBuild();
977
        if(b==null)
978 979 980 981 982
            return null;
        else
            return b.getBuiltOn();
    }

983 984 985 986
    public Object getSameNodeConstraint() {
        return this; // in this way, any member that wants to run with the main guy can nominate the project itself 
    }

987 988 989 990
    public final Task getOwnerTask() {
        return this;
    }

991
    /**
992
     * {@inheritDoc}
993
     *
994
     * <p>
995
     * A project must be blocked if its own previous build is in progress,
996 997
     * or if the blockBuildWhenUpstreamBuilding option is true and an upstream
     * project is building, but derived classes can also check other conditions.
998
     */
999
    public boolean isBuildBlocked() {
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        return getCauseOfBlockage()!=null;
    }

    public String getWhyBlocked() {
        CauseOfBlockage cb = getCauseOfBlockage();
        return cb!=null ? cb.getShortDescription() : null;
    }

    /**
     * Blocked because the previous build is already in progress.
     */
    public static class BecauseOfBuildInProgress extends CauseOfBlockage {
        private final AbstractBuild<?,?> build;

        public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {
            this.build = build;
1016 1017
        }

1018
        @Override
1019 1020 1021 1022 1023 1024 1025 1026
        public String getShortDescription() {
            Executor e = build.getExecutor();
            String eta = "";
            if (e != null)
                eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
            int lbn = build.getNumber();
            return Messages.AbstractProject_BuildInProgress(lbn, eta);
        }
1027
    }
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
    
    /**
     * Because the downstream build is in progress, and we are configured to wait for that.
     */
    public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage {
        public final AbstractProject<?,?> up;

        public BecauseOfDownstreamBuildInProgress(AbstractProject<?,?> up) {
            this.up = up;
        }

        @Override
        public String getShortDescription() {
            return Messages.AbstractProject_DownstreamBuildInProgress(up.getName());
        }
    }
1044

1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    /**
     * Because the upstream build is in progress, and we are configured to wait for that.
     */
    public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {
        public final AbstractProject<?,?> up;

        public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {
            this.up = up;
        }

1055
        @Override
1056 1057 1058
        public String getShortDescription() {
            return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
        }
1059 1060
    }

1061 1062 1063
    public CauseOfBlockage getCauseOfBlockage() {
        if (isBuilding() && !isConcurrentBuild())
            return new BecauseOfBuildInProgress(getLastBuild());
1064 1065 1066 1067 1068
        if (blockBuildWhenDownstreamBuilding()) {
            AbstractProject<?,?> bup = getBuildingDownstream();
            if (bup!=null)
                return new BecauseOfDownstreamBuildInProgress(bup);
        } else if (blockBuildWhenUpstreamBuilding()) {
1069 1070 1071 1072 1073 1074
            AbstractProject<?,?> bup = getBuildingUpstream();
            if (bup!=null)
                return new BecauseOfUpstreamBuildInProgress(bup);
        }
        return null;
    }
1075

1076
    /**
1077 1078
     * Returns the project if any of the downstream project is either
     * building, waiting, pending or buildable.
1079 1080 1081 1082 1083
     * <p>
     * This means eventually there will be an automatic triggering of
     * the given project (provided that all builds went smoothly.)
     */
    protected AbstractProject getBuildingDownstream() {
1084 1085 1086 1087
        Set<Task> unblockedTasks = Hudson.getInstance().getQueue().getUnblockedTasks();

        for (AbstractProject tup : Hudson.getInstance().getDependencyGraph().getTransitiveDownstream(this)) {
			if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
1088 1089 1090 1091 1092
                return tup;
        }
        return null;
    }

1093
    /**
1094
     * Returns the project if any of the upstream project is either
1095 1096 1097 1098 1099 1100
     * building or is in the queue.
     * <p>
     * This means eventually there will be an automatic triggering of
     * the given project (provided that all builds went smoothly.)
     */
    protected AbstractProject getBuildingUpstream() {
1101 1102 1103 1104
        Set<Task> unblockedTasks = Hudson.getInstance().getQueue().getUnblockedTasks();

        for (AbstractProject tup : Hudson.getInstance().getDependencyGraph().getTransitiveUpstream(this)) {
			if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))
1105 1106 1107
                return tup;
        }
        return null;
1108 1109
    }

1110 1111
    public List<SubTask> getSubTasks() {
        List<SubTask> r = new ArrayList<SubTask>();
1112
        r.add(this);
1113 1114 1115
        for (SubTaskContributor euc : SubTaskContributor.all())
            r.addAll(euc.forProject(this));
        for (JobProperty<? super P> p : properties)
1116
            r.addAll(p.getSubTasks());
1117
        return r;
1118 1119
    }

1120
    public R createExecutable() throws IOException {
1121
        if(isDisabled())    return null;
1122
        return newBuild();
1123 1124
    }

1125 1126 1127 1128
    public void checkAbortPermission() {
        checkPermission(AbstractProject.ABORT);
    }

K
kohsuke 已提交
1129 1130 1131 1132
    public boolean hasAbortPermission() {
        return hasPermission(AbstractProject.ABORT);
    }

1133 1134
    /**
     * Gets the {@link Resource} that represents the workspace of this project.
1135
     * Useful for locking and mutual exclusion control.
K
kohsuke 已提交
1136
     *
K
kohsuke 已提交
1137
     * @deprecated as of 1.319
K
kohsuke 已提交
1138 1139 1140 1141 1142 1143 1144
     *      Projects no longer have a fixed workspace, ands builds will find an available workspace via
     *      {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)
     *      So a {@link Resource} representation for a workspace at the project level no longer makes sense.
     *
     *      <p>
     *      If you need to lock a workspace while you do some computation, see the source code of
     *      {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.
1145 1146
     */
    public Resource getWorkspaceResource() {
1147
        return new Resource(getFullDisplayName()+" workspace");
1148 1149 1150 1151 1152 1153
    }

    /**
     * List of necessary resources to perform the build of this project.
     */
    public ResourceList getResourceList() {
1154
        final Set<ResourceActivity> resourceActivities = getResourceActivities();
1155
        final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        for (ResourceActivity activity : resourceActivities) {
            if (activity != this && activity != null) {
                // defensive infinite recursion and null check
                resourceLists.add(activity.getResourceList());
            }
        }
        return ResourceList.union(resourceLists);
    }

    /**
1166 1167
     * Set of child resource activities of the build of this project (override in child projects).
     * @return The set of child resource activities of the build of this project.
1168 1169
     */
    protected Set<ResourceActivity> getResourceActivities() {
K
kohsuke 已提交
1170
        return Collections.emptySet();
1171 1172
    }

1173
    public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
1174
        SCM scm = getScm();
1175 1176
        if(scm==null)
            return true;    // no SCM
1177

1178 1179
        FilePath workspace = build.getWorkspace();
        workspace.mkdirs();
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
        
        boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
        calcPollingBaseline(build, launcher, listener);
        return r;
    }

    /**
     * Pushes the baseline up to the newly checked out revision.
     */
    private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
        SCMRevisionState baseline = build.getAction(SCMRevisionState.class);
        if (baseline==null) {
            try {
1193
                baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
            } catch (AbstractMethodError e) {
                baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling
            }
            if (baseline!=null)
                build.addAction(baseline);
        }
        pollingBaseline = baseline;
    }

    /**
     * For reasons I don't understand, if I inline this method, AbstractMethodError escapes try/catch block.
     */
    private SCMRevisionState safeCalcRevisionsFromBuild(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
1207
        return getScm()._calcRevisionsFromBuild(build, launcher, listener);
1208 1209 1210 1211
    }

    /**
     * Checks if there's any update in SCM, and returns true if any is found.
1212
     *
1213 1214
     * @deprecated as of 1.346
     *      Use {@link #poll(TaskListener)} instead.
1215
     */
1216
    public boolean pollSCMChanges( TaskListener listener ) {
1217 1218 1219 1220 1221 1222 1223
        return poll(listener).hasChanges();
    }

    /**
     * Checks if there's any update in SCM, and returns true if any is found.
     *
     * <p>
1224 1225
     * The implementation is responsible for ensuring mutual exclusion between polling and builds
     * if necessary.
1226 1227 1228 1229
     *
     * @since 1.345
     */
    public PollingResult poll( TaskListener listener ) {
1230
        SCM scm = getScm();
1231
        if (scm==null) {
K
i18n  
kohsuke 已提交
1232
            listener.getLogger().println(Messages.AbstractProject_NoSCM());
1233
            return NO_CHANGES;
1234
        }
1235
        if (isDisabled()) {
K
i18n  
kohsuke 已提交
1236
            listener.getLogger().println(Messages.AbstractProject_Disabled());
1237 1238 1239 1240 1241
            return NO_CHANGES;
        }

        R lb = getLastBuild();
        if (lb==null) {
1242
            listener.getLogger().println(Messages.AbstractProject_NoBuilds());
1243
            return isInQueue() ? NO_CHANGES : BUILD_NOW;
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
        }

        if (pollingBaseline==null) {
            R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this
            for (R r=lb; r!=null; r=r.getPreviousBuild()) {
                SCMRevisionState s = r.getAction(SCMRevisionState.class);
                if (s!=null) {
                    pollingBaseline = s;
                    break;
                }
                if (r==success) break;  // searched far enough
            }
            // NOTE-NO-BASELINE:
            // if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline
            // as action, so we need to compute it. This happens later.
1259 1260 1261
        }

        try {
1262
            if (scm.requiresWorkspaceForPolling()) {
K
kohsuke 已提交
1263
                // lock the workspace of the last build
1264
                FilePath ws=lb.getWorkspace();
K
kohsuke 已提交
1265 1266 1267 1268 1269 1270 1271 1272

                if (ws==null || !ws.exists()) {
                    // workspace offline. build now, or nothing will ever be built
                    Label label = getAssignedLabel();
                    if (label != null && label.isSelfLabel()) {
                        // if the build is fixed on a node, then attempting a build will do us
                        // no good. We should just wait for the slave to come back.
                        listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
1273
                        return NO_CHANGES;
K
kohsuke 已提交
1274
                    }
1275 1276 1277
                    listener.getLogger().println( ws==null
                        ? Messages.AbstractProject_WorkspaceOffline()
                        : Messages.AbstractProject_NoWorkspace());
1278 1279 1280 1281 1282 1283 1284
                    if (isInQueue()) {
                        listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());
                        return NO_CHANGES;
                    } else {
                        listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace());
                        return BUILD_NOW;
                    }
K
kohsuke 已提交
1285 1286
                } else {
                    WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
1287
                    // if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
1288 1289 1290 1291 1292
                    // this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
                    //
                    // OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
                    // so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
                    // by having multiple workspaces
1293
                    WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
1294
                    Launcher launcher = ws.createLauncher(listener);
K
kohsuke 已提交
1295 1296
                    try {
                        LOGGER.fine("Polling SCM changes of " + getName());
1297 1298 1299 1300 1301
                        if (pollingBaseline==null) // see NOTE-NO-BASELINE above
                            calcPollingBaseline(lb,launcher,listener);
                        PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);
                        pollingBaseline = r.remote;
                        return r;
K
kohsuke 已提交
1302
                    } finally {
1303
                        lease.release();
K
kohsuke 已提交
1304
                    }
K
kohsuke 已提交
1305
                }
K
kohsuke 已提交
1306 1307 1308
            } else {
                // polling without workspace
                LOGGER.fine("Polling SCM changes of " + getName());
1309 1310 1311 1312 1313 1314

                if (pollingBaseline==null) // see NOTE-NO-BASELINE above
                    calcPollingBaseline(lb,null,listener);
                PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
                pollingBaseline = r.remote;
                return r;
K
kohsuke 已提交
1315
            }
1316
        } catch (AbortException e) {
1317
            listener.getLogger().println(e.getMessage());
K
i18n  
kohsuke 已提交
1318
            listener.fatalError(Messages.AbstractProject_Aborted());
1319
            LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
1320
            return NO_CHANGES;
1321 1322
        } catch (IOException e) {
            e.printStackTrace(listener.fatalError(e.getMessage()));
1323
            return NO_CHANGES;
1324
        } catch (InterruptedException e) {
1325
            e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
1326
            return NO_CHANGES;
1327 1328 1329
        }
    }

1330 1331
    /**
     * Returns true if this user has made a commit to this project.
1332
     *
1333 1334 1335
     * @since 1.191
     */
    public boolean hasParticipant(User user) {
1336 1337
        for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
            if(build.hasParticipant(user))
1338 1339 1340 1341
                return true;
        return false;
    }

1342
    @Exported
1343 1344 1345 1346
    public SCM getScm() {
        return scm;
    }

1347
    public void setScm(SCM scm) throws IOException {
1348
        this.scm = scm;
1349
        save();
1350 1351
    }

1352 1353 1354
    /**
     * Adds a new {@link Trigger} to this {@link Project} if not active yet.
     */
1355
    public void addTrigger(Trigger<?> trigger) throws IOException {
1356
        addToList(trigger,triggers);
1357 1358
    }

1359
    public void removeTrigger(TriggerDescriptor trigger) throws IOException {
1360
        removeFromList(trigger,triggers);
1361 1362
    }

1363 1364 1365 1366
    protected final synchronized <T extends Describable<T>>
    void addToList( T item, List<T> collection ) throws IOException {
        for( int i=0; i<collection.size(); i++ ) {
            if(collection.get(i).getDescriptor()==item.getDescriptor()) {
1367
                // replace
1368
                collection.set(i,item);
1369 1370 1371 1372 1373 1374 1375
                save();
                return;
            }
        }
        // add
        collection.add(item);
        save();
1376
        updateTransientActions();
1377 1378
    }

1379 1380 1381 1382
    protected final synchronized <T extends Describable<T>>
    void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
        for( int i=0; i< collection.size(); i++ ) {
            if(collection.get(i).getDescriptor()==item) {
1383 1384 1385
                // found it
                collection.remove(i);
                save();
1386
                updateTransientActions();
1387 1388 1389 1390 1391
                return;
            }
        }
    }

1392 1393
    public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
        return (Map)Descriptor.toMap(triggers);
1394 1395
    }

1396
    /**
1397
     * Gets the specific trigger, or null if the propert is not configured for this job.
1398 1399 1400
     */
    public <T extends Trigger> T getTrigger(Class<T> clazz) {
        for (Trigger p : triggers) {
1401
            if(clazz.isInstance(p))
1402 1403 1404 1405 1406
                return clazz.cast(p);
        }
        return null;
    }

1407 1408 1409 1410 1411
//
//
// fingerprint related
//
//
1412 1413 1414 1415 1416 1417
    /**
     * True if the builds of this project produces {@link Fingerprint} records.
     */
    public abstract boolean isFingerprintConfigured();

    /**
1418 1419
     * Gets the other {@link AbstractProject}s that should be built
     * when a build of this project is completed.
1420
     */
K
kohsuke 已提交
1421
    @Exported
1422 1423 1424
    public final List<AbstractProject> getDownstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getDownstream(this);
    }
1425

K
kohsuke 已提交
1426
    @Exported
1427 1428
    public final List<AbstractProject> getUpstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getUpstream(this);
K
kohsuke 已提交
1429 1430
    }

K
kohsuke 已提交
1431
    /**
1432 1433 1434 1435
     * Returns only those upstream projects that defines {@link BuildTrigger} to this project.
     * This is a subset of {@link #getUpstreamProjects()}
     *
     * @return A List of upstream projects that has a {@link BuildTrigger} to this project.
K
kohsuke 已提交
1436 1437 1438
     */
    public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
        ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
1439 1440
        for (AbstractProject<?,?> ap : getUpstreamProjects()) {
            BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
1441 1442 1443
            if (buildTrigger != null)
                if (buildTrigger.getChildProjects().contains(this))
                    result.add(ap);
1444
        }        
K
kohsuke 已提交
1445
        return result;
1446 1447
    }    
    
K
kohsuke 已提交
1448 1449
    /**
     * Gets all the upstream projects including transitive upstream projects.
1450
     *
K
kohsuke 已提交
1451 1452 1453
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveUpstreamProjects() {
1454
        return Hudson.getInstance().getDependencyGraph().getTransitiveUpstream(this);
K
kohsuke 已提交
1455 1456 1457
    }

    /**
1458 1459
     * Gets all the downstream projects including transitive downstream projects.
     *
K
kohsuke 已提交
1460 1461 1462
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveDownstreamProjects() {
1463
        return Hudson.getInstance().getDependencyGraph().getTransitiveDownstream(this);
1464 1465 1466 1467 1468
    }

    /**
     * Gets the dependency relationship map between this project (as the source)
     * and that project (as the sink.)
1469 1470 1471 1472
     *
     * @return
     *      can be empty but not null. build number of this project to the build
     *      numbers of that project.
1473 1474
     */
    public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
1475
        TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
1476 1477 1478 1479 1480 1481 1482 1483 1484

        checkAndRecord(that, r, this.getBuilds());
        // checkAndRecord(that, r, that.getBuilds());

        return r;
    }

    /**
     * Helper method for getDownstreamRelationship.
1485 1486
     *
     * For each given build, find the build number range of the given project and put that into the map.
1487
     */
1488
    private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
1489 1490
        for (R build : builds) {
            RangeSet rs = build.getDownstreamRelationship(that);
1491
            if(rs==null || rs.isEmpty())
1492 1493 1494 1495 1496
                continue;

            int n = build.getNumber();

            RangeSet value = r.get(n);
1497 1498
            if(value==null)
                r.put(n,rs);
1499 1500 1501 1502 1503
            else
                value.add(rs);
        }
    }

1504 1505 1506 1507 1508 1509
    /**
     * Builds the dependency graph.
     * @see DependencyGraph
     */
    protected abstract void buildDependencyGraph(DependencyGraph graph);

1510
    @Override
K
kohsuke 已提交
1511 1512
    protected SearchIndexBuilder makeSearchIndex() {
        SearchIndexBuilder sib = super.makeSearchIndex();
1513
        if(isBuildable() && hasPermission(Hudson.ADMINISTER))
1514
            sib.add("build","build");
K
kohsuke 已提交
1515 1516 1517
        return sib;
    }

1518 1519
    @Override
    protected HistoryWidget createHistoryWidget() {
1520
        return new BuildHistoryWidget<R>(this,getBuilds(),HISTORY_ADAPTER);
1521
    }
1522
    
K
kohsuke 已提交
1523
    public boolean isParameterized() {
1524
        return getProperty(ParametersDefinitionProperty.class) != null;
K
kohsuke 已提交
1525
    }
1526

1527 1528 1529 1530 1531
//
//
// actions
//
//
1532 1533 1534
    /**
     * Schedules a new build command.
     */
1535
    public void doBuild( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1536
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
1537

K
kohsuke 已提交
1538 1539 1540
        // if a build is parameterized, let that take over
        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
1541
            pp._doBuild(req,rsp);
K
kohsuke 已提交
1542 1543 1544
            return;
        }

1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
        if (!isBuildable())
            throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));

        Hudson.getInstance().getQueue().schedule(this, getDelay(req), getBuildCause(req));
        rsp.forwardToPreviousPage(req);
    }

    /**
     * Computes the build cause, using RemoteCause or UserCause as appropriate.
     */
    /*package*/ CauseAction getBuildCause(StaplerRequest req) {
1556 1557
        Cause cause;
        if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
1558 1559
            // Optional additional cause text when starting via token
            String causeText = req.getParameter("cause");
1560
            cause = new RemoteCause(req.getRemoteAddr(), causeText);
1561 1562 1563
        } else {
            cause = new UserCause();
        }
1564
        return new CauseAction(cause);
1565 1566 1567 1568 1569 1570
    }

    /**
     * Computes the delay by taking the default value and the override in the request parameter into the account.
     */
    public int getDelay(StaplerRequest req) throws ServletException {
1571
        String delay = req.getParameter("delay");
1572 1573 1574 1575 1576 1577 1578 1579 1580
        if (delay==null)    return getQuietPeriod();

        try {
            // TODO: more unit handling
            if(delay.endsWith("sec"))   delay=delay.substring(0,delay.length()-3);
            if(delay.endsWith("secs"))  delay=delay.substring(0,delay.length()-4);
            return Integer.parseInt(delay);
        } catch (NumberFormatException e) {
            throw new ServletException("Invalid delay parameter value: "+delay);
1581
        }
1582
    }
1583

1584 1585 1586 1587
    /**
     * Supports build trigger with parameters via an HTTP GET or POST.
     * Currently only String parameters are supported.
     */
1588
    public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);

        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
            pp.buildWithParameters(req,rsp);
        } else {
        	throw new IllegalStateException("This build is not parameterized!");
        }
    	
    }
1599 1600 1601 1602

    /**
     * Schedules a new SCM polling command.
     */
1603
    public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1604 1605 1606
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
        schedulePolling();
        rsp.forwardToPreviousPage(req);
1607 1608 1609 1610 1611
    }

    /**
     * Cancels a scheduled build.
     */
1612
    public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1613
        checkPermission(BUILD);
1614

1615
        Hudson.getInstance().getQueue().cancel(this);
1616 1617 1618
        rsp.forwardToPreviousPage(req);
    }

1619
    @Override
1620 1621
    protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
        super.submit(req,rsp);
1622

1623
        makeDisabled(req.getParameter("disable")!=null);
1624 1625

        jdk = req.getParameter("jdk");
1626
        if(req.getParameter("hasCustomQuietPeriod")!=null) {
1627 1628 1629 1630
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
        } else {
            quietPeriod = null;
        }
1631 1632
        if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) {
            scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount"));
S
 
shinodkm 已提交
1633
        } else {
1634
            scmCheckoutRetryCount = null;
S
 
shinodkm 已提交
1635
        }
1636
        blockBuildWhenDownstreamBuilding = req.getParameter("blockBuildWhenDownstreamBuilding")!=null;
1637 1638
        blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null;

1639
        if(req.getParameter("hasSlaveAffinity")!=null) {
1640
            assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString"));
1641 1642 1643
        } else {
            assignedNode = null;
        }
1644
        canRoam = assignedNode==null;
1645

1646
        concurrentBuild = req.getSubmittedForm().has("concurrentBuild");
K
kohsuke 已提交
1647

1648
        authToken = BuildAuthorizationToken.create(req);
1649

K
kohsuke 已提交
1650
        setScm(SCMS.parseSCM(req,this));
1651 1652 1653

        for (Trigger t : triggers)
            t.stop();
1654
        triggers = buildDescribable(req, Trigger.for_(this));
1655
        for (Trigger t : triggers)
1656
            t.start(this,true);
1657 1658
    }

K
kohsuke 已提交
1659 1660 1661 1662 1663 1664 1665 1666 1667
    /**
     * @deprecated
     *      As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
     */
    protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
        return buildDescribable(req,descriptors);
    }

    protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
1668
        throws FormException, ServletException {
1669

1670
        JSONObject data = req.getSubmittedForm();
1671
        List<T> r = new Vector<T>();
1672
        for (Descriptor<T> d : descriptors) {
1673 1674 1675
            String safeName = d.getJsonSafeClassName();
            if (req.getParameter(safeName) != null) {
                T instance = d.newInstance(req, data.getJSONObject(safeName));
1676
                r.add(instance);
1677 1678
            }
        }
1679
        return r;
1680 1681 1682 1683 1684
    }

    /**
     * Serves the workspace files.
     */
1685
    public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
1686
        checkPermission(AbstractProject.WORKSPACE);
K
kohsuke 已提交
1687
        FilePath ws = getSomeWorkspace();
1688
        if ((ws == null) || (!ws.exists())) {
1689
            // if there's no workspace, report a nice error message
1690 1691 1692 1693
            // Would be good if when asked for *plain*, do something else!
            // (E.g. return 404, or send empty doc.)
            // Not critical; client can just check if content type is not text/plain,
            // which also serves to detect old versions of Hudson.
1694
            req.getView(this,"noWorkspace.jelly").forward(req,rsp);
1695
            return null;
1696
        } else {
1697
            return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.gif", true);
1698 1699
        }
    }
1700

1701 1702 1703
    /**
     * Wipes out the workspace.
     */
1704
    public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
1705
        checkPermission(BUILD);
1706 1707 1708 1709
        R b = getSomeBuildWithWorkspace();
        FilePath ws = b!=null ? b.getWorkspace() : null;
        if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
            ws.deleteRecursive();
1710 1711 1712 1713
            return new HttpRedirect(".");
        } else {
            // If we get here, that means the SCM blocked the workspace deletion.
            return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
1714
        }
1715 1716
    }

1717
    @CLIMethod(name="disable-job")
1718
    public HttpResponse doDisable() throws IOException, ServletException {
1719 1720 1721
        requirePOST();
        checkPermission(CONFIGURE);
        makeDisabled(true);
1722
        return new HttpRedirect(".");
1723 1724
    }

1725
    @CLIMethod(name="enable-job")
1726
    public HttpResponse doEnable() throws IOException, ServletException {
1727
        requirePOST();
1728 1729
        checkPermission(CONFIGURE);
        makeDisabled(false);
1730
        return new HttpRedirect(".");
1731 1732
    }

K
kohsuke 已提交
1733 1734 1735
    /**
     * RSS feed for changes in this project.
     */
1736
    public void doRssChangelog(  StaplerRequest req, StaplerResponse rsp  ) throws IOException, ServletException {
K
kohsuke 已提交
1737 1738 1739 1740 1741 1742 1743 1744 1745
        class FeedItem {
            ChangeLogSet.Entry e;
            int idx;

            public FeedItem(Entry e, int idx) {
                this.e = e;
                this.idx = idx;
            }

1746
            AbstractBuild<?,?> getBuild() {
K
kohsuke 已提交
1747 1748 1749 1750 1751 1752
                return e.getParent().build;
            }
        }

        List<FeedItem> entries = new ArrayList<FeedItem>();

1753 1754 1755 1756
        for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
            int idx=0;
            for( ChangeLogSet.Entry e : r.getChangeSet())
                entries.add(new FeedItem(e,idx++));
K
kohsuke 已提交
1757 1758
        }

1759 1760 1761 1762 1763 1764 1765
        RSS.forwardToRss(
            getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
            getUrl()+"changes",
            entries, new FeedAdapter<FeedItem>() {
                public String getEntryTitle(FeedItem item) {
                    return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
                }
K
kohsuke 已提交
1766

1767 1768 1769
                public String getEntryUrl(FeedItem item) {
                    return item.getBuild().getUrl()+"changes#detail"+item.idx;
                }
K
kohsuke 已提交
1770

1771 1772 1773
                public String getEntryID(FeedItem item) {
                    return getEntryUrl(item);
                }
K
kohsuke 已提交
1774

1775 1776 1777 1778 1779 1780
                public String getEntryDescription(FeedItem item) {
                    StringBuilder buf = new StringBuilder();
                    for(String path : item.e.getAffectedPaths())
                        buf.append(path).append('\n');
                    return buf.toString();
                }
1781

1782 1783 1784
                public Calendar getEntryTimestamp(FeedItem item) {
                    return item.getBuild().getTimestamp();
                }
1785

1786
                public String getEntryAuthor(FeedItem entry) {
1787
                    return Mailer.descriptor().getAdminAddress();
1788 1789 1790
                }
            },
            req, rsp );
K
kohsuke 已提交
1791 1792
    }

1793 1794 1795 1796 1797 1798 1799
    /**
     * {@link AbstractProject} subtypes should implement this base class as a descriptor.
     *
     * @since 1.294
     */
    public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
        /**
1800
         * {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
1801
         * from showing up on their configuration screen. This is often useful when you are building
1802 1803
         * a workflow/company specific project type, where you want to limit the number of choices
         * given to the users.
1804 1805
         *
         * <p>
1806 1807 1808 1809
         * Some {@link Descriptor}s define their own schemes for controlling applicability
         * (such as {@link BuildStepDescriptor#isApplicable(Class)}),
         * This method works like AND in conjunction with them;
         * Both this method and that method need to return true in order for a given {@link Descriptor}
1810 1811 1812 1813
         * to show up for the given {@link Project}.
         *
         * <p>
         * The default implementation returns true for everything.
1814 1815
         *
         * @see BuildStepDescriptor#isApplicable(Class) 
K
kohsuke 已提交
1816 1817
         * @see BuildWrapperDescriptor#isApplicable(AbstractProject) 
         * @see TriggerDescriptor#isApplicable(Item)
1818
         */
K
kohsuke 已提交
1819
        @Override
1820
        public boolean isApplicable(Descriptor descriptor) {
1821 1822
            return true;
        }
1823 1824

        public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {
1825 1826
            if (Util.fixEmpty(value)==null)
                return FormValidation.ok(); // nothing typed yet
1827 1828 1829
            try {
                Label.parseExpression(value);
            } catch (ANTLRException e) {
S
Seiji Sogabe 已提交
1830 1831
                return FormValidation.error(e,
                        Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
1832 1833
            }
            // TODO: if there's an atom in the expression that is empty, report it
1834
            if (Hudson.getInstance().getLabel(value).isEmpty())
S
Seiji Sogabe 已提交
1835
                return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());
1836 1837
            return FormValidation.ok();
        }
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894

       public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) {
            AutoCompletionCandidates c = new AutoCompletionCandidates();
            Set<Label> labels = Hudson.getInstance().getLabels();
            List<String> queries = new AutoCompleteSeeder(value).getSeeds();

            for (String term : queries) {
                for (Label l : labels) {
                    if (l.getName().startsWith(term)) {
                        c.add(l.getName());
                    }
                }
            }
            return c;
        }

        /**
        * Utility class for taking the current input value and computing a list
        * of potential terms to match against the list of defined labels.
         */
        static class AutoCompleteSeeder {
            private String source;
            private Pattern quoteMatcher = Pattern.compile("(\\\"?)(.+?)(\\\"?+)(\\s*)");

            AutoCompleteSeeder(String source) {
                this.source = source;
            }

            List<String> getSeeds() {
                ArrayList<String> terms = new ArrayList();
                boolean trailingQuote = source.endsWith("\"");
                boolean leadingQuote = source.startsWith("\"");
                boolean trailingSpace = source.endsWith(" ");

                if (trailingQuote || (trailingSpace && !leadingQuote)) {
                    terms.add("");
                } else {
                    if (leadingQuote) {
                        int quote = source.lastIndexOf('"');
                        if (quote == 0) {
                            terms.add(source.substring(1));
                        } else {
                            terms.add("");
                        }
                    } else {
                        int space = source.lastIndexOf(' ');
                        if (space > -1) {
                            terms.add(source.substring(space+1));
                        } else {
                            terms.add(source);
                        }
                    }
                }

                return terms;
            }
        }
1895 1896
    }

1897
    /**
1898
     * Finds a {@link AbstractProject} that has the name closest to the given name.
1899 1900
     */
    public static AbstractProject findNearest(String name) {
1901
        List<AbstractProject> projects = Hudson.getInstance().getItems(AbstractProject.class);
1902
        String[] names = new String[projects.size()];
1903
        for( int i=0; i<projects.size(); i++ )
1904 1905 1906
            names[i] = projects.get(i).getName();

        String nearest = EditDistance.findNearest(name, names);
1907
        return (AbstractProject)Hudson.getInstance().getItem(nearest);
1908
    }
1909 1910 1911

    private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
1912
            return o2-o1;
1913 1914
        }
    };
1915

1916
    private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
1917

1918
    /**
1919
     * Permission to abort a build. For now, let's make it the same as {@link #BUILD}
1920 1921
     */
    public static final Permission ABORT = BUILD;
1922

K
Kohsuke Kawaguchi 已提交
1923 1924 1925
    /**
     * Replaceable "Build Now" text.
     */
1926 1927
    public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();

1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
    /**
     * Used for CLI binding.
     */
    @CLIResolver
    public static AbstractProject resolveForCLI(
            @Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException {
        AbstractProject item = Hudson.getInstance().getItemByFullName(name, AbstractProject.class);
        if (item==null)
            throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));
        return item;
    }
1939
}